blob: 39083894f794061cd0bd6a92eb168640dc205434 [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: {
618 try {
619 PackageHelper.getMountService().finishMediaUpdate();
620 } catch (RemoteException e) {
621 Log.e(TAG, "MountService not running?");
622 }
623 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700624 case WRITE_SETTINGS: {
625 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
626 synchronized (mPackages) {
627 removeMessages(WRITE_SETTINGS);
628 mSettings.writeLP();
629 }
630 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
631 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700632 }
633 }
634 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800635
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700636 void scheduleWriteSettingsLocked() {
637 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
638 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
639 }
640 }
641
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800642 static boolean installOnSd(int flags) {
643 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700644 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800645 return false;
646 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700647 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
648 return true;
649 }
650 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800651 }
652
653 static boolean isFwdLocked(int flags) {
654 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
655 return true;
656 }
657 return false;
658 }
659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 public static final IPackageManager main(Context context, boolean factoryTest) {
661 PackageManagerService m = new PackageManagerService(context, factoryTest);
662 ServiceManager.addService("package", m);
663 return m;
664 }
665
666 static String[] splitString(String str, char sep) {
667 int count = 1;
668 int i = 0;
669 while ((i=str.indexOf(sep, i)) >= 0) {
670 count++;
671 i++;
672 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 String[] res = new String[count];
675 i=0;
676 count = 0;
677 int lastI=0;
678 while ((i=str.indexOf(sep, i)) >= 0) {
679 res[count] = str.substring(lastI, i);
680 count++;
681 i++;
682 lastI = i;
683 }
684 res[count] = str.substring(lastI, str.length());
685 return res;
686 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800689 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800693 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 mContext = context;
697 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700698 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 mMetrics = new DisplayMetrics();
700 mSettings = new Settings();
701 mSettings.addSharedUserLP("android.uid.system",
702 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
703 mSettings.addSharedUserLP("android.uid.phone",
704 MULTIPLE_APPLICATION_UIDS
705 ? RADIO_UID : FIRST_APPLICATION_UID,
706 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400707 mSettings.addSharedUserLP("android.uid.log",
708 MULTIPLE_APPLICATION_UIDS
709 ? LOG_UID : FIRST_APPLICATION_UID,
710 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711
712 String separateProcesses = SystemProperties.get("debug.separate_processes");
713 if (separateProcesses != null && separateProcesses.length() > 0) {
714 if ("*".equals(separateProcesses)) {
715 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
716 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800717 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 } else {
719 mDefParseFlags = 0;
720 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800721 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 + separateProcesses);
723 }
724 } else {
725 mDefParseFlags = 0;
726 mSeparateProcesses = null;
727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 Installer installer = new Installer();
730 // Little hacky thing to check if installd is here, to determine
731 // whether we are running on the simulator and thus need to take
732 // care of building the /data file structure ourself.
733 // (apparently the sim now has a working installer)
734 if (installer.ping() && Process.supportsProcesses()) {
735 mInstaller = installer;
736 } else {
737 mInstaller = null;
738 }
739
740 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
741 Display d = wm.getDefaultDisplay();
742 d.getMetrics(mMetrics);
743
744 synchronized (mInstallLock) {
745 synchronized (mPackages) {
746 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700747 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 File dataDir = Environment.getDataDirectory();
750 mAppDataDir = new File(dataDir, "data");
751 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
752
753 if (mInstaller == null) {
754 // Make sure these dirs exist, when we are running in
755 // the simulator.
756 // Make a wide-open directory for random misc stuff.
757 File miscDir = new File(dataDir, "misc");
758 miscDir.mkdirs();
759 mAppDataDir.mkdirs();
760 mDrmAppPrivateInstallDir.mkdirs();
761 }
762
763 readPermissions();
764
765 mRestoredSettings = mSettings.readLP();
766 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800767
768 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800770
Suchi Amalapurapudaec1722010-01-14 21:25:16 -0800771 // Set flag to monitor and not change apk file paths when
772 // scanning install directories.
773 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700774 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800775 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800776 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700782 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700785 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 /**
788 * Out of paranoia, ensure that everything in the boot class
789 * path has been dexed.
790 */
791 String bootClassPath = System.getProperty("java.boot.class.path");
792 if (bootClassPath != null) {
793 String[] paths = splitString(bootClassPath, ':');
794 for (int i=0; i<paths.length; i++) {
795 try {
796 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
797 libFiles.add(paths[i]);
798 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700799 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 }
801 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800802 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800804 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 }
806 }
807 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800808 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 /**
812 * Also ensure all external libraries have had dexopt run on them.
813 */
814 if (mSharedLibraries.size() > 0) {
815 Iterator<String> libs = mSharedLibraries.values().iterator();
816 while (libs.hasNext()) {
817 String lib = libs.next();
818 try {
819 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
820 libFiles.add(lib);
821 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700822 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 }
824 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800825 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800827 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
829 }
830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 // Gross hack for now: we know this file doesn't contain any
833 // code, so don't dexopt it to avoid the resulting log spew.
834 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 /**
837 * And there are a number of commands implemented in Java, which
838 * we currently need to do the dexopt on so that they can be
839 * run from a non-root shell.
840 */
841 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700842 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 for (int i=0; i<frameworkFiles.length; i++) {
844 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
845 String path = libPath.getPath();
846 // Skip the file if we alrady did it.
847 if (libFiles.contains(path)) {
848 continue;
849 }
850 // Skip the file if it is not a type we want to dexopt.
851 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
852 continue;
853 }
854 try {
855 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
856 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700857 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 }
859 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800860 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800862 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
864 }
865 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800866
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700867 if (didDexOpt) {
868 // If we had to do a dexopt of one of the previous
869 // things, then something on the system has changed.
870 // Consider this significant, and wipe away all other
871 // existing dexopt files to ensure we don't leave any
872 // dangling around.
873 String[] files = mDalvikCacheDir.list();
874 if (files != null) {
875 for (int i=0; i<files.length; i++) {
876 String fn = files[i];
877 if (fn.startsWith("data@app@")
878 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800879 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700880 (new File(mDalvikCacheDir, fn)).delete();
881 }
882 }
883 }
884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800886
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800887 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 mFrameworkInstallObserver = new AppDirObserver(
889 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
890 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700891 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
892 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec1722010-01-14 21:25:16 -0800893 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800894
895 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
897 mSystemInstallObserver = new AppDirObserver(
898 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
899 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700900 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
901 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800902
903 if (mInstaller != null) {
904 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
905 mInstaller.moveFiles();
906 }
907
908 // Prune any system packages that no longer exist.
909 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
910 while (psit.hasNext()) {
911 PackageSetting ps = psit.next();
912 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800913 && !mPackages.containsKey(ps.name)
914 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800915 psit.remove();
916 String msg = "System package " + ps.name
917 + " no longer exists; wiping its data";
918 reportSettingsProblem(Log.WARN, msg);
919 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700920 mInstaller.remove(ps.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800921 }
922 }
923 }
924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 mAppInstallDir = new File(dataDir, "app");
926 if (mInstaller == null) {
927 // Make sure these dirs exist, when we are running in
928 // the simulator.
929 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
930 }
931 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800932 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 //clean up list
934 for(int i = 0; i < deletePkgsList.size(); i++) {
935 //clean up here
936 cleanupInstallFailedPackage(deletePkgsList.get(i));
937 }
938 //delete tmp files
939 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800940
941 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 SystemClock.uptimeMillis());
943 mAppInstallObserver = new AppDirObserver(
944 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
945 mAppInstallObserver.startWatching();
946 scanDirLI(mAppInstallDir, 0, scanMode);
947
948 mDrmAppInstallObserver = new AppDirObserver(
949 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
950 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800951 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800953 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800955 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 + ((SystemClock.uptimeMillis()-startTime)/1000f)
957 + " seconds");
958
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700959 // If the platform SDK has changed since the last time we booted,
960 // we need to re-grant app permission to catch any new ones that
961 // appear. This is really a hack, and means that apps can in some
962 // cases get permissions that the user didn't initially explicitly
963 // allow... it would be nice to have some better way to handle
964 // this situation.
965 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
966 != mSdkVersion;
967 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
968 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
969 + "; regranting permissions for internal storage");
970 mSettings.mInternalSdkPlatform = mSdkVersion;
971
972 updatePermissionsLP(null, null, true, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973
974 mSettings.writeLP();
975
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800976 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 // Now after opening every single application zip, make sure they
980 // are all flushed. Not really needed, but keeps things nice and
981 // tidy.
982 Runtime.getRuntime().gc();
983 } // synchronized (mPackages)
984 } // synchronized (mInstallLock)
985 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 @Override
988 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
989 throws RemoteException {
990 try {
991 return super.onTransact(code, data, reply, flags);
992 } catch (RuntimeException e) {
993 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800994 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 }
996 throw e;
997 }
998 }
999
Dianne Hackborne6620b22010-01-22 14:46:21 -08001000 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001001 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07001003 int retCode = mInstaller.remove(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001005 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001006 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008 } else {
1009 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001010 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 File dataDir = new File(pkg.applicationInfo.dataDir);
1012 dataDir.delete();
1013 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001014 if (ps.codePath != null) {
1015 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001016 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001017 }
1018 }
1019 if (ps.resourcePath != null) {
1020 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001021 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001022 }
1023 }
1024 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 }
1026
1027 void readPermissions() {
1028 // Read permissions from .../etc/permission directory.
1029 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1030 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001031 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 return;
1033 }
1034 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001035 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 return;
1037 }
1038
1039 // Iterate over the files in the directory and scan .xml files
1040 for (File f : libraryDir.listFiles()) {
1041 // We'll read platform.xml last
1042 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1043 continue;
1044 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001047 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 continue;
1049 }
1050 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 continue;
1053 }
1054
1055 readPermissionsFromXml(f);
1056 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1059 final File permFile = new File(Environment.getRootDirectory(),
1060 "etc/permissions/platform.xml");
1061 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001062
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001063 StringBuilder sb = new StringBuilder(128);
1064 sb.append("Libs:");
1065 Iterator<String> it = mSharedLibraries.keySet().iterator();
1066 while (it.hasNext()) {
1067 sb.append(' ');
1068 String name = it.next();
1069 sb.append(name);
1070 sb.append(':');
1071 sb.append(mSharedLibraries.get(name));
1072 }
1073 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001074
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001075 sb.setLength(0);
1076 sb.append("Features:");
1077 it = mAvailableFeatures.keySet().iterator();
1078 while (it.hasNext()) {
1079 sb.append(' ');
1080 sb.append(it.next());
1081 }
1082 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001084
1085 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 FileReader permReader = null;
1087 try {
1088 permReader = new FileReader(permFile);
1089 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001090 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 return;
1092 }
1093
1094 try {
1095 XmlPullParser parser = Xml.newPullParser();
1096 parser.setInput(permReader);
1097
1098 XmlUtils.beginDocument(parser, "permissions");
1099
1100 while (true) {
1101 XmlUtils.nextElement(parser);
1102 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1103 break;
1104 }
1105
1106 String name = parser.getName();
1107 if ("group".equals(name)) {
1108 String gidStr = parser.getAttributeValue(null, "gid");
1109 if (gidStr != null) {
1110 int gid = Integer.parseInt(gidStr);
1111 mGlobalGids = appendInt(mGlobalGids, gid);
1112 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001113 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 + parser.getPositionDescription());
1115 }
1116
1117 XmlUtils.skipCurrentTag(parser);
1118 continue;
1119 } else if ("permission".equals(name)) {
1120 String perm = parser.getAttributeValue(null, "name");
1121 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001122 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 + parser.getPositionDescription());
1124 XmlUtils.skipCurrentTag(parser);
1125 continue;
1126 }
1127 perm = perm.intern();
1128 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 } else if ("assign-permission".equals(name)) {
1131 String perm = parser.getAttributeValue(null, "name");
1132 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001133 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 + parser.getPositionDescription());
1135 XmlUtils.skipCurrentTag(parser);
1136 continue;
1137 }
1138 String uidStr = parser.getAttributeValue(null, "uid");
1139 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001140 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 + parser.getPositionDescription());
1142 XmlUtils.skipCurrentTag(parser);
1143 continue;
1144 }
1145 int uid = Process.getUidForName(uidStr);
1146 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001147 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 + uidStr + "\" at "
1149 + parser.getPositionDescription());
1150 XmlUtils.skipCurrentTag(parser);
1151 continue;
1152 }
1153 perm = perm.intern();
1154 HashSet<String> perms = mSystemPermissions.get(uid);
1155 if (perms == null) {
1156 perms = new HashSet<String>();
1157 mSystemPermissions.put(uid, perms);
1158 }
1159 perms.add(perm);
1160 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 } else if ("library".equals(name)) {
1163 String lname = parser.getAttributeValue(null, "name");
1164 String lfile = parser.getAttributeValue(null, "file");
1165 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001166 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 + parser.getPositionDescription());
1168 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001169 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 + parser.getPositionDescription());
1171 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001172 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001173 mSharedLibraries.put(lname, lfile);
1174 }
1175 XmlUtils.skipCurrentTag(parser);
1176 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001177
Dianne Hackborn49237342009-08-27 20:08:01 -07001178 } else if ("feature".equals(name)) {
1179 String fname = parser.getAttributeValue(null, "name");
1180 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001181 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001182 + parser.getPositionDescription());
1183 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001184 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001185 FeatureInfo fi = new FeatureInfo();
1186 fi.name = fname;
1187 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 }
1189 XmlUtils.skipCurrentTag(parser);
1190 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 } else {
1193 XmlUtils.skipCurrentTag(parser);
1194 continue;
1195 }
1196
1197 }
1198 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001201 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 }
1203 }
1204
1205 void readPermission(XmlPullParser parser, String name)
1206 throws IOException, XmlPullParserException {
1207
1208 name = name.intern();
1209
1210 BasePermission bp = mSettings.mPermissions.get(name);
1211 if (bp == null) {
1212 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1213 mSettings.mPermissions.put(name, bp);
1214 }
1215 int outerDepth = parser.getDepth();
1216 int type;
1217 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1218 && (type != XmlPullParser.END_TAG
1219 || parser.getDepth() > outerDepth)) {
1220 if (type == XmlPullParser.END_TAG
1221 || type == XmlPullParser.TEXT) {
1222 continue;
1223 }
1224
1225 String tagName = parser.getName();
1226 if ("group".equals(tagName)) {
1227 String gidStr = parser.getAttributeValue(null, "gid");
1228 if (gidStr != null) {
1229 int gid = Process.getGidForName(gidStr);
1230 bp.gids = appendInt(bp.gids, gid);
1231 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001232 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 + parser.getPositionDescription());
1234 }
1235 }
1236 XmlUtils.skipCurrentTag(parser);
1237 }
1238 }
1239
1240 static int[] appendInt(int[] cur, int val) {
1241 if (cur == null) {
1242 return new int[] { val };
1243 }
1244 final int N = cur.length;
1245 for (int i=0; i<N; i++) {
1246 if (cur[i] == val) {
1247 return cur;
1248 }
1249 }
1250 int[] ret = new int[N+1];
1251 System.arraycopy(cur, 0, ret, 0, N);
1252 ret[N] = val;
1253 return ret;
1254 }
1255
1256 static int[] appendInts(int[] cur, int[] add) {
1257 if (add == null) return cur;
1258 if (cur == null) return add;
1259 final int N = add.length;
1260 for (int i=0; i<N; i++) {
1261 cur = appendInt(cur, add[i]);
1262 }
1263 return cur;
1264 }
1265
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001266 static int[] removeInt(int[] cur, int val) {
1267 if (cur == null) {
1268 return null;
1269 }
1270 final int N = cur.length;
1271 for (int i=0; i<N; i++) {
1272 if (cur[i] == val) {
1273 int[] ret = new int[N-1];
1274 if (i > 0) {
1275 System.arraycopy(cur, 0, ret, 0, i);
1276 }
1277 if (i < (N-1)) {
1278 System.arraycopy(cur, i, ret, i+1, N-i-1);
1279 }
1280 return ret;
1281 }
1282 }
1283 return cur;
1284 }
1285
1286 static int[] removeInts(int[] cur, int[] rem) {
1287 if (rem == null) return cur;
1288 if (cur == null) return cur;
1289 final int N = rem.length;
1290 for (int i=0; i<N; i++) {
1291 cur = removeInt(cur, rem[i]);
1292 }
1293 return cur;
1294 }
1295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001297 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1298 // The package has been uninstalled but has retained data and resources.
1299 return PackageParser.generatePackageInfo(p, null, flags);
1300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 final PackageSetting ps = (PackageSetting)p.mExtras;
1302 if (ps == null) {
1303 return null;
1304 }
1305 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1306 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1307 }
1308
1309 public PackageInfo getPackageInfo(String packageName, int flags) {
1310 synchronized (mPackages) {
1311 PackageParser.Package p = mPackages.get(packageName);
1312 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001313 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 + ": " + p);
1315 if (p != null) {
1316 return generatePackageInfo(p, flags);
1317 }
1318 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1319 return generatePackageInfoFromSettingsLP(packageName, flags);
1320 }
1321 }
1322 return null;
1323 }
1324
Dianne Hackborn47096932010-02-11 15:57:09 -08001325 public String[] currentToCanonicalPackageNames(String[] names) {
1326 String[] out = new String[names.length];
1327 synchronized (mPackages) {
1328 for (int i=names.length-1; i>=0; i--) {
1329 PackageSetting ps = mSettings.mPackages.get(names[i]);
1330 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1331 }
1332 }
1333 return out;
1334 }
1335
1336 public String[] canonicalToCurrentPackageNames(String[] names) {
1337 String[] out = new String[names.length];
1338 synchronized (mPackages) {
1339 for (int i=names.length-1; i>=0; i--) {
1340 String cur = mSettings.mRenamedPackages.get(names[i]);
1341 out[i] = cur != null ? cur : names[i];
1342 }
1343 }
1344 return out;
1345 }
1346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 public int getPackageUid(String packageName) {
1348 synchronized (mPackages) {
1349 PackageParser.Package p = mPackages.get(packageName);
1350 if(p != null) {
1351 return p.applicationInfo.uid;
1352 }
1353 PackageSetting ps = mSettings.mPackages.get(packageName);
1354 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1355 return -1;
1356 }
1357 p = ps.pkg;
1358 return p != null ? p.applicationInfo.uid : -1;
1359 }
1360 }
1361
1362 public int[] getPackageGids(String packageName) {
1363 synchronized (mPackages) {
1364 PackageParser.Package p = mPackages.get(packageName);
1365 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001366 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 + ": " + p);
1368 if (p != null) {
1369 final PackageSetting ps = (PackageSetting)p.mExtras;
1370 final SharedUserSetting suid = ps.sharedUser;
1371 return suid != null ? suid.gids : ps.gids;
1372 }
1373 }
1374 // stupid thing to indicate an error.
1375 return new int[0];
1376 }
1377
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001378 static final PermissionInfo generatePermissionInfo(
1379 BasePermission bp, int flags) {
1380 if (bp.perm != null) {
1381 return PackageParser.generatePermissionInfo(bp.perm, flags);
1382 }
1383 PermissionInfo pi = new PermissionInfo();
1384 pi.name = bp.name;
1385 pi.packageName = bp.sourcePackage;
1386 pi.nonLocalizedLabel = bp.name;
1387 pi.protectionLevel = bp.protectionLevel;
1388 return pi;
1389 }
1390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 public PermissionInfo getPermissionInfo(String name, int flags) {
1392 synchronized (mPackages) {
1393 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001394 if (p != null) {
1395 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
1397 return null;
1398 }
1399 }
1400
1401 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1402 synchronized (mPackages) {
1403 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1404 for (BasePermission p : mSettings.mPermissions.values()) {
1405 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001406 if (p.perm == null || p.perm.info.group == null) {
1407 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
1409 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001410 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1412 }
1413 }
1414 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 if (out.size() > 0) {
1417 return out;
1418 }
1419 return mPermissionGroups.containsKey(group) ? out : null;
1420 }
1421 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1424 synchronized (mPackages) {
1425 return PackageParser.generatePermissionGroupInfo(
1426 mPermissionGroups.get(name), flags);
1427 }
1428 }
1429
1430 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1431 synchronized (mPackages) {
1432 final int N = mPermissionGroups.size();
1433 ArrayList<PermissionGroupInfo> out
1434 = new ArrayList<PermissionGroupInfo>(N);
1435 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1436 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1437 }
1438 return out;
1439 }
1440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1443 PackageSetting ps = mSettings.mPackages.get(packageName);
1444 if(ps != null) {
1445 if(ps.pkg == null) {
1446 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1447 if(pInfo != null) {
1448 return pInfo.applicationInfo;
1449 }
1450 return null;
1451 }
1452 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1453 }
1454 return null;
1455 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1458 PackageSetting ps = mSettings.mPackages.get(packageName);
1459 if(ps != null) {
1460 if(ps.pkg == null) {
1461 ps.pkg = new PackageParser.Package(packageName);
1462 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001463 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1464 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1465 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1466 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
1468 return generatePackageInfo(ps.pkg, flags);
1469 }
1470 return null;
1471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1474 synchronized (mPackages) {
1475 PackageParser.Package p = mPackages.get(packageName);
1476 if (Config.LOGV) Log.v(
1477 TAG, "getApplicationInfo " + packageName
1478 + ": " + p);
1479 if (p != null) {
1480 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001481 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
1483 if ("android".equals(packageName)||"system".equals(packageName)) {
1484 return mAndroidApplication;
1485 }
1486 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1487 return generateApplicationInfoFromSettingsLP(packageName, flags);
1488 }
1489 }
1490 return null;
1491 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001492
1493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1495 mContext.enforceCallingOrSelfPermission(
1496 android.Manifest.permission.CLEAR_APP_CACHE, null);
1497 // Queue up an async operation since clearing cache may take a little while.
1498 mHandler.post(new Runnable() {
1499 public void run() {
1500 mHandler.removeCallbacks(this);
1501 int retCode = -1;
1502 if (mInstaller != null) {
1503 retCode = mInstaller.freeCache(freeStorageSize);
1504 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001505 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507 } //end if mInstaller
1508 if (observer != null) {
1509 try {
1510 observer.onRemoveCompleted(null, (retCode >= 0));
1511 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001512 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 }
1514 }
1515 }
1516 });
1517 }
1518
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001519 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001520 mContext.enforceCallingOrSelfPermission(
1521 android.Manifest.permission.CLEAR_APP_CACHE, null);
1522 // Queue up an async operation since clearing cache may take a little while.
1523 mHandler.post(new Runnable() {
1524 public void run() {
1525 mHandler.removeCallbacks(this);
1526 int retCode = -1;
1527 if (mInstaller != null) {
1528 retCode = mInstaller.freeCache(freeStorageSize);
1529 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001530 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001531 }
1532 }
1533 if(pi != null) {
1534 try {
1535 // Callback via pending intent
1536 int code = (retCode >= 0) ? 1 : 0;
1537 pi.sendIntent(null, code, null,
1538 null, null);
1539 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001540 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001541 }
1542 }
1543 }
1544 });
1545 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1548 synchronized (mPackages) {
1549 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001550
1551 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001553 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 }
1555 if (mResolveComponentName.equals(component)) {
1556 return mResolveActivity;
1557 }
1558 }
1559 return null;
1560 }
1561
1562 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1563 synchronized (mPackages) {
1564 PackageParser.Activity a = mReceivers.mActivities.get(component);
1565 if (Config.LOGV) Log.v(
1566 TAG, "getReceiverInfo " + component + ": " + a);
1567 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1568 return PackageParser.generateActivityInfo(a, flags);
1569 }
1570 }
1571 return null;
1572 }
1573
1574 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1575 synchronized (mPackages) {
1576 PackageParser.Service s = mServices.mServices.get(component);
1577 if (Config.LOGV) Log.v(
1578 TAG, "getServiceInfo " + component + ": " + s);
1579 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1580 return PackageParser.generateServiceInfo(s, flags);
1581 }
1582 }
1583 return null;
1584 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 public String[] getSystemSharedLibraryNames() {
1587 Set<String> libSet;
1588 synchronized (mPackages) {
1589 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001590 int size = libSet.size();
1591 if (size > 0) {
1592 String[] libs = new String[size];
1593 libSet.toArray(libs);
1594 return libs;
1595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001597 return null;
1598 }
1599
1600 public FeatureInfo[] getSystemAvailableFeatures() {
1601 Collection<FeatureInfo> featSet;
1602 synchronized (mPackages) {
1603 featSet = mAvailableFeatures.values();
1604 int size = featSet.size();
1605 if (size > 0) {
1606 FeatureInfo[] features = new FeatureInfo[size+1];
1607 featSet.toArray(features);
1608 FeatureInfo fi = new FeatureInfo();
1609 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1610 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1611 features[size] = fi;
1612 return features;
1613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 }
1615 return null;
1616 }
1617
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001618 public boolean hasSystemFeature(String name) {
1619 synchronized (mPackages) {
1620 return mAvailableFeatures.containsKey(name);
1621 }
1622 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 public int checkPermission(String permName, String pkgName) {
1625 synchronized (mPackages) {
1626 PackageParser.Package p = mPackages.get(pkgName);
1627 if (p != null && p.mExtras != null) {
1628 PackageSetting ps = (PackageSetting)p.mExtras;
1629 if (ps.sharedUser != null) {
1630 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1631 return PackageManager.PERMISSION_GRANTED;
1632 }
1633 } else if (ps.grantedPermissions.contains(permName)) {
1634 return PackageManager.PERMISSION_GRANTED;
1635 }
1636 }
1637 }
1638 return PackageManager.PERMISSION_DENIED;
1639 }
1640
1641 public int checkUidPermission(String permName, int uid) {
1642 synchronized (mPackages) {
1643 Object obj = mSettings.getUserIdLP(uid);
1644 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001645 GrantedPermissions gp = (GrantedPermissions)obj;
1646 if (gp.grantedPermissions.contains(permName)) {
1647 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 } else {
1650 HashSet<String> perms = mSystemPermissions.get(uid);
1651 if (perms != null && perms.contains(permName)) {
1652 return PackageManager.PERMISSION_GRANTED;
1653 }
1654 }
1655 }
1656 return PackageManager.PERMISSION_DENIED;
1657 }
1658
1659 private BasePermission findPermissionTreeLP(String permName) {
1660 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1661 if (permName.startsWith(bp.name) &&
1662 permName.length() > bp.name.length() &&
1663 permName.charAt(bp.name.length()) == '.') {
1664 return bp;
1665 }
1666 }
1667 return null;
1668 }
1669
1670 private BasePermission checkPermissionTreeLP(String permName) {
1671 if (permName != null) {
1672 BasePermission bp = findPermissionTreeLP(permName);
1673 if (bp != null) {
1674 if (bp.uid == Binder.getCallingUid()) {
1675 return bp;
1676 }
1677 throw new SecurityException("Calling uid "
1678 + Binder.getCallingUid()
1679 + " is not allowed to add to permission tree "
1680 + bp.name + " owned by uid " + bp.uid);
1681 }
1682 }
1683 throw new SecurityException("No permission tree found for " + permName);
1684 }
1685
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001686 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1687 if (s1 == null) {
1688 return s2 == null;
1689 }
1690 if (s2 == null) {
1691 return false;
1692 }
1693 if (s1.getClass() != s2.getClass()) {
1694 return false;
1695 }
1696 return s1.equals(s2);
1697 }
1698
1699 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1700 if (pi1.icon != pi2.icon) return false;
1701 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1702 if (!compareStrings(pi1.name, pi2.name)) return false;
1703 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1704 // We'll take care of setting this one.
1705 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1706 // These are not currently stored in settings.
1707 //if (!compareStrings(pi1.group, pi2.group)) return false;
1708 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1709 //if (pi1.labelRes != pi2.labelRes) return false;
1710 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1711 return true;
1712 }
1713
1714 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1715 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1716 throw new SecurityException("Label must be specified in permission");
1717 }
1718 BasePermission tree = checkPermissionTreeLP(info.name);
1719 BasePermission bp = mSettings.mPermissions.get(info.name);
1720 boolean added = bp == null;
1721 boolean changed = true;
1722 if (added) {
1723 bp = new BasePermission(info.name, tree.sourcePackage,
1724 BasePermission.TYPE_DYNAMIC);
1725 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1726 throw new SecurityException(
1727 "Not allowed to modify non-dynamic permission "
1728 + info.name);
1729 } else {
1730 if (bp.protectionLevel == info.protectionLevel
1731 && bp.perm.owner.equals(tree.perm.owner)
1732 && bp.uid == tree.uid
1733 && comparePermissionInfos(bp.perm.info, info)) {
1734 changed = false;
1735 }
1736 }
1737 bp.protectionLevel = info.protectionLevel;
1738 bp.perm = new PackageParser.Permission(tree.perm.owner,
1739 new PermissionInfo(info));
1740 bp.perm.info.packageName = tree.perm.info.packageName;
1741 bp.uid = tree.uid;
1742 if (added) {
1743 mSettings.mPermissions.put(info.name, bp);
1744 }
1745 if (changed) {
1746 if (!async) {
1747 mSettings.writeLP();
1748 } else {
1749 scheduleWriteSettingsLocked();
1750 }
1751 }
1752 return added;
1753 }
1754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 public boolean addPermission(PermissionInfo info) {
1756 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001757 return addPermissionLocked(info, false);
1758 }
1759 }
1760
1761 public boolean addPermissionAsync(PermissionInfo info) {
1762 synchronized (mPackages) {
1763 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 }
1765 }
1766
1767 public void removePermission(String name) {
1768 synchronized (mPackages) {
1769 checkPermissionTreeLP(name);
1770 BasePermission bp = mSettings.mPermissions.get(name);
1771 if (bp != null) {
1772 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1773 throw new SecurityException(
1774 "Not allowed to modify non-dynamic permission "
1775 + name);
1776 }
1777 mSettings.mPermissions.remove(name);
1778 mSettings.writeLP();
1779 }
1780 }
1781 }
1782
Dianne Hackborn854060af2009-07-09 18:14:31 -07001783 public boolean isProtectedBroadcast(String actionName) {
1784 synchronized (mPackages) {
1785 return mProtectedBroadcasts.contains(actionName);
1786 }
1787 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 public int checkSignatures(String pkg1, String pkg2) {
1790 synchronized (mPackages) {
1791 PackageParser.Package p1 = mPackages.get(pkg1);
1792 PackageParser.Package p2 = mPackages.get(pkg2);
1793 if (p1 == null || p1.mExtras == null
1794 || p2 == null || p2.mExtras == null) {
1795 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1796 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001797 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 }
1799 }
1800
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001801 public int checkUidSignatures(int uid1, int uid2) {
1802 synchronized (mPackages) {
1803 Signature[] s1;
1804 Signature[] s2;
1805 Object obj = mSettings.getUserIdLP(uid1);
1806 if (obj != null) {
1807 if (obj instanceof SharedUserSetting) {
1808 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1809 } else if (obj instanceof PackageSetting) {
1810 s1 = ((PackageSetting)obj).signatures.mSignatures;
1811 } else {
1812 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1813 }
1814 } else {
1815 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1816 }
1817 obj = mSettings.getUserIdLP(uid2);
1818 if (obj != null) {
1819 if (obj instanceof SharedUserSetting) {
1820 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1821 } else if (obj instanceof PackageSetting) {
1822 s2 = ((PackageSetting)obj).signatures.mSignatures;
1823 } else {
1824 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1825 }
1826 } else {
1827 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1828 }
1829 return checkSignaturesLP(s1, s2);
1830 }
1831 }
1832
1833 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1834 if (s1 == null) {
1835 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1837 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1838 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001839 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1841 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001842 HashSet<Signature> set1 = new HashSet<Signature>();
1843 for (Signature sig : s1) {
1844 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001846 HashSet<Signature> set2 = new HashSet<Signature>();
1847 for (Signature sig : s2) {
1848 set2.add(sig);
1849 }
1850 // Make sure s2 contains all signatures in s1.
1851 if (set1.equals(set2)) {
1852 return PackageManager.SIGNATURE_MATCH;
1853 }
1854 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
1856
1857 public String[] getPackagesForUid(int uid) {
1858 synchronized (mPackages) {
1859 Object obj = mSettings.getUserIdLP(uid);
1860 if (obj instanceof SharedUserSetting) {
1861 SharedUserSetting sus = (SharedUserSetting)obj;
1862 final int N = sus.packages.size();
1863 String[] res = new String[N];
1864 Iterator<PackageSetting> it = sus.packages.iterator();
1865 int i=0;
1866 while (it.hasNext()) {
1867 res[i++] = it.next().name;
1868 }
1869 return res;
1870 } else if (obj instanceof PackageSetting) {
1871 PackageSetting ps = (PackageSetting)obj;
1872 return new String[] { ps.name };
1873 }
1874 }
1875 return null;
1876 }
1877
1878 public String getNameForUid(int uid) {
1879 synchronized (mPackages) {
1880 Object obj = mSettings.getUserIdLP(uid);
1881 if (obj instanceof SharedUserSetting) {
1882 SharedUserSetting sus = (SharedUserSetting)obj;
1883 return sus.name + ":" + sus.userId;
1884 } else if (obj instanceof PackageSetting) {
1885 PackageSetting ps = (PackageSetting)obj;
1886 return ps.name;
1887 }
1888 }
1889 return null;
1890 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 public int getUidForSharedUser(String sharedUserName) {
1893 if(sharedUserName == null) {
1894 return -1;
1895 }
1896 synchronized (mPackages) {
1897 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1898 if(suid == null) {
1899 return -1;
1900 }
1901 return suid.userId;
1902 }
1903 }
1904
1905 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1906 int flags) {
1907 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001908 return chooseBestActivity(intent, resolvedType, flags, query);
1909 }
1910
Mihai Predaeae850c2009-05-13 10:13:48 +02001911 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1912 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 if (query != null) {
1914 final int N = query.size();
1915 if (N == 1) {
1916 return query.get(0);
1917 } else if (N > 1) {
1918 // If there is more than one activity with the same priority,
1919 // then let the user decide between them.
1920 ResolveInfo r0 = query.get(0);
1921 ResolveInfo r1 = query.get(1);
1922 if (false) {
1923 System.out.println(r0.activityInfo.name +
1924 "=" + r0.priority + " vs " +
1925 r1.activityInfo.name +
1926 "=" + r1.priority);
1927 }
1928 // If the first activity has a higher priority, or a different
1929 // default, then it is always desireable to pick it.
1930 if (r0.priority != r1.priority
1931 || r0.preferredOrder != r1.preferredOrder
1932 || r0.isDefault != r1.isDefault) {
1933 return query.get(0);
1934 }
1935 // If we have saved a preference for a preferred activity for
1936 // this Intent, use that.
1937 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1938 flags, query, r0.priority);
1939 if (ri != null) {
1940 return ri;
1941 }
1942 return mResolveInfo;
1943 }
1944 }
1945 return null;
1946 }
1947
1948 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1949 int flags, List<ResolveInfo> query, int priority) {
1950 synchronized (mPackages) {
1951 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1952 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001953 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1955 if (prefs != null && prefs.size() > 0) {
1956 // First figure out how good the original match set is.
1957 // We will only allow preferred activities that came
1958 // from the same match quality.
1959 int match = 0;
1960 final int N = query.size();
1961 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1962 for (int j=0; j<N; j++) {
1963 ResolveInfo ri = query.get(j);
1964 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1965 + ": 0x" + Integer.toHexString(match));
1966 if (ri.match > match) match = ri.match;
1967 }
1968 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1969 + Integer.toHexString(match));
1970 match &= IntentFilter.MATCH_CATEGORY_MASK;
1971 final int M = prefs.size();
1972 for (int i=0; i<M; i++) {
1973 PreferredActivity pa = prefs.get(i);
1974 if (pa.mMatch != match) {
1975 continue;
1976 }
1977 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1978 if (DEBUG_PREFERRED) {
1979 Log.v(TAG, "Got preferred activity:");
1980 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1981 }
1982 if (ai != null) {
1983 for (int j=0; j<N; j++) {
1984 ResolveInfo ri = query.get(j);
1985 if (!ri.activityInfo.applicationInfo.packageName
1986 .equals(ai.applicationInfo.packageName)) {
1987 continue;
1988 }
1989 if (!ri.activityInfo.name.equals(ai.name)) {
1990 continue;
1991 }
1992
1993 // Okay we found a previously set preferred app.
1994 // If the result set is different from when this
1995 // was created, we need to clear it and re-ask the
1996 // user their preference.
1997 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001998 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 + intent + " type " + resolvedType);
2000 mSettings.mPreferredActivities.removeFilter(pa);
2001 return null;
2002 }
2003
2004 // Yay!
2005 return ri;
2006 }
2007 }
2008 }
2009 }
2010 }
2011 return null;
2012 }
2013
2014 public List<ResolveInfo> queryIntentActivities(Intent intent,
2015 String resolvedType, int flags) {
2016 ComponentName comp = intent.getComponent();
2017 if (comp != null) {
2018 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2019 ActivityInfo ai = getActivityInfo(comp, flags);
2020 if (ai != null) {
2021 ResolveInfo ri = new ResolveInfo();
2022 ri.activityInfo = ai;
2023 list.add(ri);
2024 }
2025 return list;
2026 }
2027
2028 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002029 String pkgName = intent.getPackage();
2030 if (pkgName == null) {
2031 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2032 resolvedType, flags);
2033 }
2034 PackageParser.Package pkg = mPackages.get(pkgName);
2035 if (pkg != null) {
2036 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2037 resolvedType, flags, pkg.activities);
2038 }
2039 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 }
2041 }
2042
2043 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2044 Intent[] specifics, String[] specificTypes, Intent intent,
2045 String resolvedType, int flags) {
2046 final String resultsAction = intent.getAction();
2047
2048 List<ResolveInfo> results = queryIntentActivities(
2049 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2050 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2051
2052 int specificsPos = 0;
2053 int N;
2054
2055 // todo: note that the algorithm used here is O(N^2). This
2056 // isn't a problem in our current environment, but if we start running
2057 // into situations where we have more than 5 or 10 matches then this
2058 // should probably be changed to something smarter...
2059
2060 // First we go through and resolve each of the specific items
2061 // that were supplied, taking care of removing any corresponding
2062 // duplicate items in the generic resolve list.
2063 if (specifics != null) {
2064 for (int i=0; i<specifics.length; i++) {
2065 final Intent sintent = specifics[i];
2066 if (sintent == null) {
2067 continue;
2068 }
2069
2070 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2071 String action = sintent.getAction();
2072 if (resultsAction != null && resultsAction.equals(action)) {
2073 // If this action was explicitly requested, then don't
2074 // remove things that have it.
2075 action = null;
2076 }
2077 ComponentName comp = sintent.getComponent();
2078 ResolveInfo ri = null;
2079 ActivityInfo ai = null;
2080 if (comp == null) {
2081 ri = resolveIntent(
2082 sintent,
2083 specificTypes != null ? specificTypes[i] : null,
2084 flags);
2085 if (ri == null) {
2086 continue;
2087 }
2088 if (ri == mResolveInfo) {
2089 // ACK! Must do something better with this.
2090 }
2091 ai = ri.activityInfo;
2092 comp = new ComponentName(ai.applicationInfo.packageName,
2093 ai.name);
2094 } else {
2095 ai = getActivityInfo(comp, flags);
2096 if (ai == null) {
2097 continue;
2098 }
2099 }
2100
2101 // Look for any generic query activities that are duplicates
2102 // of this specific one, and remove them from the results.
2103 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2104 N = results.size();
2105 int j;
2106 for (j=specificsPos; j<N; j++) {
2107 ResolveInfo sri = results.get(j);
2108 if ((sri.activityInfo.name.equals(comp.getClassName())
2109 && sri.activityInfo.applicationInfo.packageName.equals(
2110 comp.getPackageName()))
2111 || (action != null && sri.filter.matchAction(action))) {
2112 results.remove(j);
2113 if (Config.LOGV) Log.v(
2114 TAG, "Removing duplicate item from " + j
2115 + " due to specific " + specificsPos);
2116 if (ri == null) {
2117 ri = sri;
2118 }
2119 j--;
2120 N--;
2121 }
2122 }
2123
2124 // Add this specific item to its proper place.
2125 if (ri == null) {
2126 ri = new ResolveInfo();
2127 ri.activityInfo = ai;
2128 }
2129 results.add(specificsPos, ri);
2130 ri.specificIndex = i;
2131 specificsPos++;
2132 }
2133 }
2134
2135 // Now we go through the remaining generic results and remove any
2136 // duplicate actions that are found here.
2137 N = results.size();
2138 for (int i=specificsPos; i<N-1; i++) {
2139 final ResolveInfo rii = results.get(i);
2140 if (rii.filter == null) {
2141 continue;
2142 }
2143
2144 // Iterate over all of the actions of this result's intent
2145 // filter... typically this should be just one.
2146 final Iterator<String> it = rii.filter.actionsIterator();
2147 if (it == null) {
2148 continue;
2149 }
2150 while (it.hasNext()) {
2151 final String action = it.next();
2152 if (resultsAction != null && resultsAction.equals(action)) {
2153 // If this action was explicitly requested, then don't
2154 // remove things that have it.
2155 continue;
2156 }
2157 for (int j=i+1; j<N; j++) {
2158 final ResolveInfo rij = results.get(j);
2159 if (rij.filter != null && rij.filter.hasAction(action)) {
2160 results.remove(j);
2161 if (Config.LOGV) Log.v(
2162 TAG, "Removing duplicate item from " + j
2163 + " due to action " + action + " at " + i);
2164 j--;
2165 N--;
2166 }
2167 }
2168 }
2169
2170 // If the caller didn't request filter information, drop it now
2171 // so we don't have to marshall/unmarshall it.
2172 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2173 rii.filter = null;
2174 }
2175 }
2176
2177 // Filter out the caller activity if so requested.
2178 if (caller != null) {
2179 N = results.size();
2180 for (int i=0; i<N; i++) {
2181 ActivityInfo ainfo = results.get(i).activityInfo;
2182 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2183 && caller.getClassName().equals(ainfo.name)) {
2184 results.remove(i);
2185 break;
2186 }
2187 }
2188 }
2189
2190 // If the caller didn't request filter information,
2191 // drop them now so we don't have to
2192 // marshall/unmarshall it.
2193 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2194 N = results.size();
2195 for (int i=0; i<N; i++) {
2196 results.get(i).filter = null;
2197 }
2198 }
2199
2200 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2201 return results;
2202 }
2203
2204 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2205 String resolvedType, int flags) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002206 ComponentName comp = intent.getComponent();
2207 if (comp != null) {
2208 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2209 ActivityInfo ai = getReceiverInfo(comp, flags);
2210 if (ai != null) {
2211 ResolveInfo ri = new ResolveInfo();
2212 ri.activityInfo = ai;
2213 list.add(ri);
2214 }
2215 return list;
2216 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002219 String pkgName = intent.getPackage();
2220 if (pkgName == null) {
2221 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2222 resolvedType, flags);
2223 }
2224 PackageParser.Package pkg = mPackages.get(pkgName);
2225 if (pkg != null) {
2226 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2227 resolvedType, flags, pkg.receivers);
2228 }
2229 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 }
2231 }
2232
2233 public ResolveInfo resolveService(Intent intent, String resolvedType,
2234 int flags) {
2235 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2236 flags);
2237 if (query != null) {
2238 if (query.size() >= 1) {
2239 // If there is more than one service with the same priority,
2240 // just arbitrarily pick the first one.
2241 return query.get(0);
2242 }
2243 }
2244 return null;
2245 }
2246
2247 public List<ResolveInfo> queryIntentServices(Intent intent,
2248 String resolvedType, int flags) {
2249 ComponentName comp = intent.getComponent();
2250 if (comp != null) {
2251 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2252 ServiceInfo si = getServiceInfo(comp, flags);
2253 if (si != null) {
2254 ResolveInfo ri = new ResolveInfo();
2255 ri.serviceInfo = si;
2256 list.add(ri);
2257 }
2258 return list;
2259 }
2260
2261 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002262 String pkgName = intent.getPackage();
2263 if (pkgName == null) {
2264 return (List<ResolveInfo>)mServices.queryIntent(intent,
2265 resolvedType, flags);
2266 }
2267 PackageParser.Package pkg = mPackages.get(pkgName);
2268 if (pkg != null) {
2269 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2270 resolvedType, flags, pkg.services);
2271 }
2272 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 }
2274 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 public List<PackageInfo> getInstalledPackages(int flags) {
2277 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2278
2279 synchronized (mPackages) {
2280 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2281 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2282 while (i.hasNext()) {
2283 final PackageSetting ps = i.next();
2284 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2285 if(psPkg != null) {
2286 finalList.add(psPkg);
2287 }
2288 }
2289 }
2290 else {
2291 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2292 while (i.hasNext()) {
2293 final PackageParser.Package p = i.next();
2294 if (p.applicationInfo != null) {
2295 PackageInfo pi = generatePackageInfo(p, flags);
2296 if(pi != null) {
2297 finalList.add(pi);
2298 }
2299 }
2300 }
2301 }
2302 }
2303 return finalList;
2304 }
2305
2306 public List<ApplicationInfo> getInstalledApplications(int flags) {
2307 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2308 synchronized(mPackages) {
2309 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2310 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2311 while (i.hasNext()) {
2312 final PackageSetting ps = i.next();
2313 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2314 if(ai != null) {
2315 finalList.add(ai);
2316 }
2317 }
2318 }
2319 else {
2320 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2321 while (i.hasNext()) {
2322 final PackageParser.Package p = i.next();
2323 if (p.applicationInfo != null) {
2324 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2325 if(ai != null) {
2326 finalList.add(ai);
2327 }
2328 }
2329 }
2330 }
2331 }
2332 return finalList;
2333 }
2334
2335 public List<ApplicationInfo> getPersistentApplications(int flags) {
2336 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2337
2338 synchronized (mPackages) {
2339 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2340 while (i.hasNext()) {
2341 PackageParser.Package p = i.next();
2342 if (p.applicationInfo != null
2343 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2344 && (!mSafeMode || (p.applicationInfo.flags
2345 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2346 finalList.add(p.applicationInfo);
2347 }
2348 }
2349 }
2350
2351 return finalList;
2352 }
2353
2354 public ProviderInfo resolveContentProvider(String name, int flags) {
2355 synchronized (mPackages) {
2356 final PackageParser.Provider provider = mProviders.get(name);
2357 return provider != null
2358 && mSettings.isEnabledLP(provider.info, flags)
2359 && (!mSafeMode || (provider.info.applicationInfo.flags
2360 &ApplicationInfo.FLAG_SYSTEM) != 0)
2361 ? PackageParser.generateProviderInfo(provider, flags)
2362 : null;
2363 }
2364 }
2365
Fred Quintana718d8a22009-04-29 17:53:20 -07002366 /**
2367 * @deprecated
2368 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 public void querySyncProviders(List outNames, List outInfo) {
2370 synchronized (mPackages) {
2371 Iterator<Map.Entry<String, PackageParser.Provider>> i
2372 = mProviders.entrySet().iterator();
2373
2374 while (i.hasNext()) {
2375 Map.Entry<String, PackageParser.Provider> entry = i.next();
2376 PackageParser.Provider p = entry.getValue();
2377
2378 if (p.syncable
2379 && (!mSafeMode || (p.info.applicationInfo.flags
2380 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2381 outNames.add(entry.getKey());
2382 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2383 }
2384 }
2385 }
2386 }
2387
2388 public List<ProviderInfo> queryContentProviders(String processName,
2389 int uid, int flags) {
2390 ArrayList<ProviderInfo> finalList = null;
2391
2392 synchronized (mPackages) {
2393 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2394 while (i.hasNext()) {
2395 PackageParser.Provider p = i.next();
2396 if (p.info.authority != null
2397 && (processName == null ||
2398 (p.info.processName.equals(processName)
2399 && p.info.applicationInfo.uid == uid))
2400 && mSettings.isEnabledLP(p.info, flags)
2401 && (!mSafeMode || (p.info.applicationInfo.flags
2402 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2403 if (finalList == null) {
2404 finalList = new ArrayList<ProviderInfo>(3);
2405 }
2406 finalList.add(PackageParser.generateProviderInfo(p,
2407 flags));
2408 }
2409 }
2410 }
2411
2412 if (finalList != null) {
2413 Collections.sort(finalList, mProviderInitOrderSorter);
2414 }
2415
2416 return finalList;
2417 }
2418
2419 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2420 int flags) {
2421 synchronized (mPackages) {
2422 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2423 return PackageParser.generateInstrumentationInfo(i, flags);
2424 }
2425 }
2426
2427 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2428 int flags) {
2429 ArrayList<InstrumentationInfo> finalList =
2430 new ArrayList<InstrumentationInfo>();
2431
2432 synchronized (mPackages) {
2433 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2434 while (i.hasNext()) {
2435 PackageParser.Instrumentation p = i.next();
2436 if (targetPackage == null
2437 || targetPackage.equals(p.info.targetPackage)) {
2438 finalList.add(PackageParser.generateInstrumentationInfo(p,
2439 flags));
2440 }
2441 }
2442 }
2443
2444 return finalList;
2445 }
2446
2447 private void scanDirLI(File dir, int flags, int scanMode) {
2448 Log.d(TAG, "Scanning app dir " + dir);
2449
2450 String[] files = dir.list();
2451
2452 int i;
2453 for (i=0; i<files.length; i++) {
2454 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002455 if (!isPackageFilename(files[i])) {
2456 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002457 continue;
2458 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002459 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002461 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002462 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2463 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002464 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002465 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002466 file.delete();
2467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 }
2469 }
2470
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002471 private static File getSettingsProblemFile() {
2472 File dataDir = Environment.getDataDirectory();
2473 File systemDir = new File(dataDir, "system");
2474 File fname = new File(systemDir, "uiderrors.txt");
2475 return fname;
2476 }
2477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 private static void reportSettingsProblem(int priority, String msg) {
2479 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002480 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 FileOutputStream out = new FileOutputStream(fname, true);
2482 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002483 SimpleDateFormat formatter = new SimpleDateFormat();
2484 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2485 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 pw.close();
2487 FileUtils.setPermissions(
2488 fname.toString(),
2489 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2490 -1, -1);
2491 } catch (java.io.IOException e) {
2492 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002493 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 }
2495
2496 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2497 PackageParser.Package pkg, File srcFile, int parseFlags) {
2498 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002499 if (ps != null
2500 && ps.codePath.equals(srcFile)
2501 && ps.getTimeStamp() == srcFile.lastModified()) {
2502 if (ps.signatures.mSignatures != null
2503 && ps.signatures.mSignatures.length != 0) {
2504 // Optimization: reuse the existing cached certificates
2505 // if the package appears to be unchanged.
2506 pkg.mSignatures = ps.signatures.mSignatures;
2507 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 }
Jeff Browne7600722010-04-07 18:28:23 -07002509
2510 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002511 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002512 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2513 }
2514
2515 if (!pp.collectCertificates(pkg, parseFlags)) {
2516 mLastScanError = pp.getParseError();
2517 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 }
2519 }
2520 return true;
2521 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 /*
2524 * Scan a package and return the newly parsed package.
2525 * Returns null in case of errors and the error code is stored in mLastScanError
2526 */
2527 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002528 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002530 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002532 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002535 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 if (pkg == null) {
2537 mLastScanError = pp.getParseError();
2538 return null;
2539 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002540 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 PackageSetting updatedPkg;
2542 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002543 // Look to see if we already know about this package.
2544 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002545 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002546 // This package has been renamed to its original name. Let's
2547 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002548 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002549 }
2550 // If there was no original package, see one for the real package name.
2551 if (ps == null) {
2552 ps = mSettings.peekPackageLP(pkg.packageName);
2553 }
2554 // Check to see if this package could be hiding/updating a system
2555 // package. Must look for it either under the original or real
2556 // package name depending on our state.
2557 updatedPkg = mSettings.mDisabledSysPackages.get(
2558 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002560 // First check if this is a system package that may involve an update
2561 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2562 if (!ps.codePath.equals(scanFile)) {
2563 // The path has changed from what was last scanned... check the
2564 // version of the new path against what we have stored to determine
2565 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002566 if (pkg.mVersionCode < ps.versionCode) {
2567 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002568 // Ignore entry. Skip it.
2569 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2570 + "ignored: updated version " + ps.versionCode
2571 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002572 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2573 return null;
2574 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002575 // The current app on the system partion is better than
2576 // what we have updated to on the data partition; switch
2577 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002578 // At this point, its safely assumed that package installation for
2579 // apps in system partition will go through. If not there won't be a working
2580 // version of the app
2581 synchronized (mPackages) {
2582 // Just remove the loaded entries from package lists.
2583 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002584 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002585 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002586 + "reverting from " + ps.codePathString
2587 + ": new version " + pkg.mVersionCode
2588 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002589 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2590 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002591 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 }
2594 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002595 if (updatedPkg != null) {
2596 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2597 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2598 }
2599 // Verify certificates against what was last scanned
2600 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002601 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002602 return null;
2603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 // The apk is forward locked (not public) if its code and resources
2605 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002606 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002608 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002609 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002610
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002611 String codePath = null;
2612 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002613 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2614 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002615 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002616 } else {
2617 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002618 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002619 }
2620 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002621 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002622 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002623 codePath = pkg.mScanPath;
2624 // Set application objects path explicitly.
2625 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002627 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 }
2629
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002630 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2631 String destCodePath, String destResPath) {
2632 pkg.mPath = pkg.mScanPath = destCodePath;
2633 pkg.applicationInfo.sourceDir = destCodePath;
2634 pkg.applicationInfo.publicSourceDir = destResPath;
2635 }
2636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 private static String fixProcessName(String defProcessName,
2638 String processName, int uid) {
2639 if (processName == null) {
2640 return defProcessName;
2641 }
2642 return processName;
2643 }
2644
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002645 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002646 PackageParser.Package pkg) {
2647 if (pkgSetting.signatures.mSignatures != null) {
2648 // Already existing package. Make sure signatures match
2649 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2650 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002651 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002652 + " signatures do not match the previously installed version; ignoring!");
2653 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 return false;
2655 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002656 }
2657 // Check for shared user signatures
2658 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2659 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2660 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2661 Slog.e(TAG, "Package " + pkg.packageName
2662 + " has no signatures that match those in shared user "
2663 + pkgSetting.sharedUser.name + "; ignoring!");
2664 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2665 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 }
2668 return true;
2669 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002670
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002671 public boolean performDexOpt(String packageName) {
2672 if (!mNoDexOpt) {
2673 return false;
2674 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002675
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002676 PackageParser.Package p;
2677 synchronized (mPackages) {
2678 p = mPackages.get(packageName);
2679 if (p == null || p.mDidDexOpt) {
2680 return false;
2681 }
2682 }
2683 synchronized (mInstallLock) {
2684 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2685 }
2686 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002687
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002688 static final int DEX_OPT_SKIPPED = 0;
2689 static final int DEX_OPT_PERFORMED = 1;
2690 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002691
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002692 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2693 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002694 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002695 String path = pkg.mScanPath;
2696 int ret = 0;
2697 try {
2698 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002699 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002700 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002701 pkg.mDidDexOpt = true;
2702 performed = true;
2703 }
2704 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002705 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002706 ret = -1;
2707 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002708 Slog.w(TAG, "IOException reading apk: " + path, e);
2709 ret = -1;
2710 } catch (dalvik.system.StaleDexCacheError e) {
2711 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2712 ret = -1;
2713 } catch (Exception e) {
2714 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002715 ret = -1;
2716 }
2717 if (ret < 0) {
2718 //error from installer
2719 return DEX_OPT_FAILED;
2720 }
2721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002722
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002723 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2724 }
2725
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002726 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2727 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002728 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002729 + " to " + newPkg.packageName
2730 + ": old package not in system partition");
2731 return false;
2732 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002733 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002734 + " to " + newPkg.packageName
2735 + ": old package still exists");
2736 return false;
2737 }
2738 return true;
2739 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002740
2741 private File getDataPathForPackage(PackageParser.Package pkg) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002742 return new File(mAppDataDir, pkg.packageName);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002743 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002744
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002745 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2746 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002747 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002748 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2749 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002750 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002751 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002752 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2753 return null;
2754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 mScanningPath = scanFile;
2756 if (pkg == null) {
2757 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2758 return null;
2759 }
2760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2762 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2763 }
2764
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002765 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 synchronized (mPackages) {
2767 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002768 Slog.w(TAG, "*************************************************");
2769 Slog.w(TAG, "Core android package being redefined. Skipping.");
2770 Slog.w(TAG, " file=" + mScanningPath);
2771 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2773 return null;
2774 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 // Set up information for our fall-back user intent resolution
2777 // activity.
2778 mPlatformPackage = pkg;
2779 pkg.mVersionCode = mSdkVersion;
2780 mAndroidApplication = pkg.applicationInfo;
2781 mResolveActivity.applicationInfo = mAndroidApplication;
2782 mResolveActivity.name = ResolverActivity.class.getName();
2783 mResolveActivity.packageName = mAndroidApplication.packageName;
2784 mResolveActivity.processName = mAndroidApplication.processName;
2785 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2786 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2787 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2788 mResolveActivity.exported = true;
2789 mResolveActivity.enabled = true;
2790 mResolveInfo.activityInfo = mResolveActivity;
2791 mResolveInfo.priority = 0;
2792 mResolveInfo.preferredOrder = 0;
2793 mResolveInfo.match = 0;
2794 mResolveComponentName = new ComponentName(
2795 mAndroidApplication.packageName, mResolveActivity.name);
2796 }
2797 }
2798
2799 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002800 TAG, "Scanning package " + pkg.packageName);
2801 if (mPackages.containsKey(pkg.packageName)
2802 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002803 Slog.w(TAG, "*************************************************");
2804 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002806 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2808 return null;
2809 }
2810
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002811 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002812 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2813 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 SharedUserSetting suid = null;
2816 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002817
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002818 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2819 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002820 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002821 pkg.mRealPackage = null;
2822 pkg.mAdoptPermissions = null;
2823 }
2824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 synchronized (mPackages) {
2826 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002827 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2828 if (mTmpSharedLibraries == null ||
2829 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2830 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2831 }
2832 int num = 0;
2833 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2834 for (int i=0; i<N; i++) {
2835 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002837 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002839 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2841 return null;
2842 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002843 mTmpSharedLibraries[num] = file;
2844 num++;
2845 }
2846 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2847 for (int i=0; i<N; i++) {
2848 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2849 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002850 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002851 + " desires unavailable shared library "
2852 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2853 } else {
2854 mTmpSharedLibraries[num] = file;
2855 num++;
2856 }
2857 }
2858 if (num > 0) {
2859 pkg.usesLibraryFiles = new String[num];
2860 System.arraycopy(mTmpSharedLibraries, 0,
2861 pkg.usesLibraryFiles, 0, num);
2862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002863
Dianne Hackborn49237342009-08-27 20:08:01 -07002864 if (pkg.reqFeatures != null) {
2865 N = pkg.reqFeatures.size();
2866 for (int i=0; i<N; i++) {
2867 FeatureInfo fi = pkg.reqFeatures.get(i);
2868 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2869 // Don't care.
2870 continue;
2871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002872
Dianne Hackborn49237342009-08-27 20:08:01 -07002873 if (fi.name != null) {
2874 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002875 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002876 + " requires unavailable feature "
2877 + fi.name + "; failing!");
2878 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2879 return null;
2880 }
2881 }
2882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 }
2884 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 if (pkg.mSharedUserId != null) {
2887 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2888 pkg.applicationInfo.flags, true);
2889 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002890 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 + " for shared user failed");
2892 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2893 return null;
2894 }
2895 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2896 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2897 + suid.userId + "): packages=" + suid.packages);
2898 }
2899 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002900
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002901 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002902 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002903 Log.w(TAG, "WAITING FOR DEBUGGER");
2904 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002905 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2906 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002907 }
2908 }
2909
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002910 // Check if we are renaming from an original package name.
2911 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002912 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002913 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002914 // This package may need to be renamed to a previously
2915 // installed name. Let's check on that...
2916 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002917 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002918 // This package had originally been installed as the
2919 // original name, and we have already taken care of
2920 // transitioning to the new one. Just update the new
2921 // one to continue using the old name.
2922 realName = pkg.mRealPackage;
2923 if (!pkg.packageName.equals(renamed)) {
2924 // Callers into this function may have already taken
2925 // care of renaming the package; only do it here if
2926 // it is not already done.
2927 pkg.setPackageName(renamed);
2928 }
2929
Dianne Hackbornc1552392010-03-03 16:19:01 -08002930 } else {
2931 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2932 if ((origPackage=mSettings.peekPackageLP(
2933 pkg.mOriginalPackages.get(i))) != null) {
2934 // We do have the package already installed under its
2935 // original name... should we use it?
2936 if (!verifyPackageUpdate(origPackage, pkg)) {
2937 // New package is not compatible with original.
2938 origPackage = null;
2939 continue;
2940 } else if (origPackage.sharedUser != null) {
2941 // Make sure uid is compatible between packages.
2942 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002943 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002944 + " to " + pkg.packageName + ": old uid "
2945 + origPackage.sharedUser.name
2946 + " differs from " + pkg.mSharedUserId);
2947 origPackage = null;
2948 continue;
2949 }
2950 } else {
2951 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2952 + pkg.packageName + " to old name " + origPackage.name);
2953 }
2954 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002955 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002956 }
2957 }
2958 }
2959
2960 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002961 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002962 + " was transferred to another, but its .apk remains");
2963 }
2964
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002965 // Just create the setting, don't add it yet. For already existing packages
2966 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002967 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 destResourceFile, pkg.applicationInfo.flags, true, false);
2969 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002970 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2972 return null;
2973 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002974
2975 if (pkgSetting.origPackage != null) {
2976 // If we are first transitioning from an original package,
2977 // fix up the new package's name now. We need to do this after
2978 // looking up the package under its new name, so getPackageLP
2979 // can take care of fiddling things correctly.
2980 pkg.setPackageName(origPackage.name);
2981
2982 // File a report about this.
2983 String msg = "New package " + pkgSetting.realName
2984 + " renamed to replace old package " + pkgSetting.name;
2985 reportSettingsProblem(Log.WARN, msg);
2986
2987 // Make a note of it.
2988 mTransferedPackages.add(origPackage.name);
2989
2990 // No longer need to retain this.
2991 pkgSetting.origPackage = null;
2992 }
2993
2994 if (realName != null) {
2995 // Make a note of it.
2996 mTransferedPackages.add(pkg.packageName);
2997 }
2998
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002999 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 pkg.applicationInfo.uid = pkgSetting.userId;
3004 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003005
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003006 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003007 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 return null;
3009 }
3010 // The signature has changed, but this package is in the system
3011 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003012 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 // However... if this package is part of a shared user, but it
3014 // doesn't match the signature of the shared user, let's fail.
3015 // What this means is that you can't change the signatures
3016 // associated with an overall shared user, which doesn't seem all
3017 // that unreasonable.
3018 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003019 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3020 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3021 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003022 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3023 return null;
3024 }
3025 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003026 // File a report about this.
3027 String msg = "System package " + pkg.packageName
3028 + " signature changed; retaining data.";
3029 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003031
The Android Open Source Project10592532009-03-18 17:39:46 -07003032 // Verify that this new package doesn't have any content providers
3033 // that conflict with existing packages. Only do this if the
3034 // package isn't already installed, since we don't want to break
3035 // things that are installed.
3036 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3037 int N = pkg.providers.size();
3038 int i;
3039 for (i=0; i<N; i++) {
3040 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003041 if (p.info.authority != null) {
3042 String names[] = p.info.authority.split(";");
3043 for (int j = 0; j < names.length; j++) {
3044 if (mProviders.containsKey(names[j])) {
3045 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003046 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003047 " (in package " + pkg.applicationInfo.packageName +
3048 ") is already used by "
3049 + ((other != null && other.getComponentName() != null)
3050 ? other.getComponentName().getPackageName() : "?"));
3051 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3052 return null;
3053 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003054 }
3055 }
3056 }
3057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 }
3059
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003060 final String pkgName = pkg.packageName;
3061
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003062 if (pkg.mAdoptPermissions != null) {
3063 // This package wants to adopt ownership of permissions from
3064 // another package.
3065 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3066 String origName = pkg.mAdoptPermissions.get(i);
3067 PackageSetting orig = mSettings.peekPackageLP(origName);
3068 if (orig != null) {
3069 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003070 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003071 + origName + " to " + pkg.packageName);
3072 mSettings.transferPermissions(origName, pkg.packageName);
3073 }
3074 }
3075 }
3076 }
3077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 long scanFileTime = scanFile.lastModified();
3079 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3080 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3081 pkg.applicationInfo.processName = fixProcessName(
3082 pkg.applicationInfo.packageName,
3083 pkg.applicationInfo.processName,
3084 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085
3086 File dataPath;
3087 if (mPlatformPackage == pkg) {
3088 // The system package is special.
3089 dataPath = new File (Environment.getDataDirectory(), "system");
3090 pkg.applicationInfo.dataDir = dataPath.getPath();
3091 } else {
3092 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003093 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003094
3095 boolean uidError = false;
3096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 if (dataPath.exists()) {
3098 mOutPermissions[1] = 0;
3099 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3100 if (mOutPermissions[1] == pkg.applicationInfo.uid
3101 || !Process.supportsProcesses()) {
3102 pkg.applicationInfo.dataDir = dataPath.getPath();
3103 } else {
3104 boolean recovered = false;
3105 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3106 // If this is a system app, we can at least delete its
3107 // current data so the application will still work.
3108 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003109 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003110 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 // Old data gone!
3112 String msg = "System package " + pkg.packageName
3113 + " has changed from uid: "
3114 + mOutPermissions[1] + " to "
3115 + pkg.applicationInfo.uid + "; old data erased";
3116 reportSettingsProblem(Log.WARN, msg);
3117 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 // And now re-install the app.
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003120 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 pkg.applicationInfo.uid);
3122 if (ret == -1) {
3123 // Ack should not happen!
3124 msg = "System package " + pkg.packageName
3125 + " could not have data directory re-created after delete.";
3126 reportSettingsProblem(Log.WARN, msg);
3127 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3128 return null;
3129 }
3130 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 if (!recovered) {
3133 mHasSystemUidErrors = true;
3134 }
3135 }
3136 if (!recovered) {
3137 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3138 + pkg.applicationInfo.uid + "/fs_"
3139 + mOutPermissions[1];
3140 String msg = "Package " + pkg.packageName
3141 + " has mismatched uid: "
3142 + mOutPermissions[1] + " on disk, "
3143 + pkg.applicationInfo.uid + " in settings";
3144 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003145 mSettings.mReadMessages.append(msg);
3146 mSettings.mReadMessages.append('\n');
3147 uidError = true;
3148 if (!pkgSetting.uidError) {
3149 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 }
3152 }
3153 }
3154 pkg.applicationInfo.dataDir = dataPath.getPath();
3155 } else {
3156 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3157 Log.v(TAG, "Want this data dir: " + dataPath);
3158 //invoke installer to do the actual installation
3159 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003160 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 pkg.applicationInfo.uid);
3162 if(ret < 0) {
3163 // Error from installer
3164 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3165 return null;
3166 }
3167 } else {
3168 dataPath.mkdirs();
3169 if (dataPath.exists()) {
3170 FileUtils.setPermissions(
3171 dataPath.toString(),
3172 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3173 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3174 }
3175 }
3176 if (dataPath.exists()) {
3177 pkg.applicationInfo.dataDir = dataPath.getPath();
3178 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003179 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 pkg.applicationInfo.dataDir = null;
3181 }
3182 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003183
3184 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 }
3186
3187 // Perform shared library installation and dex validation and
3188 // optimization, if this is not a system app.
3189 if (mInstaller != null) {
3190 String path = scanFile.getPath();
3191 if (scanFileNewer) {
3192 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003193 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3194 if (err != PackageManager.INSTALL_SUCCEEDED) {
3195 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 return null;
3197 }
3198 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003199 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003200
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003201 if ((scanMode&SCAN_NO_DEX) == 0) {
3202 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3204 return null;
3205 }
3206 }
3207 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 if (mFactoryTest && pkg.requestedPermissions.contains(
3210 android.Manifest.permission.FACTORY_TEST)) {
3211 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3212 }
3213
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003214 // Request the ActivityManager to kill the process(only for existing packages)
3215 // so that we do not end up in a confused state while the user is still using the older
3216 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003217 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003218 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003219 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003220 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003223 // We don't expect installation to fail beyond this point,
3224 if ((scanMode&SCAN_MONITOR) != 0) {
3225 mAppDirs.put(pkg.mPath, pkg);
3226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003228 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003230 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003231 // Make sure we don't accidentally delete its data.
3232 mSettings.mPackagesToBeCleaned.remove(pkgName);
3233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 int N = pkg.providers.size();
3235 StringBuilder r = null;
3236 int i;
3237 for (i=0; i<N; i++) {
3238 PackageParser.Provider p = pkg.providers.get(i);
3239 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3240 p.info.processName, pkg.applicationInfo.uid);
3241 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3242 p.info.name), p);
3243 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003244 if (p.info.authority != null) {
3245 String names[] = p.info.authority.split(";");
3246 p.info.authority = null;
3247 for (int j = 0; j < names.length; j++) {
3248 if (j == 1 && p.syncable) {
3249 // We only want the first authority for a provider to possibly be
3250 // syncable, so if we already added this provider using a different
3251 // authority clear the syncable flag. We copy the provider before
3252 // changing it because the mProviders object contains a reference
3253 // to a provider that we don't want to change.
3254 // Only do this for the second authority since the resulting provider
3255 // object can be the same for all future authorities for this provider.
3256 p = new PackageParser.Provider(p);
3257 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003259 if (!mProviders.containsKey(names[j])) {
3260 mProviders.put(names[j], p);
3261 if (p.info.authority == null) {
3262 p.info.authority = names[j];
3263 } else {
3264 p.info.authority = p.info.authority + ";" + names[j];
3265 }
3266 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3267 Log.d(TAG, "Registered content provider: " + names[j] +
3268 ", className = " + p.info.name +
3269 ", isSyncable = " + p.info.isSyncable);
3270 } else {
3271 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003272 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003273 " (in package " + pkg.applicationInfo.packageName +
3274 "): name already used by "
3275 + ((other != null && other.getComponentName() != null)
3276 ? other.getComponentName().getPackageName() : "?"));
3277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 }
3279 }
3280 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3281 if (r == null) {
3282 r = new StringBuilder(256);
3283 } else {
3284 r.append(' ');
3285 }
3286 r.append(p.info.name);
3287 }
3288 }
3289 if (r != null) {
3290 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3291 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 N = pkg.services.size();
3294 r = null;
3295 for (i=0; i<N; i++) {
3296 PackageParser.Service s = pkg.services.get(i);
3297 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3298 s.info.processName, pkg.applicationInfo.uid);
3299 mServices.addService(s);
3300 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3301 if (r == null) {
3302 r = new StringBuilder(256);
3303 } else {
3304 r.append(' ');
3305 }
3306 r.append(s.info.name);
3307 }
3308 }
3309 if (r != null) {
3310 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 N = pkg.receivers.size();
3314 r = null;
3315 for (i=0; i<N; i++) {
3316 PackageParser.Activity a = pkg.receivers.get(i);
3317 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3318 a.info.processName, pkg.applicationInfo.uid);
3319 mReceivers.addActivity(a, "receiver");
3320 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3321 if (r == null) {
3322 r = new StringBuilder(256);
3323 } else {
3324 r.append(' ');
3325 }
3326 r.append(a.info.name);
3327 }
3328 }
3329 if (r != null) {
3330 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3331 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 N = pkg.activities.size();
3334 r = null;
3335 for (i=0; i<N; i++) {
3336 PackageParser.Activity a = pkg.activities.get(i);
3337 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3338 a.info.processName, pkg.applicationInfo.uid);
3339 mActivities.addActivity(a, "activity");
3340 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3341 if (r == null) {
3342 r = new StringBuilder(256);
3343 } else {
3344 r.append(' ');
3345 }
3346 r.append(a.info.name);
3347 }
3348 }
3349 if (r != null) {
3350 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3351 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 N = pkg.permissionGroups.size();
3354 r = null;
3355 for (i=0; i<N; i++) {
3356 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3357 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3358 if (cur == null) {
3359 mPermissionGroups.put(pg.info.name, pg);
3360 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3361 if (r == null) {
3362 r = new StringBuilder(256);
3363 } else {
3364 r.append(' ');
3365 }
3366 r.append(pg.info.name);
3367 }
3368 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003369 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 + pg.info.packageName + " ignored: original from "
3371 + cur.info.packageName);
3372 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3373 if (r == null) {
3374 r = new StringBuilder(256);
3375 } else {
3376 r.append(' ');
3377 }
3378 r.append("DUP:");
3379 r.append(pg.info.name);
3380 }
3381 }
3382 }
3383 if (r != null) {
3384 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3385 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 N = pkg.permissions.size();
3388 r = null;
3389 for (i=0; i<N; i++) {
3390 PackageParser.Permission p = pkg.permissions.get(i);
3391 HashMap<String, BasePermission> permissionMap =
3392 p.tree ? mSettings.mPermissionTrees
3393 : mSettings.mPermissions;
3394 p.group = mPermissionGroups.get(p.info.group);
3395 if (p.info.group == null || p.group != null) {
3396 BasePermission bp = permissionMap.get(p.info.name);
3397 if (bp == null) {
3398 bp = new BasePermission(p.info.name, p.info.packageName,
3399 BasePermission.TYPE_NORMAL);
3400 permissionMap.put(p.info.name, bp);
3401 }
3402 if (bp.perm == null) {
3403 if (bp.sourcePackage == null
3404 || bp.sourcePackage.equals(p.info.packageName)) {
3405 BasePermission tree = findPermissionTreeLP(p.info.name);
3406 if (tree == null
3407 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003408 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 bp.perm = p;
3410 bp.uid = pkg.applicationInfo.uid;
3411 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3412 if (r == null) {
3413 r = new StringBuilder(256);
3414 } else {
3415 r.append(' ');
3416 }
3417 r.append(p.info.name);
3418 }
3419 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003420 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 + p.info.packageName + " ignored: base tree "
3422 + tree.name + " is from package "
3423 + tree.sourcePackage);
3424 }
3425 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003426 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 + p.info.packageName + " ignored: original from "
3428 + bp.sourcePackage);
3429 }
3430 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3431 if (r == null) {
3432 r = new StringBuilder(256);
3433 } else {
3434 r.append(' ');
3435 }
3436 r.append("DUP:");
3437 r.append(p.info.name);
3438 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003439 if (bp.perm == p) {
3440 bp.protectionLevel = p.info.protectionLevel;
3441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 } 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: no group "
3445 + p.group);
3446 }
3447 }
3448 if (r != null) {
3449 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3450 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 N = pkg.instrumentation.size();
3453 r = null;
3454 for (i=0; i<N; i++) {
3455 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3456 a.info.packageName = pkg.applicationInfo.packageName;
3457 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3458 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3459 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003460 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3462 if (r == null) {
3463 r = new StringBuilder(256);
3464 } else {
3465 r.append(' ');
3466 }
3467 r.append(a.info.name);
3468 }
3469 }
3470 if (r != null) {
3471 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003473
Dianne Hackborn854060af2009-07-09 18:14:31 -07003474 if (pkg.protectedBroadcasts != null) {
3475 N = pkg.protectedBroadcasts.size();
3476 for (i=0; i<N; i++) {
3477 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3478 }
3479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 pkgSetting.setTimeStamp(scanFileTime);
3482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 return pkg;
3485 }
3486
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003487 private void killApplication(String pkgName, int uid) {
3488 // Request the ActivityManager to kill the process(only for existing packages)
3489 // so that we do not end up in a confused state while the user is still using the older
3490 // version of the application while the new one gets installed.
3491 IActivityManager am = ActivityManagerNative.getDefault();
3492 if (am != null) {
3493 try {
3494 am.killApplicationWithUid(pkgName, uid);
3495 } catch (RemoteException e) {
3496 }
3497 }
3498 }
3499
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003500 // The following constants are returned by cachePackageSharedLibsForAbiLI
3501 // to indicate if native shared libraries were found in the package.
3502 // Values are:
3503 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3504 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3505 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3506 // in package (and not installed)
3507 //
3508 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3509 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3510 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003512 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3513 // and automatically copy them to /data/data/<appname>/lib if present.
3514 //
3515 // NOTE: this method may throw an IOException if the library cannot
3516 // be copied to its final destination, e.g. if there isn't enough
3517 // room left on the data partition, or a ZipException if the package
3518 // file is malformed.
3519 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003520 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3521 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003522 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3523 final String apkLib = "lib/";
3524 final int apkLibLen = apkLib.length();
3525 final int cpuAbiLen = cpuAbi.length();
3526 final String libPrefix = "lib";
3527 final int libPrefixLen = libPrefix.length();
3528 final String libSuffix = ".so";
3529 final int libSuffixLen = libSuffix.length();
3530 boolean hasNativeLibraries = false;
3531 boolean installedNativeLibraries = false;
3532
3533 // the minimum length of a valid native shared library of the form
3534 // lib/<something>/lib<name>.so.
3535 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3536
3537 ZipFile zipFile = new ZipFile(scanFile);
3538 Enumeration<ZipEntry> entries =
3539 (Enumeration<ZipEntry>) zipFile.entries();
3540
3541 while (entries.hasMoreElements()) {
3542 ZipEntry entry = entries.nextElement();
3543 // skip directories
3544 if (entry.isDirectory()) {
3545 continue;
3546 }
3547 String entryName = entry.getName();
3548
3549 // check that the entry looks like lib/<something>/lib<name>.so
3550 // here, but don't check the ABI just yet.
3551 //
3552 // - must be sufficiently long
3553 // - must end with libSuffix, i.e. ".so"
3554 // - must start with apkLib, i.e. "lib/"
3555 if (entryName.length() < minEntryLen ||
3556 !entryName.endsWith(libSuffix) ||
3557 !entryName.startsWith(apkLib) ) {
3558 continue;
3559 }
3560
3561 // file name must start with libPrefix, i.e. "lib"
3562 int lastSlash = entryName.lastIndexOf('/');
3563
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003564 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003565 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3566 continue;
3567 }
3568
3569 hasNativeLibraries = true;
3570
3571 // check the cpuAbi now, between lib/ and /lib<name>.so
3572 //
3573 if (lastSlash != apkLibLen + cpuAbiLen ||
3574 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3575 continue;
3576
3577 // extract the library file name, ensure it doesn't contain
3578 // weird characters. we're guaranteed here that it doesn't contain
3579 // a directory separator though.
3580 String libFileName = entryName.substring(lastSlash+1);
3581 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3582 continue;
3583 }
3584
3585 installedNativeLibraries = true;
3586
3587 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3588 File.separator + libFileName;
3589 File sharedLibraryFile = new File(sharedLibraryFilePath);
3590 if (! sharedLibraryFile.exists() ||
3591 sharedLibraryFile.length() != entry.getSize() ||
3592 sharedLibraryFile.lastModified() != entry.getTime()) {
3593 if (Config.LOGD) {
3594 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003596 if (mInstaller == null) {
3597 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003598 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003599 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003600 sharedLibraryFile);
3601 }
3602 }
3603 if (!hasNativeLibraries)
3604 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3605
3606 if (!installedNativeLibraries)
3607 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3608
3609 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3610 }
3611
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003612 // Find the gdbserver executable program in a package at
3613 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3614 //
3615 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3616 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3617 //
3618 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3619 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3620 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3621 final String GDBSERVER = "gdbserver";
3622 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3623
3624 ZipFile zipFile = new ZipFile(scanFile);
3625 Enumeration<ZipEntry> entries =
3626 (Enumeration<ZipEntry>) zipFile.entries();
3627
3628 while (entries.hasMoreElements()) {
3629 ZipEntry entry = entries.nextElement();
3630 // skip directories
3631 if (entry.isDirectory()) {
3632 continue;
3633 }
3634 String entryName = entry.getName();
3635
3636 if (!entryName.equals(apkGdbServerPath)) {
3637 continue;
3638 }
3639
3640 String installGdbServerPath = installGdbServerDir.getPath() +
3641 "/" + GDBSERVER;
3642 File installGdbServerFile = new File(installGdbServerPath);
3643 if (! installGdbServerFile.exists() ||
3644 installGdbServerFile.length() != entry.getSize() ||
3645 installGdbServerFile.lastModified() != entry.getTime()) {
3646 if (Config.LOGD) {
3647 Log.d(TAG, "Caching gdbserver " + entry.getName());
3648 }
3649 if (mInstaller == null) {
3650 installGdbServerDir.mkdir();
3651 }
3652 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3653 installGdbServerFile);
3654 }
3655 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3656 }
3657 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3658 }
3659
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003660 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3661 // and copy them to /data/data/<appname>/lib.
3662 //
3663 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3664 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3665 // one if ro.product.cpu.abi2 is defined.
3666 //
3667 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3668 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003669 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003670 try {
3671 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3672
3673 // some architectures are capable of supporting several CPU ABIs
3674 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3675 // this is indicated by the definition of the ro.product.cpu.abi2
3676 // system property.
3677 //
3678 // only scan the package twice in case of ABI mismatch
3679 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003680 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003681 if (cpuAbi2 != null) {
3682 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003684
3685 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003686 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003687 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003689
3690 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3691 cpuAbi = cpuAbi2;
3692 }
3693 }
3694
3695 // for debuggable packages, also extract gdbserver from lib/<abi>
3696 // into /data/data/<appname>/lib too.
3697 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3698 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3699 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3700 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3701 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003704 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003705 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003706 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003708 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003709 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003711 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 }
3713
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003714 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003716 File binaryDir,
3717 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 InputStream inputStream = zipFile.getInputStream(entry);
3719 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003720 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003722 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 // now need to be left as world readable and owned by the system.
3724 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3725 ! tempFile.setLastModified(entry.getTime()) ||
3726 FileUtils.setPermissions(tempFilePath,
3727 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003728 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003730 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 // Failed to properly write file.
3732 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003733 throw new IOException("Couldn't create cached binary "
3734 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 }
3736 } finally {
3737 inputStream.close();
3738 }
3739 }
3740
3741 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3742 if (chatty && Config.LOGD) Log.d(
3743 TAG, "Removing package " + pkg.applicationInfo.packageName );
3744
3745 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 mPackages.remove(pkg.applicationInfo.packageName);
3749 if (pkg.mPath != null) {
3750 mAppDirs.remove(pkg.mPath);
3751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 PackageSetting ps = (PackageSetting)pkg.mExtras;
3754 if (ps != null && ps.sharedUser != null) {
3755 // XXX don't do this until the data is removed.
3756 if (false) {
3757 ps.sharedUser.packages.remove(ps);
3758 if (ps.sharedUser.packages.size() == 0) {
3759 // Remove.
3760 }
3761 }
3762 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 int N = pkg.providers.size();
3765 StringBuilder r = null;
3766 int i;
3767 for (i=0; i<N; i++) {
3768 PackageParser.Provider p = pkg.providers.get(i);
3769 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3770 p.info.name));
3771 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 /* The is another ContentProvider with this authority when
3774 * this app was installed so this authority is null,
3775 * Ignore it as we don't have to unregister the provider.
3776 */
3777 continue;
3778 }
3779 String names[] = p.info.authority.split(";");
3780 for (int j = 0; j < names.length; j++) {
3781 if (mProviders.get(names[j]) == p) {
3782 mProviders.remove(names[j]);
3783 if (chatty && Config.LOGD) Log.d(
3784 TAG, "Unregistered content provider: " + names[j] +
3785 ", className = " + p.info.name +
3786 ", isSyncable = " + p.info.isSyncable);
3787 }
3788 }
3789 if (chatty) {
3790 if (r == null) {
3791 r = new StringBuilder(256);
3792 } else {
3793 r.append(' ');
3794 }
3795 r.append(p.info.name);
3796 }
3797 }
3798 if (r != null) {
3799 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3800 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 N = pkg.services.size();
3803 r = null;
3804 for (i=0; i<N; i++) {
3805 PackageParser.Service s = pkg.services.get(i);
3806 mServices.removeService(s);
3807 if (chatty) {
3808 if (r == null) {
3809 r = new StringBuilder(256);
3810 } else {
3811 r.append(' ');
3812 }
3813 r.append(s.info.name);
3814 }
3815 }
3816 if (r != null) {
3817 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 N = pkg.receivers.size();
3821 r = null;
3822 for (i=0; i<N; i++) {
3823 PackageParser.Activity a = pkg.receivers.get(i);
3824 mReceivers.removeActivity(a, "receiver");
3825 if (chatty) {
3826 if (r == null) {
3827 r = new StringBuilder(256);
3828 } else {
3829 r.append(' ');
3830 }
3831 r.append(a.info.name);
3832 }
3833 }
3834 if (r != null) {
3835 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 N = pkg.activities.size();
3839 r = null;
3840 for (i=0; i<N; i++) {
3841 PackageParser.Activity a = pkg.activities.get(i);
3842 mActivities.removeActivity(a, "activity");
3843 if (chatty) {
3844 if (r == null) {
3845 r = new StringBuilder(256);
3846 } else {
3847 r.append(' ');
3848 }
3849 r.append(a.info.name);
3850 }
3851 }
3852 if (r != null) {
3853 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 N = pkg.permissions.size();
3857 r = null;
3858 for (i=0; i<N; i++) {
3859 PackageParser.Permission p = pkg.permissions.get(i);
3860 boolean tree = false;
3861 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3862 if (bp == null) {
3863 tree = true;
3864 bp = mSettings.mPermissionTrees.get(p.info.name);
3865 }
3866 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003867 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 if (chatty) {
3869 if (r == null) {
3870 r = new StringBuilder(256);
3871 } else {
3872 r.append(' ');
3873 }
3874 r.append(p.info.name);
3875 }
3876 }
3877 }
3878 if (r != null) {
3879 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3880 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 N = pkg.instrumentation.size();
3883 r = null;
3884 for (i=0; i<N; i++) {
3885 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003886 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 if (chatty) {
3888 if (r == null) {
3889 r = new StringBuilder(256);
3890 } else {
3891 r.append(' ');
3892 }
3893 r.append(a.info.name);
3894 }
3895 }
3896 if (r != null) {
3897 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3898 }
3899 }
3900 }
3901
3902 private static final boolean isPackageFilename(String name) {
3903 return name != null && name.endsWith(".apk");
3904 }
3905
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003906 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3907 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3908 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3909 return true;
3910 }
3911 }
3912 return false;
3913 }
3914
3915 private void updatePermissionsLP(String changingPkg,
3916 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 // Make sure there are no dangling permission trees.
3918 Iterator<BasePermission> it = mSettings.mPermissionTrees
3919 .values().iterator();
3920 while (it.hasNext()) {
3921 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003922 if (bp.packageSetting == null) {
3923 // We may not yet have parsed the package, so just see if
3924 // we still know about its settings.
3925 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3926 }
3927 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003928 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 + " from package " + bp.sourcePackage);
3930 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003931 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3932 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3933 Slog.i(TAG, "Removing old permission tree: " + bp.name
3934 + " from package " + bp.sourcePackage);
3935 grantPermissions = true;
3936 it.remove();
3937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 }
3939 }
3940
3941 // Make sure all dynamic permissions have been assigned to a package,
3942 // and make sure there are no dangling permissions.
3943 it = mSettings.mPermissions.values().iterator();
3944 while (it.hasNext()) {
3945 BasePermission bp = it.next();
3946 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3947 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3948 + bp.name + " pkg=" + bp.sourcePackage
3949 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003950 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 BasePermission tree = findPermissionTreeLP(bp.name);
3952 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003953 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 bp.perm = new PackageParser.Permission(tree.perm.owner,
3955 new PermissionInfo(bp.pendingInfo));
3956 bp.perm.info.packageName = tree.perm.info.packageName;
3957 bp.perm.info.name = bp.name;
3958 bp.uid = tree.uid;
3959 }
3960 }
3961 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003962 if (bp.packageSetting == null) {
3963 // We may not yet have parsed the package, so just see if
3964 // we still know about its settings.
3965 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3966 }
3967 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003968 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 + " from package " + bp.sourcePackage);
3970 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003971 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3972 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3973 Slog.i(TAG, "Removing old permission: " + bp.name
3974 + " from package " + bp.sourcePackage);
3975 grantPermissions = true;
3976 it.remove();
3977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 }
3979 }
3980
3981 // Now update the permissions for all packages, in particular
3982 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003983 if (grantPermissions) {
3984 for (PackageParser.Package pkg : mPackages.values()) {
3985 if (pkg != pkgInfo) {
3986 grantPermissionsLP(pkg, false);
3987 }
3988 }
3989 }
3990
3991 if (pkgInfo != null) {
3992 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 }
3994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3997 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3998 if (ps == null) {
3999 return;
4000 }
4001 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004002 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 if (replace) {
4005 ps.permissionsFixed = false;
4006 if (gp == ps) {
4007 gp.grantedPermissions.clear();
4008 gp.gids = mGlobalGids;
4009 }
4010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 if (gp.gids == null) {
4013 gp.gids = mGlobalGids;
4014 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 final int N = pkg.requestedPermissions.size();
4017 for (int i=0; i<N; i++) {
4018 String name = pkg.requestedPermissions.get(i);
4019 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 if (false) {
4021 if (gp != ps) {
4022 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004023 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 }
4025 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004026 if (bp != null && bp.packageSetting != null) {
4027 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004029 boolean allowedSig = false;
4030 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4031 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004033 } else if (bp.packageSetting == null) {
4034 // This permission is invalid; skip it.
4035 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004036 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4037 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4038 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004040 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004042 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4044 // For updated system applications, the signatureOrSystem permission
4045 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004046 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4048 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4049 if(sysPs.grantedPermissions.contains(perm)) {
4050 allowed = true;
4051 } else {
4052 allowed = false;
4053 }
4054 } else {
4055 allowed = true;
4056 }
4057 }
4058 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004059 if (allowed) {
4060 allowedSig = true;
4061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 } else {
4063 allowed = false;
4064 }
4065 if (false) {
4066 if (gp != ps) {
4067 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4068 }
4069 }
4070 if (allowed) {
4071 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4072 && ps.permissionsFixed) {
4073 // If this is an existing, non-system package, then
4074 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004075 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004076 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004077 // Except... if this is a permission that was added
4078 // to the platform (note: need to only do this when
4079 // updating the platform).
4080 final int NP = PackageParser.NEW_PERMISSIONS.length;
4081 for (int ip=0; ip<NP; ip++) {
4082 final PackageParser.NewPermissionInfo npi
4083 = PackageParser.NEW_PERMISSIONS[ip];
4084 if (npi.name.equals(perm)
4085 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4086 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004087 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004088 + pkg.packageName);
4089 break;
4090 }
4091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 }
4093 }
4094 if (allowed) {
4095 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004096 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 gp.grantedPermissions.add(perm);
4098 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004099 } else if (!ps.haveGids) {
4100 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 }
4102 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004103 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 + " to package " + pkg.packageName
4105 + " because it was previously installed without");
4106 }
4107 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004108 if (gp.grantedPermissions.remove(perm)) {
4109 changedPermission = true;
4110 gp.gids = removeInts(gp.gids, bp.gids);
4111 Slog.i(TAG, "Un-granting permission " + perm
4112 + " from package " + pkg.packageName
4113 + " (protectionLevel=" + bp.protectionLevel
4114 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4115 + ")");
4116 } else {
4117 Slog.w(TAG, "Not granting permission " + perm
4118 + " to package " + pkg.packageName
4119 + " (protectionLevel=" + bp.protectionLevel
4120 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4121 + ")");
4122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 }
4124 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004125 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 + " in package " + pkg.packageName);
4127 }
4128 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004129
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004130 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004131 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4132 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 // This is the first that we have heard about this package, so the
4134 // permissions we have now selected are fixed until explicitly
4135 // changed.
4136 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004137 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004138 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 private final class ActivityIntentResolver
4142 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004143 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004145 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 }
4147
Mihai Preda074edef2009-05-18 17:13:31 +02004148 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004150 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4152 }
4153
Mihai Predaeae850c2009-05-13 10:13:48 +02004154 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4155 ArrayList<PackageParser.Activity> packageActivities) {
4156 if (packageActivities == null) {
4157 return null;
4158 }
4159 mFlags = flags;
4160 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4161 int N = packageActivities.size();
4162 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4163 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004164
4165 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004166 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004167 intentFilters = packageActivities.get(i).intents;
4168 if (intentFilters != null && intentFilters.size() > 0) {
4169 listCut.add(intentFilters);
4170 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004171 }
4172 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4173 }
4174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004176 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 if (SHOW_INFO || Config.LOGV) Log.v(
4178 TAG, " " + type + " " +
4179 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4180 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4181 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004182 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4184 if (SHOW_INFO || Config.LOGV) {
4185 Log.v(TAG, " IntentFilter:");
4186 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4187 }
4188 if (!intent.debugCheck()) {
4189 Log.w(TAG, "==> For Activity " + a.info.name);
4190 }
4191 addFilter(intent);
4192 }
4193 }
4194
4195 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004196 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 if (SHOW_INFO || Config.LOGV) Log.v(
4198 TAG, " " + type + " " +
4199 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4200 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4201 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004202 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4204 if (SHOW_INFO || Config.LOGV) {
4205 Log.v(TAG, " IntentFilter:");
4206 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4207 }
4208 removeFilter(intent);
4209 }
4210 }
4211
4212 @Override
4213 protected boolean allowFilterResult(
4214 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4215 ActivityInfo filterAi = filter.activity.info;
4216 for (int i=dest.size()-1; i>=0; i--) {
4217 ActivityInfo destAi = dest.get(i).activityInfo;
4218 if (destAi.name == filterAi.name
4219 && destAi.packageName == filterAi.packageName) {
4220 return false;
4221 }
4222 }
4223 return true;
4224 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004226 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004227 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4228 return info.activity.owner.packageName;
4229 }
4230
4231 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4233 int match) {
4234 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4235 return null;
4236 }
4237 final PackageParser.Activity activity = info.activity;
4238 if (mSafeMode && (activity.info.applicationInfo.flags
4239 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4240 return null;
4241 }
4242 final ResolveInfo res = new ResolveInfo();
4243 res.activityInfo = PackageParser.generateActivityInfo(activity,
4244 mFlags);
4245 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4246 res.filter = info;
4247 }
4248 res.priority = info.getPriority();
4249 res.preferredOrder = activity.owner.mPreferredOrder;
4250 //System.out.println("Result: " + res.activityInfo.className +
4251 // " = " + res.priority);
4252 res.match = match;
4253 res.isDefault = info.hasDefault;
4254 res.labelRes = info.labelRes;
4255 res.nonLocalizedLabel = info.nonLocalizedLabel;
4256 res.icon = info.icon;
4257 return res;
4258 }
4259
4260 @Override
4261 protected void sortResults(List<ResolveInfo> results) {
4262 Collections.sort(results, mResolvePrioritySorter);
4263 }
4264
4265 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004266 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004268 out.print(prefix); out.print(
4269 Integer.toHexString(System.identityHashCode(filter.activity)));
4270 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004271 out.print(filter.activity.getComponentShortName());
4272 out.print(" filter ");
4273 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004274 }
4275
4276// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4277// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4278// final List<ResolveInfo> retList = Lists.newArrayList();
4279// while (i.hasNext()) {
4280// final ResolveInfo resolveInfo = i.next();
4281// if (isEnabledLP(resolveInfo.activityInfo)) {
4282// retList.add(resolveInfo);
4283// }
4284// }
4285// return retList;
4286// }
4287
4288 // Keys are String (activity class name), values are Activity.
4289 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4290 = new HashMap<ComponentName, PackageParser.Activity>();
4291 private int mFlags;
4292 }
4293
4294 private final class ServiceIntentResolver
4295 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004296 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004298 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 }
4300
Mihai Preda074edef2009-05-18 17:13:31 +02004301 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004303 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4305 }
4306
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07004307 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4308 ArrayList<PackageParser.Service> packageServices) {
4309 if (packageServices == null) {
4310 return null;
4311 }
4312 mFlags = flags;
4313 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4314 int N = packageServices.size();
4315 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4316 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4317
4318 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4319 for (int i = 0; i < N; ++i) {
4320 intentFilters = packageServices.get(i).intents;
4321 if (intentFilters != null && intentFilters.size() > 0) {
4322 listCut.add(intentFilters);
4323 }
4324 }
4325 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4326 }
4327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004329 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 if (SHOW_INFO || Config.LOGV) Log.v(
4331 TAG, " " + (s.info.nonLocalizedLabel != null
4332 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4333 if (SHOW_INFO || Config.LOGV) Log.v(
4334 TAG, " Class=" + s.info.name);
4335 int NI = s.intents.size();
4336 int j;
4337 for (j=0; j<NI; j++) {
4338 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4339 if (SHOW_INFO || Config.LOGV) {
4340 Log.v(TAG, " IntentFilter:");
4341 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4342 }
4343 if (!intent.debugCheck()) {
4344 Log.w(TAG, "==> For Service " + s.info.name);
4345 }
4346 addFilter(intent);
4347 }
4348 }
4349
4350 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004351 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004352 if (SHOW_INFO || Config.LOGV) Log.v(
4353 TAG, " " + (s.info.nonLocalizedLabel != null
4354 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4355 if (SHOW_INFO || Config.LOGV) Log.v(
4356 TAG, " Class=" + s.info.name);
4357 int NI = s.intents.size();
4358 int j;
4359 for (j=0; j<NI; j++) {
4360 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4361 if (SHOW_INFO || Config.LOGV) {
4362 Log.v(TAG, " IntentFilter:");
4363 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4364 }
4365 removeFilter(intent);
4366 }
4367 }
4368
4369 @Override
4370 protected boolean allowFilterResult(
4371 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4372 ServiceInfo filterSi = filter.service.info;
4373 for (int i=dest.size()-1; i>=0; i--) {
4374 ServiceInfo destAi = dest.get(i).serviceInfo;
4375 if (destAi.name == filterSi.name
4376 && destAi.packageName == filterSi.packageName) {
4377 return false;
4378 }
4379 }
4380 return true;
4381 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004384 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4385 return info.service.owner.packageName;
4386 }
4387
4388 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004389 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4390 int match) {
4391 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4392 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4393 return null;
4394 }
4395 final PackageParser.Service service = info.service;
4396 if (mSafeMode && (service.info.applicationInfo.flags
4397 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4398 return null;
4399 }
4400 final ResolveInfo res = new ResolveInfo();
4401 res.serviceInfo = PackageParser.generateServiceInfo(service,
4402 mFlags);
4403 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4404 res.filter = filter;
4405 }
4406 res.priority = info.getPriority();
4407 res.preferredOrder = service.owner.mPreferredOrder;
4408 //System.out.println("Result: " + res.activityInfo.className +
4409 // " = " + res.priority);
4410 res.match = match;
4411 res.isDefault = info.hasDefault;
4412 res.labelRes = info.labelRes;
4413 res.nonLocalizedLabel = info.nonLocalizedLabel;
4414 res.icon = info.icon;
4415 return res;
4416 }
4417
4418 @Override
4419 protected void sortResults(List<ResolveInfo> results) {
4420 Collections.sort(results, mResolvePrioritySorter);
4421 }
4422
4423 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004424 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004425 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004426 out.print(prefix); out.print(
4427 Integer.toHexString(System.identityHashCode(filter.service)));
4428 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004429 out.print(filter.service.getComponentShortName());
4430 out.print(" filter ");
4431 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 }
4433
4434// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4435// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4436// final List<ResolveInfo> retList = Lists.newArrayList();
4437// while (i.hasNext()) {
4438// final ResolveInfo resolveInfo = (ResolveInfo) i;
4439// if (isEnabledLP(resolveInfo.serviceInfo)) {
4440// retList.add(resolveInfo);
4441// }
4442// }
4443// return retList;
4444// }
4445
4446 // Keys are String (activity class name), values are Activity.
4447 private final HashMap<ComponentName, PackageParser.Service> mServices
4448 = new HashMap<ComponentName, PackageParser.Service>();
4449 private int mFlags;
4450 };
4451
4452 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4453 new Comparator<ResolveInfo>() {
4454 public int compare(ResolveInfo r1, ResolveInfo r2) {
4455 int v1 = r1.priority;
4456 int v2 = r2.priority;
4457 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4458 if (v1 != v2) {
4459 return (v1 > v2) ? -1 : 1;
4460 }
4461 v1 = r1.preferredOrder;
4462 v2 = r2.preferredOrder;
4463 if (v1 != v2) {
4464 return (v1 > v2) ? -1 : 1;
4465 }
4466 if (r1.isDefault != r2.isDefault) {
4467 return r1.isDefault ? -1 : 1;
4468 }
4469 v1 = r1.match;
4470 v2 = r2.match;
4471 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4472 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4473 }
4474 };
4475
4476 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4477 new Comparator<ProviderInfo>() {
4478 public int compare(ProviderInfo p1, ProviderInfo p2) {
4479 final int v1 = p1.initOrder;
4480 final int v2 = p2.initOrder;
4481 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4482 }
4483 };
4484
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004485 private static final void sendPackageBroadcast(String action, String pkg,
4486 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 IActivityManager am = ActivityManagerNative.getDefault();
4488 if (am != null) {
4489 try {
4490 final Intent intent = new Intent(action,
4491 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4492 if (extras != null) {
4493 intent.putExtras(extras);
4494 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004495 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004496 am.broadcastIntent(null, intent, null, finishedReceiver,
4497 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 } catch (RemoteException ex) {
4499 }
4500 }
4501 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004502
4503 public String nextPackageToClean(String lastPackage) {
4504 synchronized (mPackages) {
4505 if (!mMediaMounted) {
4506 // If the external storage is no longer mounted at this point,
4507 // the caller may not have been able to delete all of this
4508 // packages files and can not delete any more. Bail.
4509 return null;
4510 }
4511 if (lastPackage != null) {
4512 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4513 }
4514 return mSettings.mPackagesToBeCleaned.size() > 0
4515 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4516 }
4517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004518
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004519 void schedulePackageCleaning(String packageName) {
4520 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4521 }
4522
4523 void startCleaningPackages() {
4524 synchronized (mPackages) {
4525 if (!mMediaMounted) {
4526 return;
4527 }
4528 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4529 return;
4530 }
4531 }
4532 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4533 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4534 IActivityManager am = ActivityManagerNative.getDefault();
4535 if (am != null) {
4536 try {
4537 am.startService(null, intent, null);
4538 } catch (RemoteException e) {
4539 }
4540 }
4541 }
4542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 private final class AppDirObserver extends FileObserver {
4544 public AppDirObserver(String path, int mask, boolean isrom) {
4545 super(path, mask);
4546 mRootDir = path;
4547 mIsRom = isrom;
4548 }
4549
4550 public void onEvent(int event, String path) {
4551 String removedPackage = null;
4552 int removedUid = -1;
4553 String addedPackage = null;
4554 int addedUid = -1;
4555
4556 synchronized (mInstallLock) {
4557 String fullPathStr = null;
4558 File fullPath = null;
4559 if (path != null) {
4560 fullPath = new File(mRootDir, path);
4561 fullPathStr = fullPath.getPath();
4562 }
4563
4564 if (Config.LOGV) Log.v(
4565 TAG, "File " + fullPathStr + " changed: "
4566 + Integer.toHexString(event));
4567
4568 if (!isPackageFilename(path)) {
4569 if (Config.LOGV) Log.v(
4570 TAG, "Ignoring change of non-package file: " + fullPathStr);
4571 return;
4572 }
4573
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004574 // Ignore packages that are being installed or
4575 // have just been installed.
4576 if (ignoreCodePath(fullPathStr)) {
4577 return;
4578 }
4579 PackageParser.Package p = null;
4580 synchronized (mPackages) {
4581 p = mAppDirs.get(fullPathStr);
4582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004584 if (p != null) {
4585 removePackageLI(p, true);
4586 removedPackage = p.applicationInfo.packageName;
4587 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 }
4589 }
4590
4591 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004593 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004594 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4595 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 PackageParser.PARSE_CHATTY |
4597 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004598 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 if (p != null) {
4600 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004601 updatePermissionsLP(p.packageName, p,
4602 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004603 }
4604 addedPackage = p.applicationInfo.packageName;
4605 addedUid = p.applicationInfo.uid;
4606 }
4607 }
4608 }
4609
4610 synchronized (mPackages) {
4611 mSettings.writeLP();
4612 }
4613 }
4614
4615 if (removedPackage != null) {
4616 Bundle extras = new Bundle(1);
4617 extras.putInt(Intent.EXTRA_UID, removedUid);
4618 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004619 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4620 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 }
4622 if (addedPackage != null) {
4623 Bundle extras = new Bundle(1);
4624 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004625 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4626 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004627 }
4628 }
4629
4630 private final String mRootDir;
4631 private final boolean mIsRom;
4632 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 /* Called when a downloaded package installation has been confirmed by the user */
4635 public void installPackage(
4636 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004637 installPackage(packageURI, observer, flags, null);
4638 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004639
Jacek Surazski65e13172009-04-28 15:26:38 +02004640 /* Called when a downloaded package installation has been confirmed by the user */
4641 public void installPackage(
4642 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4643 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 mContext.enforceCallingOrSelfPermission(
4645 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004646
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004647 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004648 msg.obj = new InstallParams(packageURI, observer, flags,
4649 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004650 mHandler.sendMessage(msg);
4651 }
4652
Christopher Tate1bb69062010-02-19 17:02:12 -08004653 public void finishPackageInstall(int token) {
4654 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4655 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4656 mHandler.sendMessage(msg);
4657 }
4658
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004659 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004660 // Queue up an async operation since the package installation may take a little while.
4661 mHandler.post(new Runnable() {
4662 public void run() {
4663 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004664 // Result object to be returned
4665 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004666 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004667 res.uid = -1;
4668 res.pkg = null;
4669 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004670 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004671 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004672 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004673 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004674 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004675 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004677
4678 // A restore should be performed at this point if (a) the install
4679 // succeeded, (b) the operation is not an update, and (c) the new
4680 // package has a backupAgent defined.
4681 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004682 boolean doRestore = (!update
4683 && res.pkg != null
4684 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004685
4686 // Set up the post-install work request bookkeeping. This will be used
4687 // and cleaned up by the post-install event handling regardless of whether
4688 // there's a restore pass performed. Token values are >= 1.
4689 int token;
4690 if (mNextInstallToken < 0) mNextInstallToken = 1;
4691 token = mNextInstallToken++;
4692
4693 PostInstallData data = new PostInstallData(args, res);
4694 mRunningInstalls.put(token, data);
4695 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4696
4697 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4698 // Pass responsibility to the Backup Manager. It will perform a
4699 // restore if appropriate, then pass responsibility back to the
4700 // Package Manager to run the post-install observer callbacks
4701 // and broadcasts.
4702 IBackupManager bm = IBackupManager.Stub.asInterface(
4703 ServiceManager.getService(Context.BACKUP_SERVICE));
4704 if (bm != null) {
4705 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4706 + " to BM for possible restore");
4707 try {
4708 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4709 } catch (RemoteException e) {
4710 // can't happen; the backup manager is local
4711 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004712 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004713 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004714 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004715 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004716 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004717 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004720
4721 if (!doRestore) {
4722 // No restore possible, or the Backup Manager was mysteriously not
4723 // available -- just fire the post-install work request directly.
4724 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4725 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4726 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004728 }
4729 });
4730 }
4731
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004732 abstract class HandlerParams {
4733 final static int MAX_RETRIES = 4;
4734 int retry = 0;
4735 final void startCopy() {
4736 try {
4737 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4738 retry++;
4739 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004740 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004741 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4742 handleServiceError();
4743 return;
4744 } else {
4745 handleStartCopy();
4746 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4747 mHandler.sendEmptyMessage(MCS_UNBIND);
4748 }
4749 } catch (RemoteException e) {
4750 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4751 mHandler.sendEmptyMessage(MCS_RECONNECT);
4752 }
4753 handleReturnCode();
4754 }
4755
4756 final void serviceError() {
4757 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4758 handleServiceError();
4759 handleReturnCode();
4760 }
4761 abstract void handleStartCopy() throws RemoteException;
4762 abstract void handleServiceError();
4763 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004764 }
4765
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004766 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004767 final IPackageInstallObserver observer;
4768 int flags;
4769 final Uri packageURI;
4770 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004771 private InstallArgs mArgs;
4772 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004773 InstallParams(Uri packageURI,
4774 IPackageInstallObserver observer, int flags,
4775 String installerPackageName) {
4776 this.packageURI = packageURI;
4777 this.flags = flags;
4778 this.observer = observer;
4779 this.installerPackageName = installerPackageName;
4780 }
4781
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004782 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4783 String packageName = pkgLite.packageName;
4784 int installLocation = pkgLite.installLocation;
4785 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4786 synchronized (mPackages) {
4787 PackageParser.Package pkg = mPackages.get(packageName);
4788 if (pkg != null) {
4789 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4790 // Check for updated system application.
4791 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4792 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004793 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004794 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4795 }
4796 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4797 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004798 if (onSd) {
4799 // Install flag overrides everything.
4800 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4801 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004802 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004803 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4804 // Application explicitly specified internal.
4805 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4806 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4807 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004808 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004809 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004810 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4811 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4812 }
4813 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004814 }
4815 }
4816 } else {
4817 // Invalid install. Return error code
4818 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4819 }
4820 }
4821 }
4822 // All the special cases have been taken care of.
4823 // Return result based on recommended install location.
4824 if (onSd) {
4825 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4826 }
4827 return pkgLite.recommendedInstallLocation;
4828 }
4829
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004830 /*
4831 * Invoke remote method to get package information and install
4832 * location values. Override install location based on default
4833 * policy if needed and then create install arguments based
4834 * on the install location.
4835 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004836 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004837 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004838 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4839 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004840 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4841 if (onInt && onSd) {
4842 // Check if both bits are set.
4843 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4844 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4845 } else if (fwdLocked && onSd) {
4846 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004847 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004848 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004849 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004850 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004851 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004852 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004853 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4854 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4855 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4856 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4857 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4859 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4860 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004861 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4862 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004863 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004864 // Override with defaults if needed.
4865 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004866 if (!onSd && !onInt) {
4867 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004868 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4869 // Set the flag to install on external media.
4870 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004871 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004872 } else {
4873 // Make sure the flag for installing on external
4874 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004875 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004876 flags &= ~PackageManager.INSTALL_EXTERNAL;
4877 }
4878 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004879 }
4880 }
4881 // Create the file args now.
4882 mArgs = createInstallArgs(this);
4883 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4884 // Create copy only if we are not in an erroneous state.
4885 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004886 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004887 }
4888 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004889 }
4890
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004891 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004892 void handleReturnCode() {
4893 processPendingInstall(mArgs, mRet);
4894 }
4895
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004896 @Override
4897 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004898 mArgs = createInstallArgs(this);
4899 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004900 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004901 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004902
4903 /*
4904 * Utility class used in movePackage api.
4905 * srcArgs and targetArgs are not set for invalid flags and make
4906 * sure to do null checks when invoking methods on them.
4907 * We probably want to return ErrorPrams for both failed installs
4908 * and moves.
4909 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004910 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004911 final IPackageMoveObserver observer;
4912 final int flags;
4913 final String packageName;
4914 final InstallArgs srcArgs;
4915 final InstallArgs targetArgs;
4916 int mRet;
4917 MoveParams(InstallArgs srcArgs,
4918 IPackageMoveObserver observer,
4919 int flags, String packageName) {
4920 this.srcArgs = srcArgs;
4921 this.observer = observer;
4922 this.flags = flags;
4923 this.packageName = packageName;
4924 if (srcArgs != null) {
4925 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4926 targetArgs = createInstallArgs(packageUri, flags, packageName);
4927 } else {
4928 targetArgs = null;
4929 }
4930 }
4931
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004932 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004933 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4934 // Check for storage space on target medium
4935 if (!targetArgs.checkFreeStorage(mContainerService)) {
4936 Log.w(TAG, "Insufficient storage to install");
4937 return;
4938 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004939 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004940 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004941 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004942 if (DEBUG_SD_INSTALL) {
4943 StringBuilder builder = new StringBuilder();
4944 if (srcArgs != null) {
4945 builder.append("src: ");
4946 builder.append(srcArgs.getCodePath());
4947 }
4948 if (targetArgs != null) {
4949 builder.append(" target : ");
4950 builder.append(targetArgs.getCodePath());
4951 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004952 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004953 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004954 }
4955
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004956 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004957 void handleReturnCode() {
4958 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004959 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4960 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4961 currentStatus = PackageManager.MOVE_SUCCEEDED;
4962 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4963 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4964 }
4965 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004966 }
4967
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004968 @Override
4969 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004970 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004971 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004972 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004973
4974 private InstallArgs createInstallArgs(InstallParams params) {
4975 if (installOnSd(params.flags)) {
4976 return new SdInstallArgs(params);
4977 } else {
4978 return new FileInstallArgs(params);
4979 }
4980 }
4981
4982 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4983 if (installOnSd(flags)) {
4984 return new SdInstallArgs(fullCodePath, fullResourcePath);
4985 } else {
4986 return new FileInstallArgs(fullCodePath, fullResourcePath);
4987 }
4988 }
4989
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004990 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4991 if (installOnSd(flags)) {
4992 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4993 return new SdInstallArgs(packageURI, cid);
4994 } else {
4995 return new FileInstallArgs(packageURI, pkgName);
4996 }
4997 }
4998
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004999 static abstract class InstallArgs {
5000 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005001 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005002 final int flags;
5003 final Uri packageURI;
5004 final String installerPackageName;
5005
5006 InstallArgs(Uri packageURI,
5007 IPackageInstallObserver observer, int flags,
5008 String installerPackageName) {
5009 this.packageURI = packageURI;
5010 this.flags = flags;
5011 this.observer = observer;
5012 this.installerPackageName = installerPackageName;
5013 }
5014
5015 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005016 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005017 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005018 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005019 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005020 abstract String getCodePath();
5021 abstract String getResourcePath();
5022 // Need installer lock especially for dex file removal.
5023 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005024 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005025 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005026 }
5027
5028 class FileInstallArgs extends InstallArgs {
5029 File installDir;
5030 String codeFileName;
5031 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005032 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005033
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005034 FileInstallArgs(InstallParams params) {
5035 super(params.packageURI, params.observer,
5036 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005037 }
5038
5039 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5040 super(null, null, 0, null);
5041 File codeFile = new File(fullCodePath);
5042 installDir = codeFile.getParentFile();
5043 codeFileName = fullCodePath;
5044 resourceFileName = fullResourcePath;
5045 }
5046
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005047 FileInstallArgs(Uri packageURI, String pkgName) {
5048 super(packageURI, null, 0, null);
5049 boolean fwdLocked = isFwdLocked(flags);
5050 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5051 String apkName = getNextCodePath(null, pkgName, ".apk");
5052 codeFileName = new File(installDir, apkName + ".apk").getPath();
5053 resourceFileName = getResourcePathFromCodePath();
5054 }
5055
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005056 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5057 return imcs.checkFreeStorage(false, packageURI);
5058 }
5059
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005060 String getCodePath() {
5061 return codeFileName;
5062 }
5063
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005064 void createCopyFile() {
5065 boolean fwdLocked = isFwdLocked(flags);
5066 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5067 codeFileName = createTempPackageFile(installDir).getPath();
5068 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005069 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005070 }
5071
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005072 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005073 if (temp) {
5074 // Generate temp file name
5075 createCopyFile();
5076 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005077 // Get a ParcelFileDescriptor to write to the output file
5078 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005079 if (!created) {
5080 try {
5081 codeFile.createNewFile();
5082 // Set permissions
5083 if (!setPermissions()) {
5084 // Failed setting permissions.
5085 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5086 }
5087 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005088 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005089 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5090 }
5091 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005092 ParcelFileDescriptor out = null;
5093 try {
5094 out = ParcelFileDescriptor.open(codeFile,
5095 ParcelFileDescriptor.MODE_READ_WRITE);
5096 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005097 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005098 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5099 }
5100 // Copy the resource now
5101 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5102 try {
5103 if (imcs.copyResource(packageURI, out)) {
5104 ret = PackageManager.INSTALL_SUCCEEDED;
5105 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005106 } finally {
5107 try { if (out != null) out.close(); } catch (IOException e) {}
5108 }
5109 return ret;
5110 }
5111
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005112 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005113 if (status != PackageManager.INSTALL_SUCCEEDED) {
5114 cleanUp();
5115 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005116 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005117 }
5118
5119 boolean doRename(int status, final String pkgName, String oldCodePath) {
5120 if (status != PackageManager.INSTALL_SUCCEEDED) {
5121 cleanUp();
5122 return false;
5123 } else {
5124 // Rename based on packageName
5125 File codeFile = new File(getCodePath());
5126 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5127 File desFile = new File(installDir, apkName + ".apk");
5128 if (!codeFile.renameTo(desFile)) {
5129 return false;
5130 }
5131 // Reset paths since the file has been renamed.
5132 codeFileName = desFile.getPath();
5133 resourceFileName = getResourcePathFromCodePath();
5134 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005135 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005136 // Failed setting permissions.
5137 return false;
5138 }
5139 return true;
5140 }
5141 }
5142
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005143 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005144 if (status != PackageManager.INSTALL_SUCCEEDED) {
5145 cleanUp();
5146 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005147 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005148 }
5149
5150 String getResourcePath() {
5151 return resourceFileName;
5152 }
5153
5154 String getResourcePathFromCodePath() {
5155 String codePath = getCodePath();
5156 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5157 String apkNameOnly = getApkName(codePath);
5158 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5159 } else {
5160 return codePath;
5161 }
5162 }
5163
5164 private boolean cleanUp() {
5165 boolean ret = true;
5166 String sourceDir = getCodePath();
5167 String publicSourceDir = getResourcePath();
5168 if (sourceDir != null) {
5169 File sourceFile = new File(sourceDir);
5170 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005171 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005172 ret = false;
5173 }
5174 // Delete application's code and resources
5175 sourceFile.delete();
5176 }
5177 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5178 final File publicSourceFile = new File(publicSourceDir);
5179 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005180 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005181 }
5182 if (publicSourceFile.exists()) {
5183 publicSourceFile.delete();
5184 }
5185 }
5186 return ret;
5187 }
5188
5189 void cleanUpResourcesLI() {
5190 String sourceDir = getCodePath();
5191 if (cleanUp() && mInstaller != null) {
5192 int retCode = mInstaller.rmdex(sourceDir);
5193 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005194 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005195 + " at location "
5196 + sourceDir + ", retcode=" + retCode);
5197 // we don't consider this to be a failure of the core package deletion
5198 }
5199 }
5200 }
5201
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005202 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005203 // TODO Do this in a more elegant way later on. for now just a hack
5204 if (!isFwdLocked(flags)) {
5205 final int filePermissions =
5206 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5207 |FileUtils.S_IROTH;
5208 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5209 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005210 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005211 getCodePath()
5212 + ". The return code was: " + retCode);
5213 // TODO Define new internal error
5214 return false;
5215 }
5216 return true;
5217 }
5218 return true;
5219 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005220
5221 boolean doPostDeleteLI(boolean delete) {
5222 cleanUpResourcesLI();
5223 return true;
5224 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005225 }
5226
5227 class SdInstallArgs extends InstallArgs {
5228 String cid;
5229 String cachePath;
5230 static final String RES_FILE_NAME = "pkg.apk";
5231
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005232 SdInstallArgs(InstallParams params) {
5233 super(params.packageURI, params.observer,
5234 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005235 }
5236
5237 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005238 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005239 // Extract cid from fullCodePath
5240 int eidx = fullCodePath.lastIndexOf("/");
5241 String subStr1 = fullCodePath.substring(0, eidx);
5242 int sidx = subStr1.lastIndexOf("/");
5243 cid = subStr1.substring(sidx+1, eidx);
5244 cachePath = subStr1;
5245 }
5246
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005247 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005248 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5249 this.cid = cid;
5250 }
5251
5252 SdInstallArgs(Uri packageURI, String cid) {
5253 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005254 this.cid = cid;
5255 }
5256
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005257 void createCopyFile() {
5258 cid = getTempContainerId();
5259 }
5260
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005261 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5262 return imcs.checkFreeStorage(true, packageURI);
5263 }
5264
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005265 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005266 if (temp) {
5267 createCopyFile();
5268 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005269 cachePath = imcs.copyResourceToContainer(
5270 packageURI, cid,
5271 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005272 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5273 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005274 }
5275
5276 @Override
5277 String getCodePath() {
5278 return cachePath + "/" + RES_FILE_NAME;
5279 }
5280
5281 @Override
5282 String getResourcePath() {
5283 return cachePath + "/" + RES_FILE_NAME;
5284 }
5285
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005286 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005287 if (status != PackageManager.INSTALL_SUCCEEDED) {
5288 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005289 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005290 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005291 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005292 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005293 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005294 if (cachePath == null) {
5295 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5296 }
5297 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005298 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005299 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005300 }
5301
5302 boolean doRename(int status, final String pkgName,
5303 String oldCodePath) {
5304 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005305 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005306 if (PackageHelper.isContainerMounted(cid)) {
5307 // Unmount the container
5308 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005309 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005310 return false;
5311 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005312 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005313 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005314 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5315 " which might be stale. Will try to clean up.");
5316 // Clean up the stale container and proceed to recreate.
5317 if (!PackageHelper.destroySdDir(newCacheId)) {
5318 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5319 return false;
5320 }
5321 // Successfully cleaned up stale container. Try to rename again.
5322 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5323 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5324 + " inspite of cleaning it up.");
5325 return false;
5326 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005327 }
5328 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005329 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005330 newCachePath = PackageHelper.mountSdDir(newCacheId,
5331 getEncryptKey(), Process.SYSTEM_UID);
5332 } else {
5333 newCachePath = PackageHelper.getSdDir(newCacheId);
5334 }
5335 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005336 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005337 return false;
5338 }
5339 Log.i(TAG, "Succesfully renamed " + cid +
5340 " at path: " + cachePath + " to " + newCacheId +
5341 " at new path: " + newCachePath);
5342 cid = newCacheId;
5343 cachePath = newCachePath;
5344 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005345 }
5346
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005347 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005348 if (status != PackageManager.INSTALL_SUCCEEDED) {
5349 cleanUp();
5350 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005351 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005352 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005353 PackageHelper.mountSdDir(cid,
5354 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005355 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005356 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005357 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005358 }
5359
5360 private void cleanUp() {
5361 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005362 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005363 }
5364
5365 void cleanUpResourcesLI() {
5366 String sourceFile = getCodePath();
5367 // Remove dex file
5368 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005369 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005370 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005371 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005372 + " at location "
5373 + sourceFile.toString() + ", retcode=" + retCode);
5374 // we don't consider this to be a failure of the core package deletion
5375 }
5376 }
5377 cleanUp();
5378 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005379
5380 boolean matchContainer(String app) {
5381 if (cid.startsWith(app)) {
5382 return true;
5383 }
5384 return false;
5385 }
5386
5387 String getPackageName() {
5388 int idx = cid.lastIndexOf("-");
5389 if (idx == -1) {
5390 return cid;
5391 }
5392 return cid.substring(0, idx);
5393 }
5394
5395 boolean doPostDeleteLI(boolean delete) {
5396 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005397 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005398 if (mounted) {
5399 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005400 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005401 }
5402 if (ret && delete) {
5403 cleanUpResourcesLI();
5404 }
5405 return ret;
5406 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005407 };
5408
5409 // Utility method used to create code paths based on package name and available index.
5410 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5411 String idxStr = "";
5412 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005413 // Fall back to default value of idx=1 if prefix is not
5414 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005415 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005416 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005417 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005418 if (subStr.endsWith(suffix)) {
5419 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005420 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005421 // If oldCodePath already contains prefix find out the
5422 // ending index to either increment or decrement.
5423 int sidx = subStr.lastIndexOf(prefix);
5424 if (sidx != -1) {
5425 subStr = subStr.substring(sidx + prefix.length());
5426 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005427 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5428 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005429 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005430 try {
5431 idx = Integer.parseInt(subStr);
5432 if (idx <= 1) {
5433 idx++;
5434 } else {
5435 idx--;
5436 }
5437 } catch(NumberFormatException e) {
5438 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005439 }
5440 }
5441 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005442 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005443 return prefix + idxStr;
5444 }
5445
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005446 // Utility method used to ignore ADD/REMOVE events
5447 // by directory observer.
5448 private static boolean ignoreCodePath(String fullPathStr) {
5449 String apkName = getApkName(fullPathStr);
5450 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5451 if (idx != -1 && ((idx+1) < apkName.length())) {
5452 // Make sure the package ends with a numeral
5453 String version = apkName.substring(idx+1);
5454 try {
5455 Integer.parseInt(version);
5456 return true;
5457 } catch (NumberFormatException e) {}
5458 }
5459 return false;
5460 }
5461
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005462 // Utility method that returns the relative package path with respect
5463 // to the installation directory. Like say for /data/data/com.test-1.apk
5464 // string com.test-1 is returned.
5465 static String getApkName(String codePath) {
5466 if (codePath == null) {
5467 return null;
5468 }
5469 int sidx = codePath.lastIndexOf("/");
5470 int eidx = codePath.lastIndexOf(".");
5471 if (eidx == -1) {
5472 eidx = codePath.length();
5473 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005474 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005475 return null;
5476 }
5477 return codePath.substring(sidx+1, eidx);
5478 }
5479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005480 class PackageInstalledInfo {
5481 String name;
5482 int uid;
5483 PackageParser.Package pkg;
5484 int returnCode;
5485 PackageRemovedInfo removedInfo;
5486 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 /*
5489 * Install a non-existing package.
5490 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005491 private void installNewPackageLI(PackageParser.Package pkg,
5492 int parseFlags,
5493 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005494 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005496 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005497
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005498 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 res.name = pkgName;
5500 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005501 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5502 // A package with the same name is already installed, though
5503 // it has been renamed to an older name. The package we
5504 // are trying to install should be installed as an update to
5505 // the existing one, but that has not been requested, so bail.
5506 Slog.w(TAG, "Attempt to re-install " + pkgName
5507 + " without first uninstalling package running as "
5508 + mSettings.mRenamedPackages.get(pkgName));
5509 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5510 return;
5511 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005512 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005513 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005514 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 + " without first uninstalling.");
5516 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5517 return;
5518 }
5519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005521 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005523 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5525 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5526 }
5527 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005528 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005529 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 res);
5531 // delete the partially installed application. the data directory will have to be
5532 // restored if it was already existing
5533 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5534 // remove package from internal structures. Note that we want deletePackageX to
5535 // delete the package data and cache directories that it created in
5536 // scanPackageLocked, unless those directories existed before we even tried to
5537 // install.
5538 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005539 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5541 res.removedInfo);
5542 }
5543 }
5544 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005545
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005546 private void replacePackageLI(PackageParser.Package pkg,
5547 int parseFlags,
5548 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005549 String installerPackageName, PackageInstalledInfo res) {
5550
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005551 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005552 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 // First find the old package info and check signatures
5554 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005555 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005556 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005557 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5559 return;
5560 }
5561 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005562 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005563 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005564 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005566 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 }
5568 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005571 PackageParser.Package pkg,
5572 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005573 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 PackageParser.Package newPackage = null;
5575 String pkgName = deletedPackage.packageName;
5576 boolean deletedPkg = true;
5577 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005578
Jacek Surazski65e13172009-04-28 15:26:38 +02005579 String oldInstallerPackageName = null;
5580 synchronized (mPackages) {
5581 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005585 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 res.removedInfo)) {
5587 // If the existing package was'nt successfully deleted
5588 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5589 deletedPkg = false;
5590 } else {
5591 // Successfully deleted the old package. Now proceed with re-installation
5592 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005593 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005595 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5597 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005598 }
5599 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005600 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005601 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 res);
5603 updatedSettings = true;
5604 }
5605 }
5606
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005607 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 // remove package from internal structures. Note that we want deletePackageX to
5609 // delete the package data and cache directories that it created in
5610 // scanPackageLocked, unless those directories existed before we even tried to
5611 // install.
5612 if(updatedSettings) {
5613 deletePackageLI(
5614 pkgName, true,
5615 PackageManager.DONT_DELETE_DATA,
5616 res.removedInfo);
5617 }
5618 // Since we failed to install the new package we need to restore the old
5619 // package that we deleted.
5620 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005621 File restoreFile = new File(deletedPackage.mPath);
5622 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005623 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005624 return;
5625 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005626 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005627 boolean oldOnSd = isExternal(deletedPackage);
5628 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5629 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5630 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5631 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5632 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5633 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5634 return;
5635 }
5636 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005637 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005638 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5639 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005640 mSettings.writeLP();
5641 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005642 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 }
5644 }
5645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005648 PackageParser.Package pkg,
5649 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005650 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 PackageParser.Package newPackage = null;
5652 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005653 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 PackageParser.PARSE_IS_SYSTEM;
5655 String packageName = deletedPackage.packageName;
5656 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5657 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005658 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 return;
5660 }
5661 PackageParser.Package oldPkg;
5662 PackageSetting oldPkgSetting;
5663 synchronized (mPackages) {
5664 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005665 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5667 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005668 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 return;
5670 }
5671 }
5672 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5673 res.removedInfo.removedPackage = packageName;
5674 // Remove existing system package
5675 removePackageLI(oldPkg, true);
5676 synchronized (mPackages) {
5677 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5678 }
5679
5680 // Successfully disabled the old package. Now proceed with re-installation
5681 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5682 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005683 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005685 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5687 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5688 }
5689 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005690 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 updatedSettings = true;
5692 }
5693
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005694 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 // Re installation failed. Restore old information
5696 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005697 if (newPackage != null) {
5698 removePackageLI(newPackage, true);
5699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005701 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005703 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704 // Restore the old system information in Settings
5705 synchronized(mPackages) {
5706 if(updatedSettings) {
5707 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005708 mSettings.setInstallerPackageName(packageName,
5709 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 }
5711 mSettings.writeLP();
5712 }
5713 }
5714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005715
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005716 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005717 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005718 int retCode;
5719 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5720 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5721 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005722 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005723 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5724 }
5725 }
5726 return PackageManager.INSTALL_SUCCEEDED;
5727 }
5728
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005729 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005730 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005731 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 synchronized (mPackages) {
5733 //write settings. the installStatus will be incomplete at this stage.
5734 //note that the new package setting would have already been
5735 //added to mPackages. It hasn't been persisted yet.
5736 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5737 mSettings.writeLP();
5738 }
5739
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005740 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005741 != PackageManager.INSTALL_SUCCEEDED) {
5742 // Discontinue if moving dex files failed.
5743 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005745 if((res.returnCode = setPermissionsLI(newPackage))
5746 != PackageManager.INSTALL_SUCCEEDED) {
5747 if (mInstaller != null) {
5748 mInstaller.rmdex(newPackage.mScanPath);
5749 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005750 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005752 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005755 updatePermissionsLP(newPackage.packageName, newPackage,
5756 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 res.name = pkgName;
5758 res.uid = newPackage.applicationInfo.uid;
5759 res.pkg = newPackage;
5760 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005761 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5763 //to update install status
5764 mSettings.writeLP();
5765 }
5766 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005767
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005768 private void installPackageLI(InstallArgs args,
5769 boolean newInstall, PackageInstalledInfo res) {
5770 int pFlags = args.flags;
5771 String installerPackageName = args.installerPackageName;
5772 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005773 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005774 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005775 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005776 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005777 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005778 // Result object to be returned
5779 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5780
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005781 // Retrieve PackageSettings and parse package
5782 int parseFlags = PackageParser.PARSE_CHATTY |
5783 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5784 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5785 parseFlags |= mDefParseFlags;
5786 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5787 pp.setSeparateProcesses(mSeparateProcesses);
5788 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5789 null, mMetrics, parseFlags);
5790 if (pkg == null) {
5791 res.returnCode = pp.getParseError();
5792 return;
5793 }
5794 String pkgName = res.name = pkg.packageName;
5795 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5796 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5797 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5798 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005800 }
5801 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5802 res.returnCode = pp.getParseError();
5803 return;
5804 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005805 // Get rid of all references to package scan path via parser.
5806 pp = null;
5807 String oldCodePath = null;
5808 boolean systemApp = false;
5809 synchronized (mPackages) {
5810 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005811 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5812 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005813 if (pkg.mOriginalPackages != null
5814 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005815 && mPackages.containsKey(oldName)) {
5816 // This package is derived from an original package,
5817 // and this device has been updating from that original
5818 // name. We must continue using the original name, so
5819 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005820 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005821 pkgName = pkg.packageName;
5822 replace = true;
5823 } else if (mPackages.containsKey(pkgName)) {
5824 // This package, under its official name, already exists
5825 // on the device; we should replace it.
5826 replace = true;
5827 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005828 }
5829 PackageSetting ps = mSettings.mPackages.get(pkgName);
5830 if (ps != null) {
5831 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5832 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5833 systemApp = (ps.pkg.applicationInfo.flags &
5834 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005835 }
5836 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005838
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005839 if (systemApp && onSd) {
5840 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005841 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005842 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5843 return;
5844 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005845
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005846 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5847 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5848 return;
5849 }
5850 // Set application objects path explicitly after the rename
5851 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005852 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005853 replacePackageLI(pkg, parseFlags, scanMode,
5854 installerPackageName, res);
5855 } else {
5856 installNewPackageLI(pkg, parseFlags, scanMode,
5857 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 }
5859 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005860
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005861 private int setPermissionsLI(PackageParser.Package newPackage) {
5862 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005863 int retCode = 0;
5864 // TODO Gross hack but fix later. Ideally move this to be a post installation
5865 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005866 if ((newPackage.applicationInfo.flags
5867 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5868 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 try {
5870 extractPublicFiles(newPackage, destResourceFile);
5871 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005872 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 -08005873 " forward-locked app.");
5874 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5875 } finally {
5876 //TODO clean up the extracted public files
5877 }
5878 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005879 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 newPackage.applicationInfo.uid);
5881 } else {
5882 final int filePermissions =
5883 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005884 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 newPackage.applicationInfo.uid);
5886 }
5887 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005888 // The permissions on the resource file was set when it was copied for
5889 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005893 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005894 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005896 // TODO Define new internal error
5897 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898 }
5899 return PackageManager.INSTALL_SUCCEEDED;
5900 }
5901
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005902 private boolean isForwardLocked(PackageParser.Package pkg) {
5903 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005904 }
5905
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005906 private boolean isExternal(PackageParser.Package pkg) {
5907 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
5908 }
5909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 private void extractPublicFiles(PackageParser.Package newPackage,
5911 File publicZipFile) throws IOException {
5912 final ZipOutputStream publicZipOutStream =
5913 new ZipOutputStream(new FileOutputStream(publicZipFile));
5914 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5915
5916 // Copy manifest, resources.arsc and res directory to public zip
5917
5918 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5919 while (privateZipEntries.hasMoreElements()) {
5920 final ZipEntry zipEntry = privateZipEntries.nextElement();
5921 final String zipEntryName = zipEntry.getName();
5922 if ("AndroidManifest.xml".equals(zipEntryName)
5923 || "resources.arsc".equals(zipEntryName)
5924 || zipEntryName.startsWith("res/")) {
5925 try {
5926 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5927 } catch (IOException e) {
5928 try {
5929 publicZipOutStream.close();
5930 throw e;
5931 } finally {
5932 publicZipFile.delete();
5933 }
5934 }
5935 }
5936 }
5937
5938 publicZipOutStream.close();
5939 FileUtils.setPermissions(
5940 publicZipFile.getAbsolutePath(),
5941 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5942 -1, -1);
5943 }
5944
5945 private static void copyZipEntry(ZipEntry zipEntry,
5946 ZipFile inZipFile,
5947 ZipOutputStream outZipStream) throws IOException {
5948 byte[] buffer = new byte[4096];
5949 int num;
5950
5951 ZipEntry newEntry;
5952 if (zipEntry.getMethod() == ZipEntry.STORED) {
5953 // Preserve the STORED method of the input entry.
5954 newEntry = new ZipEntry(zipEntry);
5955 } else {
5956 // Create a new entry so that the compressed len is recomputed.
5957 newEntry = new ZipEntry(zipEntry.getName());
5958 }
5959 outZipStream.putNextEntry(newEntry);
5960
5961 InputStream data = inZipFile.getInputStream(zipEntry);
5962 while ((num = data.read(buffer)) > 0) {
5963 outZipStream.write(buffer, 0, num);
5964 }
5965 outZipStream.flush();
5966 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968 private void deleteTempPackageFiles() {
5969 FilenameFilter filter = new FilenameFilter() {
5970 public boolean accept(File dir, String name) {
5971 return name.startsWith("vmdl") && name.endsWith(".tmp");
5972 }
5973 };
5974 String tmpFilesList[] = mAppInstallDir.list(filter);
5975 if(tmpFilesList == null) {
5976 return;
5977 }
5978 for(int i = 0; i < tmpFilesList.length; i++) {
5979 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5980 tmpFile.delete();
5981 }
5982 }
5983
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005984 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 File tmpPackageFile;
5986 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005987 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005989 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005990 return null;
5991 }
5992 try {
5993 FileUtils.setPermissions(
5994 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5995 -1, -1);
5996 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005997 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005998 return null;
5999 }
6000 return tmpPackageFile;
6001 }
6002
6003 public void deletePackage(final String packageName,
6004 final IPackageDeleteObserver observer,
6005 final int flags) {
6006 mContext.enforceCallingOrSelfPermission(
6007 android.Manifest.permission.DELETE_PACKAGES, null);
6008 // Queue up an async operation since the package deletion may take a little while.
6009 mHandler.post(new Runnable() {
6010 public void run() {
6011 mHandler.removeCallbacks(this);
6012 final boolean succeded = deletePackageX(packageName, true, true, flags);
6013 if (observer != null) {
6014 try {
6015 observer.packageDeleted(succeded);
6016 } catch (RemoteException e) {
6017 Log.i(TAG, "Observer no longer exists.");
6018 } //end catch
6019 } //end if
6020 } //end run
6021 });
6022 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 /**
6025 * This method is an internal method that could be get invoked either
6026 * to delete an installed package or to clean up a failed installation.
6027 * After deleting an installed package, a broadcast is sent to notify any
6028 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006029 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 * installation wouldn't have sent the initial broadcast either
6031 * The key steps in deleting a package are
6032 * deleting the package information in internal structures like mPackages,
6033 * deleting the packages base directories through installd
6034 * updating mSettings to reflect current status
6035 * persisting settings for later use
6036 * sending a broadcast if necessary
6037 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6039 boolean deleteCodeAndResources, int flags) {
6040 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006041 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006043 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6044 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6045 try {
6046 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006047 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006048 return false;
6049 }
6050 } catch (RemoteException e) {
6051 }
6052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 synchronized (mInstallLock) {
6054 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
6055 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006057 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006058 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
6059 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
6060
6061 // If the removed package was a system update, the old system packaged
6062 // was re-enabled; we need to broadcast this information
6063 if (systemUpdate) {
6064 Bundle extras = new Bundle(1);
6065 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6066 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6067
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006068 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6069 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08006072 // Force a gc here.
6073 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006074 // Delete the resources here after sending the broadcast to let
6075 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006076 if (info.args != null) {
6077 synchronized (mInstallLock) {
6078 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006079 }
6080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 return res;
6082 }
6083
6084 static class PackageRemovedInfo {
6085 String removedPackage;
6086 int uid = -1;
6087 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006088 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006089 // Clean up resources deleted packages.
6090 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006092 void sendBroadcast(boolean fullRemove, boolean replacing) {
6093 Bundle extras = new Bundle(1);
6094 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6095 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6096 if (replacing) {
6097 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6098 }
6099 if (removedPackage != null) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006100 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006101 }
6102 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006103 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 }
6105 }
6106 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 /*
6109 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6110 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006111 * 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 -08006112 * delete a partially installed application.
6113 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006114 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 int flags) {
6116 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006117 if (outInfo != null) {
6118 outInfo.removedPackage = packageName;
6119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 removePackageLI(p, true);
6121 // Retrieve object to delete permissions for shared user later on
6122 PackageSetting deletedPs;
6123 synchronized (mPackages) {
6124 deletedPs = mSettings.mPackages.get(packageName);
6125 }
6126 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6127 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006128 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006130 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 + packageName + ", retcode=" + retCode);
6132 // we don't consider this to be a failure of the core package deletion
6133 }
6134 } else {
6135 //for emulator
6136 PackageParser.Package pkg = mPackages.get(packageName);
6137 File dataDir = new File(pkg.applicationInfo.dataDir);
6138 dataDir.delete();
6139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140 }
6141 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006142 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006143 schedulePackageCleaning(packageName);
6144
6145 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6146 if (outInfo != null) {
6147 outInfo.removedUid = mSettings.removePackageLP(packageName);
6148 }
6149 if (deletedPs != null) {
6150 updatePermissionsLP(deletedPs.name, null, false, false);
6151 if (deletedPs.sharedUser != null) {
6152 // remove permissions associated with package
6153 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6154 }
6155 }
6156 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006157 // remove from preferred activities.
6158 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6159 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6160 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6161 removed.add(pa);
6162 }
6163 }
6164 for (PreferredActivity pa : removed) {
6165 mSettings.mPreferredActivities.removeFilter(pa);
6166 }
6167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006168 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006169 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 }
6171 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 /*
6174 * Tries to delete system package.
6175 */
6176 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006177 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 ApplicationInfo applicationInfo = p.applicationInfo;
6179 //applicable for non-partially installed applications only
6180 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006181 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 return false;
6183 }
6184 PackageSetting ps = null;
6185 // Confirm if the system package has been updated
6186 // An updated system app can be deleted. This will also have to restore
6187 // the system pkg from system partition
6188 synchronized (mPackages) {
6189 ps = mSettings.getDisabledSystemPkg(p.packageName);
6190 }
6191 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006192 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 return false;
6194 } else {
6195 Log.i(TAG, "Deleting system pkg from data partition");
6196 }
6197 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006198 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006199 boolean deleteCodeAndResources = false;
6200 if (ps.versionCode < p.mVersionCode) {
6201 // Delete code and resources for downgrades
6202 deleteCodeAndResources = true;
6203 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6204 flags &= ~PackageManager.DONT_DELETE_DATA;
6205 }
6206 } else {
6207 // Preserve data by setting flag
6208 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6209 flags |= PackageManager.DONT_DELETE_DATA;
6210 }
6211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6213 if (!ret) {
6214 return false;
6215 }
6216 synchronized (mPackages) {
6217 // Reinstate the old system package
6218 mSettings.enableSystemPackageLP(p.packageName);
6219 }
6220 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006221 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006223 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006226 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 return false;
6228 }
6229 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006230 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 mSettings.writeLP();
6232 }
6233 return true;
6234 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6237 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6238 ApplicationInfo applicationInfo = p.applicationInfo;
6239 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006240 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 return false;
6242 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006243 if (outInfo != null) {
6244 outInfo.uid = applicationInfo.uid;
6245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246
6247 // Delete package data from internal structures and also remove data if flag is set
6248 removePackageDataLI(p, outInfo, flags);
6249
6250 // Delete application code and resources
6251 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006252 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006253 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006254 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006255 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6256 PackageManager.INSTALL_FORWARD_LOCK : 0;
6257 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006258 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 }
6260 return true;
6261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 /*
6264 * This method handles package deletion in general
6265 */
6266 private boolean deletePackageLI(String packageName,
6267 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6268 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006269 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 return false;
6271 }
6272 PackageParser.Package p;
6273 boolean dataOnly = false;
6274 synchronized (mPackages) {
6275 p = mPackages.get(packageName);
6276 if (p == null) {
6277 //this retrieves partially installed apps
6278 dataOnly = true;
6279 PackageSetting ps = mSettings.mPackages.get(packageName);
6280 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006281 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 return false;
6283 }
6284 p = ps.pkg;
6285 }
6286 }
6287 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006288 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289 return false;
6290 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 if (dataOnly) {
6293 // Delete application data first
6294 removePackageDataLI(p, outInfo, flags);
6295 return true;
6296 }
6297 // At this point the package should have ApplicationInfo associated with it
6298 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006299 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 return false;
6301 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006302 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6304 Log.i(TAG, "Removing system package:"+p.packageName);
6305 // When an updated system application is deleted we delete the existing resources as well and
6306 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006307 ret = deleteSystemPackageLI(p, flags, outInfo);
6308 } else {
6309 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006310 // Kill application pre-emptively especially for apps on sd.
6311 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006312 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006314 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 public void clearApplicationUserData(final String packageName,
6318 final IPackageDataObserver observer) {
6319 mContext.enforceCallingOrSelfPermission(
6320 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6321 // Queue up an async operation since the package deletion may take a little while.
6322 mHandler.post(new Runnable() {
6323 public void run() {
6324 mHandler.removeCallbacks(this);
6325 final boolean succeeded;
6326 synchronized (mInstallLock) {
6327 succeeded = clearApplicationUserDataLI(packageName);
6328 }
6329 if (succeeded) {
6330 // invoke DeviceStorageMonitor's update method to clear any notifications
6331 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6332 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6333 if (dsm != null) {
6334 dsm.updateMemory();
6335 }
6336 }
6337 if(observer != null) {
6338 try {
6339 observer.onRemoveCompleted(packageName, succeeded);
6340 } catch (RemoteException e) {
6341 Log.i(TAG, "Observer no longer exists.");
6342 }
6343 } //end if observer
6344 } //end run
6345 });
6346 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 private boolean clearApplicationUserDataLI(String packageName) {
6349 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006350 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 return false;
6352 }
6353 PackageParser.Package p;
6354 boolean dataOnly = false;
6355 synchronized (mPackages) {
6356 p = mPackages.get(packageName);
6357 if(p == null) {
6358 dataOnly = true;
6359 PackageSetting ps = mSettings.mPackages.get(packageName);
6360 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006361 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 return false;
6363 }
6364 p = ps.pkg;
6365 }
6366 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 if(!dataOnly) {
6369 //need to check this only for fully installed applications
6370 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006371 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 return false;
6373 }
6374 final ApplicationInfo applicationInfo = p.applicationInfo;
6375 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006376 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 return false;
6378 }
6379 }
6380 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006381 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006383 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 + packageName);
6385 return false;
6386 }
6387 }
6388 return true;
6389 }
6390
6391 public void deleteApplicationCacheFiles(final String packageName,
6392 final IPackageDataObserver observer) {
6393 mContext.enforceCallingOrSelfPermission(
6394 android.Manifest.permission.DELETE_CACHE_FILES, null);
6395 // Queue up an async operation since the package deletion may take a little while.
6396 mHandler.post(new Runnable() {
6397 public void run() {
6398 mHandler.removeCallbacks(this);
6399 final boolean succeded;
6400 synchronized (mInstallLock) {
6401 succeded = deleteApplicationCacheFilesLI(packageName);
6402 }
6403 if(observer != null) {
6404 try {
6405 observer.onRemoveCompleted(packageName, succeded);
6406 } catch (RemoteException e) {
6407 Log.i(TAG, "Observer no longer exists.");
6408 }
6409 } //end if observer
6410 } //end run
6411 });
6412 }
6413
6414 private boolean deleteApplicationCacheFilesLI(String packageName) {
6415 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006416 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 return false;
6418 }
6419 PackageParser.Package p;
6420 synchronized (mPackages) {
6421 p = mPackages.get(packageName);
6422 }
6423 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006424 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 return false;
6426 }
6427 final ApplicationInfo applicationInfo = p.applicationInfo;
6428 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006429 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 return false;
6431 }
6432 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006433 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006435 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 + packageName);
6437 return false;
6438 }
6439 }
6440 return true;
6441 }
6442
6443 public void getPackageSizeInfo(final String packageName,
6444 final IPackageStatsObserver observer) {
6445 mContext.enforceCallingOrSelfPermission(
6446 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6447 // Queue up an async operation since the package deletion may take a little while.
6448 mHandler.post(new Runnable() {
6449 public void run() {
6450 mHandler.removeCallbacks(this);
6451 PackageStats lStats = new PackageStats(packageName);
6452 final boolean succeded;
6453 synchronized (mInstallLock) {
6454 succeded = getPackageSizeInfoLI(packageName, lStats);
6455 }
6456 if(observer != null) {
6457 try {
6458 observer.onGetStatsCompleted(lStats, succeded);
6459 } catch (RemoteException e) {
6460 Log.i(TAG, "Observer no longer exists.");
6461 }
6462 } //end if observer
6463 } //end run
6464 });
6465 }
6466
6467 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6468 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006469 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 return false;
6471 }
6472 PackageParser.Package p;
6473 boolean dataOnly = false;
6474 synchronized (mPackages) {
6475 p = mPackages.get(packageName);
6476 if(p == null) {
6477 dataOnly = true;
6478 PackageSetting ps = mSettings.mPackages.get(packageName);
6479 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006480 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 return false;
6482 }
6483 p = ps.pkg;
6484 }
6485 }
6486 String publicSrcDir = null;
6487 if(!dataOnly) {
6488 final ApplicationInfo applicationInfo = p.applicationInfo;
6489 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006490 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 return false;
6492 }
6493 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6494 }
6495 if (mInstaller != null) {
6496 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006497 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 if (res < 0) {
6499 return false;
6500 } else {
6501 return true;
6502 }
6503 }
6504 return true;
6505 }
6506
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 public void addPackageToPreferred(String packageName) {
6509 mContext.enforceCallingOrSelfPermission(
6510 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006511 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 }
6513
6514 public void removePackageFromPreferred(String packageName) {
6515 mContext.enforceCallingOrSelfPermission(
6516 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006517 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 }
6519
6520 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006521 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 }
6523
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006524 int getUidTargetSdkVersionLockedLP(int uid) {
6525 Object obj = mSettings.getUserIdLP(uid);
6526 if (obj instanceof SharedUserSetting) {
6527 SharedUserSetting sus = (SharedUserSetting)obj;
6528 final int N = sus.packages.size();
6529 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6530 Iterator<PackageSetting> it = sus.packages.iterator();
6531 int i=0;
6532 while (it.hasNext()) {
6533 PackageSetting ps = it.next();
6534 if (ps.pkg != null) {
6535 int v = ps.pkg.applicationInfo.targetSdkVersion;
6536 if (v < vers) vers = v;
6537 }
6538 }
6539 return vers;
6540 } else if (obj instanceof PackageSetting) {
6541 PackageSetting ps = (PackageSetting)obj;
6542 if (ps.pkg != null) {
6543 return ps.pkg.applicationInfo.targetSdkVersion;
6544 }
6545 }
6546 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6547 }
6548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 public void addPreferredActivity(IntentFilter filter, int match,
6550 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006551 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006552 if (mContext.checkCallingOrSelfPermission(
6553 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6554 != PackageManager.PERMISSION_GRANTED) {
6555 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6556 < Build.VERSION_CODES.FROYO) {
6557 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6558 + Binder.getCallingUid());
6559 return;
6560 }
6561 mContext.enforceCallingOrSelfPermission(
6562 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6563 }
6564
6565 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6567 mSettings.mPreferredActivities.addFilter(
6568 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006569 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006570 }
6571 }
6572
Satish Sampath8dbe6122009-06-02 23:35:54 +01006573 public void replacePreferredActivity(IntentFilter filter, int match,
6574 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006575 if (filter.countActions() != 1) {
6576 throw new IllegalArgumentException(
6577 "replacePreferredActivity expects filter to have only 1 action.");
6578 }
6579 if (filter.countCategories() != 1) {
6580 throw new IllegalArgumentException(
6581 "replacePreferredActivity expects filter to have only 1 category.");
6582 }
6583 if (filter.countDataAuthorities() != 0
6584 || filter.countDataPaths() != 0
6585 || filter.countDataSchemes() != 0
6586 || filter.countDataTypes() != 0) {
6587 throw new IllegalArgumentException(
6588 "replacePreferredActivity expects filter to have no data authorities, " +
6589 "paths, schemes or types.");
6590 }
6591 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006592 if (mContext.checkCallingOrSelfPermission(
6593 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6594 != PackageManager.PERMISSION_GRANTED) {
6595 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6596 < Build.VERSION_CODES.FROYO) {
6597 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6598 + Binder.getCallingUid());
6599 return;
6600 }
6601 mContext.enforceCallingOrSelfPermission(
6602 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6603 }
6604
Satish Sampath8dbe6122009-06-02 23:35:54 +01006605 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6606 String action = filter.getAction(0);
6607 String category = filter.getCategory(0);
6608 while (it.hasNext()) {
6609 PreferredActivity pa = it.next();
6610 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6611 it.remove();
6612 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6613 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6614 }
6615 }
6616 addPreferredActivity(filter, match, set, activity);
6617 }
6618 }
6619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006622 int uid = Binder.getCallingUid();
6623 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006624 if (pkg == null || pkg.applicationInfo.uid != uid) {
6625 if (mContext.checkCallingOrSelfPermission(
6626 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6627 != PackageManager.PERMISSION_GRANTED) {
6628 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6629 < Build.VERSION_CODES.FROYO) {
6630 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6631 + Binder.getCallingUid());
6632 return;
6633 }
6634 mContext.enforceCallingOrSelfPermission(
6635 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6636 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006637 }
6638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006640 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 }
6642 }
6643 }
6644
6645 boolean clearPackagePreferredActivitiesLP(String packageName) {
6646 boolean changed = false;
6647 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6648 while (it.hasNext()) {
6649 PreferredActivity pa = it.next();
6650 if (pa.mActivity.getPackageName().equals(packageName)) {
6651 it.remove();
6652 changed = true;
6653 }
6654 }
6655 return changed;
6656 }
6657
6658 public int getPreferredActivities(List<IntentFilter> outFilters,
6659 List<ComponentName> outActivities, String packageName) {
6660
6661 int num = 0;
6662 synchronized (mPackages) {
6663 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6664 while (it.hasNext()) {
6665 PreferredActivity pa = it.next();
6666 if (packageName == null
6667 || pa.mActivity.getPackageName().equals(packageName)) {
6668 if (outFilters != null) {
6669 outFilters.add(new IntentFilter(pa));
6670 }
6671 if (outActivities != null) {
6672 outActivities.add(pa.mActivity);
6673 }
6674 }
6675 }
6676 }
6677
6678 return num;
6679 }
6680
6681 public void setApplicationEnabledSetting(String appPackageName,
6682 int newState, int flags) {
6683 setEnabledSetting(appPackageName, null, newState, flags);
6684 }
6685
6686 public void setComponentEnabledSetting(ComponentName componentName,
6687 int newState, int flags) {
6688 setEnabledSetting(componentName.getPackageName(),
6689 componentName.getClassName(), newState, flags);
6690 }
6691
6692 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006693 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6695 || newState == COMPONENT_ENABLED_STATE_ENABLED
6696 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6697 throw new IllegalArgumentException("Invalid new component state: "
6698 + newState);
6699 }
6700 PackageSetting pkgSetting;
6701 final int uid = Binder.getCallingUid();
6702 final int permission = mContext.checkCallingPermission(
6703 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6704 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006705 boolean sendNow = false;
6706 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006707 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006709 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006711 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006713 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006714 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006715 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 }
6717 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006718 "Unknown component: " + packageName
6719 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 }
6721 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6722 throw new SecurityException(
6723 "Permission Denial: attempt to change component state from pid="
6724 + Binder.getCallingPid()
6725 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6726 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006727 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006729 if (pkgSetting.enabled == newState) {
6730 // Nothing to do
6731 return;
6732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 pkgSetting.enabled = newState;
6734 } else {
6735 // We're dealing with a component level state change
6736 switch (newState) {
6737 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006738 if (!pkgSetting.enableComponentLP(className)) {
6739 return;
6740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 break;
6742 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006743 if (!pkgSetting.disableComponentLP(className)) {
6744 return;
6745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 break;
6747 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006748 if (!pkgSetting.restoreComponentLP(className)) {
6749 return;
6750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006751 break;
6752 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006753 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006754 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 }
6756 }
6757 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006758 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006759 components = mPendingBroadcasts.get(packageName);
6760 boolean newPackage = components == null;
6761 if (newPackage) {
6762 components = new ArrayList<String>();
6763 }
6764 if (!components.contains(componentName)) {
6765 components.add(componentName);
6766 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006767 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6768 sendNow = true;
6769 // Purge entry from pending broadcast list if another one exists already
6770 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006771 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006772 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006773 if (newPackage) {
6774 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006775 }
6776 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6777 // Schedule a message
6778 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6779 }
6780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 long callingId = Binder.clearCallingIdentity();
6784 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006785 if (sendNow) {
6786 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006787 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006789 } finally {
6790 Binder.restoreCallingIdentity(callingId);
6791 }
6792 }
6793
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006794 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006795 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6796 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6797 + " components=" + componentNames);
6798 Bundle extras = new Bundle(4);
6799 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6800 String nameList[] = new String[componentNames.size()];
6801 componentNames.toArray(nameList);
6802 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006803 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6804 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006805 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006806 }
6807
Jacek Surazski65e13172009-04-28 15:26:38 +02006808 public String getInstallerPackageName(String packageName) {
6809 synchronized (mPackages) {
6810 PackageSetting pkg = mSettings.mPackages.get(packageName);
6811 if (pkg == null) {
6812 throw new IllegalArgumentException("Unknown package: " + packageName);
6813 }
6814 return pkg.installerPackageName;
6815 }
6816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 public int getApplicationEnabledSetting(String appPackageName) {
6819 synchronized (mPackages) {
6820 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6821 if (pkg == null) {
6822 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6823 }
6824 return pkg.enabled;
6825 }
6826 }
6827
6828 public int getComponentEnabledSetting(ComponentName componentName) {
6829 synchronized (mPackages) {
6830 final String packageNameStr = componentName.getPackageName();
6831 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6832 if (pkg == null) {
6833 throw new IllegalArgumentException("Unknown component: " + componentName);
6834 }
6835 final String classNameStr = componentName.getClassName();
6836 return pkg.currentEnabledStateLP(classNameStr);
6837 }
6838 }
6839
6840 public void enterSafeMode() {
6841 if (!mSystemReady) {
6842 mSafeMode = true;
6843 }
6844 }
6845
6846 public void systemReady() {
6847 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006848
6849 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006850 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006851 mContext.getContentResolver(),
6852 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006853 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006854 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006855 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 }
6858
6859 public boolean isSafeMode() {
6860 return mSafeMode;
6861 }
6862
6863 public boolean hasSystemUidErrors() {
6864 return mHasSystemUidErrors;
6865 }
6866
6867 static String arrayToString(int[] array) {
6868 StringBuffer buf = new StringBuffer(128);
6869 buf.append('[');
6870 if (array != null) {
6871 for (int i=0; i<array.length; i++) {
6872 if (i > 0) buf.append(", ");
6873 buf.append(array[i]);
6874 }
6875 }
6876 buf.append(']');
6877 return buf.toString();
6878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 @Override
6881 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6882 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6883 != PackageManager.PERMISSION_GRANTED) {
6884 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6885 + Binder.getCallingPid()
6886 + ", uid=" + Binder.getCallingUid()
6887 + " without permission "
6888 + android.Manifest.permission.DUMP);
6889 return;
6890 }
6891
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006892 String packageName = null;
6893
6894 int opti = 0;
6895 while (opti < args.length) {
6896 String opt = args[opti];
6897 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6898 break;
6899 }
6900 opti++;
6901 if ("-a".equals(opt)) {
6902 // Right now we only know how to print all.
6903 } else if ("-h".equals(opt)) {
6904 pw.println("Package manager dump options:");
6905 pw.println(" [-h] [cmd] ...");
6906 pw.println(" cmd may be one of:");
6907 pw.println(" [package.name]: info about given package");
6908 return;
6909 } else {
6910 pw.println("Unknown argument: " + opt + "; use -h for help");
6911 }
6912 }
6913
6914 // Is the caller requesting to dump a particular piece of data?
6915 if (opti < args.length) {
6916 String cmd = args[opti];
6917 opti++;
6918 // Is this a package name?
6919 if ("android".equals(cmd) || cmd.contains(".")) {
6920 packageName = cmd;
6921 }
6922 }
6923
6924 boolean printedTitle = false;
6925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006927 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6928 printedTitle = true;
6929 }
6930 if (mReceivers.dump(pw, printedTitle
6931 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6932 " ", packageName)) {
6933 printedTitle = true;
6934 }
6935 if (mServices.dump(pw, printedTitle
6936 ? "\nService Resolver Table:" : "Service Resolver Table:",
6937 " ", packageName)) {
6938 printedTitle = true;
6939 }
6940 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6941 ? "\nPreferred Activities:" : "Preferred Activities:",
6942 " ", packageName)) {
6943 printedTitle = true;
6944 }
6945 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 {
6947 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006948 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6949 continue;
6950 }
6951 if (!printedSomething) {
6952 if (printedTitle) pw.println(" ");
6953 pw.println("Permissions:");
6954 printedSomething = true;
6955 printedTitle = true;
6956 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006957 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6958 pw.print(Integer.toHexString(System.identityHashCode(p)));
6959 pw.println("):");
6960 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6961 pw.print(" uid="); pw.print(p.uid);
6962 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006963 pw.print(" type="); pw.print(p.type);
6964 pw.print(" prot="); pw.println(p.protectionLevel);
6965 if (p.packageSetting != null) {
6966 pw.print(" packageSetting="); pw.println(p.packageSetting);
6967 }
6968 if (p.perm != null) {
6969 pw.print(" perm="); pw.println(p.perm);
6970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006971 }
6972 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006973 printedSomething = false;
6974 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006975 {
6976 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006977 if (packageName != null && !packageName.equals(ps.realName)
6978 && !packageName.equals(ps.name)) {
6979 continue;
6980 }
6981 if (!printedSomething) {
6982 if (printedTitle) pw.println(" ");
6983 pw.println("Packages:");
6984 printedSomething = true;
6985 printedTitle = true;
6986 }
6987 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006988 pw.print(" Package [");
6989 pw.print(ps.realName != null ? ps.realName : ps.name);
6990 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006991 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6992 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006993 if (ps.realName != null) {
6994 pw.print(" compat name="); pw.println(ps.name);
6995 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006996 pw.print(" userId="); pw.print(ps.userId);
6997 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6998 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6999 pw.print(" pkg="); pw.println(ps.pkg);
7000 pw.print(" codePath="); pw.println(ps.codePathString);
7001 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007002 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007003 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007004 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007005 pw.print(" supportsScreens=[");
7006 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007007 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007008 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007009 if (!first) pw.print(", ");
7010 first = false;
7011 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007012 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007013 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007014 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007015 if (!first) pw.print(", ");
7016 first = false;
7017 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007018 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007019 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007020 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007021 if (!first) pw.print(", ");
7022 first = false;
7023 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007025 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007026 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007027 if (!first) pw.print(", ");
7028 first = false;
7029 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007031 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007032 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7033 if (!first) pw.print(", ");
7034 first = false;
7035 pw.print("anyDensity");
7036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007038 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007039 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7040 pw.print(" signatures="); pw.println(ps.signatures);
7041 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007042 pw.print(" haveGids="); pw.println(ps.haveGids);
7043 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007044 pw.print(" installStatus="); pw.print(ps.installStatus);
7045 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007046 if (ps.disabledComponents.size() > 0) {
7047 pw.println(" disabledComponents:");
7048 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007049 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 }
7051 }
7052 if (ps.enabledComponents.size() > 0) {
7053 pw.println(" enabledComponents:");
7054 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007055 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 }
7057 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007058 if (ps.grantedPermissions.size() > 0) {
7059 pw.println(" grantedPermissions:");
7060 for (String s : ps.grantedPermissions) {
7061 pw.print(" "); pw.println(s);
7062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007064 }
7065 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007066 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007067 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007068 for (HashMap.Entry<String, String> e
7069 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007070 if (packageName != null && !packageName.equals(e.getKey())
7071 && !packageName.equals(e.getValue())) {
7072 continue;
7073 }
7074 if (!printedSomething) {
7075 if (printedTitle) pw.println(" ");
7076 pw.println("Renamed packages:");
7077 printedSomething = true;
7078 printedTitle = true;
7079 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007080 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7081 pw.println(e.getValue());
7082 }
7083 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007084 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007085 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007086 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007087 if (packageName != null && !packageName.equals(ps.realName)
7088 && !packageName.equals(ps.name)) {
7089 continue;
7090 }
7091 if (!printedSomething) {
7092 if (printedTitle) pw.println(" ");
7093 pw.println("Hidden system packages:");
7094 printedSomething = true;
7095 printedTitle = true;
7096 }
7097 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007098 pw.print(ps.realName != null ? ps.realName : ps.name);
7099 pw.print("] (");
7100 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7101 pw.println("):");
7102 if (ps.realName != null) {
7103 pw.print(" compat name="); pw.println(ps.name);
7104 }
7105 pw.print(" userId="); pw.println(ps.userId);
7106 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7107 pw.print(" codePath="); pw.println(ps.codePathString);
7108 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7109 }
7110 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007111 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007112 {
7113 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007114 if (packageName != null && su != packageSharedUser) {
7115 continue;
7116 }
7117 if (!printedSomething) {
7118 if (printedTitle) pw.println(" ");
7119 pw.println("Shared users:");
7120 printedSomething = true;
7121 printedTitle = true;
7122 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007123 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7124 pw.print(Integer.toHexString(System.identityHashCode(su)));
7125 pw.println("):");
7126 pw.print(" userId="); pw.print(su.userId);
7127 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007128 pw.println(" grantedPermissions:");
7129 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007130 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 }
7133 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007134
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007135 if (packageName == null) {
7136 if (printedTitle) pw.println(" ");
7137 printedTitle = true;
7138 pw.println("Settings parse messages:");
7139 pw.println(mSettings.mReadMessages.toString());
7140
7141 pw.println(" ");
7142 pw.println("Package warning messages:");
7143 File fname = getSettingsProblemFile();
7144 FileInputStream in;
7145 try {
7146 in = new FileInputStream(fname);
7147 int avail = in.available();
7148 byte[] data = new byte[avail];
7149 in.read(data);
7150 pw.println(new String(data));
7151 } catch (FileNotFoundException e) {
7152 } catch (IOException e) {
7153 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007156
7157 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007158 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007159 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007160 if (packageName != null && !packageName.equals(p.info.packageName)) {
7161 continue;
7162 }
7163 if (!printedSomething) {
7164 if (printedTitle) pw.println(" ");
7165 pw.println("Registered ContentProviders:");
7166 printedSomething = true;
7167 printedTitle = true;
7168 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007169 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007170 pw.println(p.toString());
7171 }
7172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007173 }
7174
7175 static final class BasePermission {
7176 final static int TYPE_NORMAL = 0;
7177 final static int TYPE_BUILTIN = 1;
7178 final static int TYPE_DYNAMIC = 2;
7179
7180 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007181 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007182 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007183 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007184 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007185 PackageParser.Permission perm;
7186 PermissionInfo pendingInfo;
7187 int uid;
7188 int[] gids;
7189
7190 BasePermission(String _name, String _sourcePackage, int _type) {
7191 name = _name;
7192 sourcePackage = _sourcePackage;
7193 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007194 // Default to most conservative protection level.
7195 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7196 }
7197
7198 public String toString() {
7199 return "BasePermission{"
7200 + Integer.toHexString(System.identityHashCode(this))
7201 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007202 }
7203 }
7204
7205 static class PackageSignatures {
7206 private Signature[] mSignatures;
7207
7208 PackageSignatures(Signature[] sigs) {
7209 assignSignatures(sigs);
7210 }
7211
7212 PackageSignatures() {
7213 }
7214
7215 void writeXml(XmlSerializer serializer, String tagName,
7216 ArrayList<Signature> pastSignatures) throws IOException {
7217 if (mSignatures == null) {
7218 return;
7219 }
7220 serializer.startTag(null, tagName);
7221 serializer.attribute(null, "count",
7222 Integer.toString(mSignatures.length));
7223 for (int i=0; i<mSignatures.length; i++) {
7224 serializer.startTag(null, "cert");
7225 final Signature sig = mSignatures[i];
7226 final int sigHash = sig.hashCode();
7227 final int numPast = pastSignatures.size();
7228 int j;
7229 for (j=0; j<numPast; j++) {
7230 Signature pastSig = pastSignatures.get(j);
7231 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7232 serializer.attribute(null, "index", Integer.toString(j));
7233 break;
7234 }
7235 }
7236 if (j >= numPast) {
7237 pastSignatures.add(sig);
7238 serializer.attribute(null, "index", Integer.toString(numPast));
7239 serializer.attribute(null, "key", sig.toCharsString());
7240 }
7241 serializer.endTag(null, "cert");
7242 }
7243 serializer.endTag(null, tagName);
7244 }
7245
7246 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7247 throws IOException, XmlPullParserException {
7248 String countStr = parser.getAttributeValue(null, "count");
7249 if (countStr == null) {
7250 reportSettingsProblem(Log.WARN,
7251 "Error in package manager settings: <signatures> has"
7252 + " no count at " + parser.getPositionDescription());
7253 XmlUtils.skipCurrentTag(parser);
7254 }
7255 final int count = Integer.parseInt(countStr);
7256 mSignatures = new Signature[count];
7257 int pos = 0;
7258
7259 int outerDepth = parser.getDepth();
7260 int type;
7261 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7262 && (type != XmlPullParser.END_TAG
7263 || parser.getDepth() > outerDepth)) {
7264 if (type == XmlPullParser.END_TAG
7265 || type == XmlPullParser.TEXT) {
7266 continue;
7267 }
7268
7269 String tagName = parser.getName();
7270 if (tagName.equals("cert")) {
7271 if (pos < count) {
7272 String index = parser.getAttributeValue(null, "index");
7273 if (index != null) {
7274 try {
7275 int idx = Integer.parseInt(index);
7276 String key = parser.getAttributeValue(null, "key");
7277 if (key == null) {
7278 if (idx >= 0 && idx < pastSignatures.size()) {
7279 Signature sig = pastSignatures.get(idx);
7280 if (sig != null) {
7281 mSignatures[pos] = pastSignatures.get(idx);
7282 pos++;
7283 } else {
7284 reportSettingsProblem(Log.WARN,
7285 "Error in package manager settings: <cert> "
7286 + "index " + index + " is not defined at "
7287 + parser.getPositionDescription());
7288 }
7289 } else {
7290 reportSettingsProblem(Log.WARN,
7291 "Error in package manager settings: <cert> "
7292 + "index " + index + " is out of bounds at "
7293 + parser.getPositionDescription());
7294 }
7295 } else {
7296 while (pastSignatures.size() <= idx) {
7297 pastSignatures.add(null);
7298 }
7299 Signature sig = new Signature(key);
7300 pastSignatures.set(idx, sig);
7301 mSignatures[pos] = sig;
7302 pos++;
7303 }
7304 } catch (NumberFormatException e) {
7305 reportSettingsProblem(Log.WARN,
7306 "Error in package manager settings: <cert> "
7307 + "index " + index + " is not a number at "
7308 + parser.getPositionDescription());
7309 }
7310 } else {
7311 reportSettingsProblem(Log.WARN,
7312 "Error in package manager settings: <cert> has"
7313 + " no index at " + parser.getPositionDescription());
7314 }
7315 } else {
7316 reportSettingsProblem(Log.WARN,
7317 "Error in package manager settings: too "
7318 + "many <cert> tags, expected " + count
7319 + " at " + parser.getPositionDescription());
7320 }
7321 } else {
7322 reportSettingsProblem(Log.WARN,
7323 "Unknown element under <cert>: "
7324 + parser.getName());
7325 }
7326 XmlUtils.skipCurrentTag(parser);
7327 }
7328
7329 if (pos < count) {
7330 // Should never happen -- there is an error in the written
7331 // settings -- but if it does we don't want to generate
7332 // a bad array.
7333 Signature[] newSigs = new Signature[pos];
7334 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7335 mSignatures = newSigs;
7336 }
7337 }
7338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007339 private void assignSignatures(Signature[] sigs) {
7340 if (sigs == null) {
7341 mSignatures = null;
7342 return;
7343 }
7344 mSignatures = new Signature[sigs.length];
7345 for (int i=0; i<sigs.length; i++) {
7346 mSignatures[i] = sigs[i];
7347 }
7348 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007350 @Override
7351 public String toString() {
7352 StringBuffer buf = new StringBuffer(128);
7353 buf.append("PackageSignatures{");
7354 buf.append(Integer.toHexString(System.identityHashCode(this)));
7355 buf.append(" [");
7356 if (mSignatures != null) {
7357 for (int i=0; i<mSignatures.length; i++) {
7358 if (i > 0) buf.append(", ");
7359 buf.append(Integer.toHexString(
7360 System.identityHashCode(mSignatures[i])));
7361 }
7362 }
7363 buf.append("]}");
7364 return buf.toString();
7365 }
7366 }
7367
7368 static class PreferredActivity extends IntentFilter {
7369 final int mMatch;
7370 final String[] mSetPackages;
7371 final String[] mSetClasses;
7372 final String[] mSetComponents;
7373 final ComponentName mActivity;
7374 final String mShortActivity;
7375 String mParseError;
7376
7377 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7378 ComponentName activity) {
7379 super(filter);
7380 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7381 mActivity = activity;
7382 mShortActivity = activity.flattenToShortString();
7383 mParseError = null;
7384 if (set != null) {
7385 final int N = set.length;
7386 String[] myPackages = new String[N];
7387 String[] myClasses = new String[N];
7388 String[] myComponents = new String[N];
7389 for (int i=0; i<N; i++) {
7390 ComponentName cn = set[i];
7391 if (cn == null) {
7392 mSetPackages = null;
7393 mSetClasses = null;
7394 mSetComponents = null;
7395 return;
7396 }
7397 myPackages[i] = cn.getPackageName().intern();
7398 myClasses[i] = cn.getClassName().intern();
7399 myComponents[i] = cn.flattenToShortString().intern();
7400 }
7401 mSetPackages = myPackages;
7402 mSetClasses = myClasses;
7403 mSetComponents = myComponents;
7404 } else {
7405 mSetPackages = null;
7406 mSetClasses = null;
7407 mSetComponents = null;
7408 }
7409 }
7410
7411 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7412 IOException {
7413 mShortActivity = parser.getAttributeValue(null, "name");
7414 mActivity = ComponentName.unflattenFromString(mShortActivity);
7415 if (mActivity == null) {
7416 mParseError = "Bad activity name " + mShortActivity;
7417 }
7418 String matchStr = parser.getAttributeValue(null, "match");
7419 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7420 String setCountStr = parser.getAttributeValue(null, "set");
7421 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7422
7423 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7424 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7425 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7426
7427 int setPos = 0;
7428
7429 int outerDepth = parser.getDepth();
7430 int type;
7431 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7432 && (type != XmlPullParser.END_TAG
7433 || parser.getDepth() > outerDepth)) {
7434 if (type == XmlPullParser.END_TAG
7435 || type == XmlPullParser.TEXT) {
7436 continue;
7437 }
7438
7439 String tagName = parser.getName();
7440 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7441 // + parser.getDepth() + " tag=" + tagName);
7442 if (tagName.equals("set")) {
7443 String name = parser.getAttributeValue(null, "name");
7444 if (name == null) {
7445 if (mParseError == null) {
7446 mParseError = "No name in set tag in preferred activity "
7447 + mShortActivity;
7448 }
7449 } else if (setPos >= setCount) {
7450 if (mParseError == null) {
7451 mParseError = "Too many set tags in preferred activity "
7452 + mShortActivity;
7453 }
7454 } else {
7455 ComponentName cn = ComponentName.unflattenFromString(name);
7456 if (cn == null) {
7457 if (mParseError == null) {
7458 mParseError = "Bad set name " + name + " in preferred activity "
7459 + mShortActivity;
7460 }
7461 } else {
7462 myPackages[setPos] = cn.getPackageName();
7463 myClasses[setPos] = cn.getClassName();
7464 myComponents[setPos] = name;
7465 setPos++;
7466 }
7467 }
7468 XmlUtils.skipCurrentTag(parser);
7469 } else if (tagName.equals("filter")) {
7470 //Log.i(TAG, "Starting to parse filter...");
7471 readFromXml(parser);
7472 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7473 // + parser.getDepth() + " tag=" + parser.getName());
7474 } else {
7475 reportSettingsProblem(Log.WARN,
7476 "Unknown element under <preferred-activities>: "
7477 + parser.getName());
7478 XmlUtils.skipCurrentTag(parser);
7479 }
7480 }
7481
7482 if (setPos != setCount) {
7483 if (mParseError == null) {
7484 mParseError = "Not enough set tags (expected " + setCount
7485 + " but found " + setPos + ") in " + mShortActivity;
7486 }
7487 }
7488
7489 mSetPackages = myPackages;
7490 mSetClasses = myClasses;
7491 mSetComponents = myComponents;
7492 }
7493
7494 public void writeToXml(XmlSerializer serializer) throws IOException {
7495 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7496 serializer.attribute(null, "name", mShortActivity);
7497 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7498 serializer.attribute(null, "set", Integer.toString(NS));
7499 for (int s=0; s<NS; s++) {
7500 serializer.startTag(null, "set");
7501 serializer.attribute(null, "name", mSetComponents[s]);
7502 serializer.endTag(null, "set");
7503 }
7504 serializer.startTag(null, "filter");
7505 super.writeToXml(serializer);
7506 serializer.endTag(null, "filter");
7507 }
7508
7509 boolean sameSet(List<ResolveInfo> query, int priority) {
7510 if (mSetPackages == null) return false;
7511 final int NQ = query.size();
7512 final int NS = mSetPackages.length;
7513 int numMatch = 0;
7514 for (int i=0; i<NQ; i++) {
7515 ResolveInfo ri = query.get(i);
7516 if (ri.priority != priority) continue;
7517 ActivityInfo ai = ri.activityInfo;
7518 boolean good = false;
7519 for (int j=0; j<NS; j++) {
7520 if (mSetPackages[j].equals(ai.packageName)
7521 && mSetClasses[j].equals(ai.name)) {
7522 numMatch++;
7523 good = true;
7524 break;
7525 }
7526 }
7527 if (!good) return false;
7528 }
7529 return numMatch == NS;
7530 }
7531 }
7532
7533 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007534 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 HashSet<String> grantedPermissions = new HashSet<String>();
7537 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007540 setFlags(pkgFlags);
7541 }
7542
7543 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007544 this.pkgFlags = pkgFlags & (
7545 ApplicationInfo.FLAG_SYSTEM |
7546 ApplicationInfo.FLAG_FORWARD_LOCK |
7547 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 }
7549 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007551 /**
7552 * Settings base class for pending and resolved classes.
7553 */
7554 static class PackageSettingBase extends GrantedPermissions {
7555 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007556 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007557 File codePath;
7558 String codePathString;
7559 File resourcePath;
7560 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 private long timeStamp;
7562 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007563 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007565 boolean uidError;
7566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007567 PackageSignatures signatures = new PackageSignatures();
7568
7569 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007570 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007572 /* Explicitly disabled components */
7573 HashSet<String> disabledComponents = new HashSet<String>(0);
7574 /* Explicitly enabled components */
7575 HashSet<String> enabledComponents = new HashSet<String>(0);
7576 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7577 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007578
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007579 PackageSettingBase origPackage;
7580
Jacek Surazski65e13172009-04-28 15:26:38 +02007581 /* package name of the app that installed this package */
7582 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007584 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007585 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586 super(pkgFlags);
7587 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007588 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007589 init(codePath, resourcePath, pVersionCode);
7590 }
7591
7592 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007593 this.codePath = codePath;
7594 this.codePathString = codePath.toString();
7595 this.resourcePath = resourcePath;
7596 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007597 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007598 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007599
Jacek Surazski65e13172009-04-28 15:26:38 +02007600 public void setInstallerPackageName(String packageName) {
7601 installerPackageName = packageName;
7602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007603
Jacek Surazski65e13172009-04-28 15:26:38 +02007604 String getInstallerPackageName() {
7605 return installerPackageName;
7606 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 public void setInstallStatus(int newStatus) {
7609 installStatus = newStatus;
7610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007612 public int getInstallStatus() {
7613 return installStatus;
7614 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 public void setTimeStamp(long newStamp) {
7617 if (newStamp != timeStamp) {
7618 timeStamp = newStamp;
7619 timeStampString = Long.toString(newStamp);
7620 }
7621 }
7622
7623 public void setTimeStamp(long newStamp, String newStampStr) {
7624 timeStamp = newStamp;
7625 timeStampString = newStampStr;
7626 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628 public long getTimeStamp() {
7629 return timeStamp;
7630 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 public String getTimeStampStr() {
7633 return timeStampString;
7634 }
7635
7636 public void copyFrom(PackageSettingBase base) {
7637 grantedPermissions = base.grantedPermissions;
7638 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007640 timeStamp = base.timeStamp;
7641 timeStampString = base.timeStampString;
7642 signatures = base.signatures;
7643 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007644 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 disabledComponents = base.disabledComponents;
7646 enabledComponents = base.enabledComponents;
7647 enabled = base.enabled;
7648 installStatus = base.installStatus;
7649 }
7650
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007651 boolean enableComponentLP(String componentClassName) {
7652 boolean changed = disabledComponents.remove(componentClassName);
7653 changed |= enabledComponents.add(componentClassName);
7654 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655 }
7656
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007657 boolean disableComponentLP(String componentClassName) {
7658 boolean changed = enabledComponents.remove(componentClassName);
7659 changed |= disabledComponents.add(componentClassName);
7660 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 }
7662
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007663 boolean restoreComponentLP(String componentClassName) {
7664 boolean changed = enabledComponents.remove(componentClassName);
7665 changed |= disabledComponents.remove(componentClassName);
7666 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 }
7668
7669 int currentEnabledStateLP(String componentName) {
7670 if (enabledComponents.contains(componentName)) {
7671 return COMPONENT_ENABLED_STATE_ENABLED;
7672 } else if (disabledComponents.contains(componentName)) {
7673 return COMPONENT_ENABLED_STATE_DISABLED;
7674 } else {
7675 return COMPONENT_ENABLED_STATE_DEFAULT;
7676 }
7677 }
7678 }
7679
7680 /**
7681 * Settings data for a particular package we know about.
7682 */
7683 static final class PackageSetting extends PackageSettingBase {
7684 int userId;
7685 PackageParser.Package pkg;
7686 SharedUserSetting sharedUser;
7687
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007688 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007689 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007690 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007691 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 @Override
7694 public String toString() {
7695 return "PackageSetting{"
7696 + Integer.toHexString(System.identityHashCode(this))
7697 + " " + name + "/" + userId + "}";
7698 }
7699 }
7700
7701 /**
7702 * Settings data for a particular shared user ID we know about.
7703 */
7704 static final class SharedUserSetting extends GrantedPermissions {
7705 final String name;
7706 int userId;
7707 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7708 final PackageSignatures signatures = new PackageSignatures();
7709
7710 SharedUserSetting(String _name, int _pkgFlags) {
7711 super(_pkgFlags);
7712 name = _name;
7713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 @Override
7716 public String toString() {
7717 return "SharedUserSetting{"
7718 + Integer.toHexString(System.identityHashCode(this))
7719 + " " + name + "/" + userId + "}";
7720 }
7721 }
7722
7723 /**
7724 * Holds information about dynamic settings.
7725 */
7726 private static final class Settings {
7727 private final File mSettingsFilename;
7728 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007729 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 private final HashMap<String, PackageSetting> mPackages =
7731 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732 // List of replaced system applications
7733 final HashMap<String, PackageSetting> mDisabledSysPackages =
7734 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007735
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007736 // These are the last platform API version we were using for
7737 // the apps installed on internal and external storage. It is
7738 // used to grant newer permissions one time during a system upgrade.
7739 int mInternalSdkPlatform;
7740 int mExternalSdkPlatform;
7741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742 // The user's preferred activities associated with particular intent
7743 // filters.
7744 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7745 new IntentResolver<PreferredActivity, PreferredActivity>() {
7746 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007747 protected String packageForFilter(PreferredActivity filter) {
7748 return filter.mActivity.getPackageName();
7749 }
7750 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007751 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007752 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007753 out.print(prefix); out.print(
7754 Integer.toHexString(System.identityHashCode(filter)));
7755 out.print(' ');
7756 out.print(filter.mActivity.flattenToShortString());
7757 out.print(" match=0x");
7758 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007759 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007760 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007762 out.print(prefix); out.print(" ");
7763 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 }
7765 }
7766 }
7767 };
7768 private final HashMap<String, SharedUserSetting> mSharedUsers =
7769 new HashMap<String, SharedUserSetting>();
7770 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7771 private final SparseArray<Object> mOtherUserIds =
7772 new SparseArray<Object>();
7773
7774 // For reading/writing settings file.
7775 private final ArrayList<Signature> mPastSignatures =
7776 new ArrayList<Signature>();
7777
7778 // Mapping from permission names to info about them.
7779 final HashMap<String, BasePermission> mPermissions =
7780 new HashMap<String, BasePermission>();
7781
7782 // Mapping from permission tree names to info about them.
7783 final HashMap<String, BasePermission> mPermissionTrees =
7784 new HashMap<String, BasePermission>();
7785
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007786 // Packages that have been uninstalled and still need their external
7787 // storage data deleted.
7788 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7789
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007790 // Packages that have been renamed since they were first installed.
7791 // Keys are the new names of the packages, values are the original
7792 // names. The packages appear everwhere else under their original
7793 // names.
7794 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 private final StringBuilder mReadMessages = new StringBuilder();
7797
7798 private static final class PendingPackage extends PackageSettingBase {
7799 final int sharedId;
7800
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007801 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007802 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007803 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 this.sharedId = sharedId;
7805 }
7806 }
7807 private final ArrayList<PendingPackage> mPendingPackages
7808 = new ArrayList<PendingPackage>();
7809
7810 Settings() {
7811 File dataDir = Environment.getDataDirectory();
7812 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007813 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007814 systemDir.mkdirs();
7815 FileUtils.setPermissions(systemDir.toString(),
7816 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7817 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7818 -1, -1);
7819 mSettingsFilename = new File(systemDir, "packages.xml");
7820 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007821 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007822 }
7823
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007824 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007825 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 int pkgFlags, boolean create, boolean add) {
7827 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007828 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007829 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 return p;
7831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007832
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007833 PackageSetting peekPackageLP(String name) {
7834 return mPackages.get(name);
7835 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 PackageSetting p = mPackages.get(name);
7837 if (p != null && p.codePath.getPath().equals(codePath)) {
7838 return p;
7839 }
7840 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007841 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 void setInstallStatus(String pkgName, int status) {
7845 PackageSetting p = mPackages.get(pkgName);
7846 if(p != null) {
7847 if(p.getInstallStatus() != status) {
7848 p.setInstallStatus(status);
7849 }
7850 }
7851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007852
Jacek Surazski65e13172009-04-28 15:26:38 +02007853 void setInstallerPackageName(String pkgName,
7854 String installerPkgName) {
7855 PackageSetting p = mPackages.get(pkgName);
7856 if(p != null) {
7857 p.setInstallerPackageName(installerPkgName);
7858 }
7859 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007860
Jacek Surazski65e13172009-04-28 15:26:38 +02007861 String getInstallerPackageName(String pkgName) {
7862 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007863 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007864 }
7865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 int getInstallStatus(String pkgName) {
7867 PackageSetting p = mPackages.get(pkgName);
7868 if(p != null) {
7869 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007871 return -1;
7872 }
7873
7874 SharedUserSetting getSharedUserLP(String name,
7875 int pkgFlags, boolean create) {
7876 SharedUserSetting s = mSharedUsers.get(name);
7877 if (s == null) {
7878 if (!create) {
7879 return null;
7880 }
7881 s = new SharedUserSetting(name, pkgFlags);
7882 if (MULTIPLE_APPLICATION_UIDS) {
7883 s.userId = newUserIdLP(s);
7884 } else {
7885 s.userId = FIRST_APPLICATION_UID;
7886 }
7887 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7888 // < 0 means we couldn't assign a userid; fall out and return
7889 // s, which is currently null
7890 if (s.userId >= 0) {
7891 mSharedUsers.put(name, s);
7892 }
7893 }
7894
7895 return s;
7896 }
7897
7898 int disableSystemPackageLP(String name) {
7899 PackageSetting p = mPackages.get(name);
7900 if(p == null) {
7901 Log.w(TAG, "Package:"+name+" is not an installed package");
7902 return -1;
7903 }
7904 PackageSetting dp = mDisabledSysPackages.get(name);
7905 // always make sure the system package code and resource paths dont change
7906 if(dp == null) {
7907 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7908 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7909 }
7910 mDisabledSysPackages.put(name, p);
7911 }
7912 return removePackageLP(name);
7913 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 PackageSetting enableSystemPackageLP(String name) {
7916 PackageSetting p = mDisabledSysPackages.get(name);
7917 if(p == null) {
7918 Log.w(TAG, "Package:"+name+" is not disabled");
7919 return null;
7920 }
7921 // Reset flag in ApplicationInfo object
7922 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7923 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7924 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007925 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007926 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 mDisabledSysPackages.remove(name);
7928 return ret;
7929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007930
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007931 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007932 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 PackageSetting p = mPackages.get(name);
7934 if (p != null) {
7935 if (p.userId == uid) {
7936 return p;
7937 }
7938 reportSettingsProblem(Log.ERROR,
7939 "Adding duplicate package, keeping first: " + name);
7940 return null;
7941 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007942 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007943 p.userId = uid;
7944 if (addUserIdLP(uid, p, name)) {
7945 mPackages.put(name, p);
7946 return p;
7947 }
7948 return null;
7949 }
7950
7951 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7952 SharedUserSetting s = mSharedUsers.get(name);
7953 if (s != null) {
7954 if (s.userId == uid) {
7955 return s;
7956 }
7957 reportSettingsProblem(Log.ERROR,
7958 "Adding duplicate shared user, keeping first: " + name);
7959 return null;
7960 }
7961 s = new SharedUserSetting(name, pkgFlags);
7962 s.userId = uid;
7963 if (addUserIdLP(uid, s, name)) {
7964 mSharedUsers.put(name, s);
7965 return s;
7966 }
7967 return null;
7968 }
7969
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007970 // Transfer ownership of permissions from one package to another.
7971 private void transferPermissions(String origPkg, String newPkg) {
7972 // Transfer ownership of permissions to the new package.
7973 for (int i=0; i<2; i++) {
7974 HashMap<String, BasePermission> permissions =
7975 i == 0 ? mPermissionTrees : mPermissions;
7976 for (BasePermission bp : permissions.values()) {
7977 if (origPkg.equals(bp.sourcePackage)) {
7978 if (DEBUG_UPGRADE) Log.v(TAG,
7979 "Moving permission " + bp.name
7980 + " from pkg " + bp.sourcePackage
7981 + " to " + newPkg);
7982 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007983 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007984 bp.perm = null;
7985 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007986 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007987 }
7988 bp.uid = 0;
7989 bp.gids = null;
7990 }
7991 }
7992 }
7993 }
7994
7995 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007996 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007997 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 PackageSetting p = mPackages.get(name);
7999 if (p != null) {
8000 if (!p.codePath.equals(codePath)) {
8001 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008002 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008003 // This is an updated system app with versions in both system
8004 // and data partition. Just let the most recent version
8005 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008006 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008007 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008008 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008009 // Just a change in the code path is not an issue, but
8010 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008011 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008012 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008013 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008014 }
8015 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008016 reportSettingsProblem(Log.WARN,
8017 "Package " + name + " shared user changed from "
8018 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8019 + " to "
8020 + (sharedUser != null ? sharedUser.name : "<nothing>")
8021 + "; replacing with new");
8022 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008023 } else {
8024 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8025 // If what we are scanning is a system package, then
8026 // make it so, regardless of whether it was previously
8027 // installed only in the data partition.
8028 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008030 }
8031 }
8032 if (p == null) {
8033 // Create a new PackageSettings entry. this can end up here because
8034 // of code path mismatch or user id mismatch of an updated system partition
8035 if (!create) {
8036 return null;
8037 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008038 if (origPackage != null) {
8039 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008040 p = new PackageSetting(origPackage.name, name, codePath,
8041 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008042 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8043 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008044 // Note that we will retain the new package's signature so
8045 // that we can keep its data.
8046 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008047 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008048 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008049 p.sharedUser = origPackage.sharedUser;
8050 p.userId = origPackage.userId;
8051 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008052 mRenamedPackages.put(name, origPackage.name);
8053 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008054 // Update new package state.
8055 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008056 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008057 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008058 p.setTimeStamp(codePath.lastModified());
8059 p.sharedUser = sharedUser;
8060 if (sharedUser != null) {
8061 p.userId = sharedUser.userId;
8062 } else if (MULTIPLE_APPLICATION_UIDS) {
8063 // Clone the setting here for disabled system packages
8064 PackageSetting dis = mDisabledSysPackages.get(name);
8065 if (dis != null) {
8066 // For disabled packages a new setting is created
8067 // from the existing user id. This still has to be
8068 // added to list of user id's
8069 // Copy signatures from previous setting
8070 if (dis.signatures.mSignatures != null) {
8071 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8072 }
8073 p.userId = dis.userId;
8074 // Clone permissions
8075 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008076 // Clone component info
8077 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8078 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8079 // Add new setting to list of user ids
8080 addUserIdLP(p.userId, p, name);
8081 } else {
8082 // Assign new user id
8083 p.userId = newUserIdLP(p);
8084 }
8085 } else {
8086 p.userId = FIRST_APPLICATION_UID;
8087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 }
8089 if (p.userId < 0) {
8090 reportSettingsProblem(Log.WARN,
8091 "Package " + name + " could not be assigned a valid uid");
8092 return null;
8093 }
8094 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008095 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008096 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008097 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008098 }
8099 }
8100 return p;
8101 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008102
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008103 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008104 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008105 String codePath = pkg.applicationInfo.sourceDir;
8106 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008107 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008108 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008109 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008110 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008111 p.codePath = new File(codePath);
8112 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008113 }
8114 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008115 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008116 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008117 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008118 p.resourcePath = new File(resourcePath);
8119 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008120 }
8121 // Update version code if needed
8122 if (pkg.mVersionCode != p.versionCode) {
8123 p.versionCode = pkg.mVersionCode;
8124 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008125 // Update signatures if needed.
8126 if (p.signatures.mSignatures == null) {
8127 p.signatures.assignSignatures(pkg.mSignatures);
8128 }
8129 // If this app defines a shared user id initialize
8130 // the shared user signatures as well.
8131 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8132 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8133 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008134 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8135 }
8136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 // Utility method that adds a PackageSetting to mPackages and
8138 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008139 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008140 SharedUserSetting sharedUser) {
8141 mPackages.put(name, p);
8142 if (sharedUser != null) {
8143 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8144 reportSettingsProblem(Log.ERROR,
8145 "Package " + p.name + " was user "
8146 + p.sharedUser + " but is now " + sharedUser
8147 + "; I am not changing its files so it will probably fail!");
8148 p.sharedUser.packages.remove(p);
8149 } else if (p.userId != sharedUser.userId) {
8150 reportSettingsProblem(Log.ERROR,
8151 "Package " + p.name + " was user id " + p.userId
8152 + " but is now user " + sharedUser
8153 + " with id " + sharedUser.userId
8154 + "; I am not changing its files so it will probably fail!");
8155 }
8156
8157 sharedUser.packages.add(p);
8158 p.sharedUser = sharedUser;
8159 p.userId = sharedUser.userId;
8160 }
8161 }
8162
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008163 /*
8164 * Update the shared user setting when a package using
8165 * specifying the shared user id is removed. The gids
8166 * associated with each permission of the deleted package
8167 * are removed from the shared user's gid list only if its
8168 * not in use by other permissions of packages in the
8169 * shared user setting.
8170 */
8171 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008172 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008173 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008174 return;
8175 }
8176 // No sharedUserId
8177 if (deletedPs.sharedUser == null) {
8178 return;
8179 }
8180 SharedUserSetting sus = deletedPs.sharedUser;
8181 // Update permissions
8182 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8183 boolean used = false;
8184 if (!sus.grantedPermissions.contains (eachPerm)) {
8185 continue;
8186 }
8187 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008188 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008189 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008190 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008191 used = true;
8192 break;
8193 }
8194 }
8195 if (!used) {
8196 // can safely delete this permission from list
8197 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008198 }
8199 }
8200 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008201 int newGids[] = globalGids;
8202 for (String eachPerm : sus.grantedPermissions) {
8203 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008204 if (bp != null) {
8205 newGids = appendInts(newGids, bp.gids);
8206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008207 }
8208 sus.gids = newGids;
8209 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008211 private int removePackageLP(String name) {
8212 PackageSetting p = mPackages.get(name);
8213 if (p != null) {
8214 mPackages.remove(name);
8215 if (p.sharedUser != null) {
8216 p.sharedUser.packages.remove(p);
8217 if (p.sharedUser.packages.size() == 0) {
8218 mSharedUsers.remove(p.sharedUser.name);
8219 removeUserIdLP(p.sharedUser.userId);
8220 return p.sharedUser.userId;
8221 }
8222 } else {
8223 removeUserIdLP(p.userId);
8224 return p.userId;
8225 }
8226 }
8227 return -1;
8228 }
8229
8230 private boolean addUserIdLP(int uid, Object obj, Object name) {
8231 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8232 return false;
8233 }
8234
8235 if (uid >= FIRST_APPLICATION_UID) {
8236 int N = mUserIds.size();
8237 final int index = uid - FIRST_APPLICATION_UID;
8238 while (index >= N) {
8239 mUserIds.add(null);
8240 N++;
8241 }
8242 if (mUserIds.get(index) != null) {
8243 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008244 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008245 + " name=" + name);
8246 return false;
8247 }
8248 mUserIds.set(index, obj);
8249 } else {
8250 if (mOtherUserIds.get(uid) != null) {
8251 reportSettingsProblem(Log.ERROR,
8252 "Adding duplicate shared id: " + uid
8253 + " name=" + name);
8254 return false;
8255 }
8256 mOtherUserIds.put(uid, obj);
8257 }
8258 return true;
8259 }
8260
8261 public Object getUserIdLP(int uid) {
8262 if (uid >= FIRST_APPLICATION_UID) {
8263 int N = mUserIds.size();
8264 final int index = uid - FIRST_APPLICATION_UID;
8265 return index < N ? mUserIds.get(index) : null;
8266 } else {
8267 return mOtherUserIds.get(uid);
8268 }
8269 }
8270
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008271 private Set<String> findPackagesWithFlag(int flag) {
8272 Set<String> ret = new HashSet<String>();
8273 for (PackageSetting ps : mPackages.values()) {
8274 // Has to match atleast all the flag bits set on flag
8275 if ((ps.pkgFlags & flag) == flag) {
8276 ret.add(ps.name);
8277 }
8278 }
8279 return ret;
8280 }
8281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 private void removeUserIdLP(int uid) {
8283 if (uid >= FIRST_APPLICATION_UID) {
8284 int N = mUserIds.size();
8285 final int index = uid - FIRST_APPLICATION_UID;
8286 if (index < N) mUserIds.set(index, null);
8287 } else {
8288 mOtherUserIds.remove(uid);
8289 }
8290 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008292 void writeLP() {
8293 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8294
8295 // Keep the old settings around until we know the new ones have
8296 // been successfully written.
8297 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008298 // Presence of backup settings file indicates that we failed
8299 // to persist settings earlier. So preserve the older
8300 // backup for future reference since the current settings
8301 // might have been corrupted.
8302 if (!mBackupSettingsFilename.exists()) {
8303 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008304 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008305 return;
8306 }
8307 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008308 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008309 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008311 }
8312
8313 mPastSignatures.clear();
8314
8315 try {
8316 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8317
8318 //XmlSerializer serializer = XmlUtils.serializerInstance();
8319 XmlSerializer serializer = new FastXmlSerializer();
8320 serializer.setOutput(str, "utf-8");
8321 serializer.startDocument(null, true);
8322 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8323
8324 serializer.startTag(null, "packages");
8325
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008326 serializer.startTag(null, "last-platform-version");
8327 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8328 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8329 serializer.endTag(null, "last-platform-version");
8330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 serializer.startTag(null, "permission-trees");
8332 for (BasePermission bp : mPermissionTrees.values()) {
8333 writePermission(serializer, bp);
8334 }
8335 serializer.endTag(null, "permission-trees");
8336
8337 serializer.startTag(null, "permissions");
8338 for (BasePermission bp : mPermissions.values()) {
8339 writePermission(serializer, bp);
8340 }
8341 serializer.endTag(null, "permissions");
8342
8343 for (PackageSetting pkg : mPackages.values()) {
8344 writePackage(serializer, pkg);
8345 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008347 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8348 writeDisabledSysPackage(serializer, pkg);
8349 }
8350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008351 serializer.startTag(null, "preferred-activities");
8352 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8353 serializer.startTag(null, "item");
8354 pa.writeToXml(serializer);
8355 serializer.endTag(null, "item");
8356 }
8357 serializer.endTag(null, "preferred-activities");
8358
8359 for (SharedUserSetting usr : mSharedUsers.values()) {
8360 serializer.startTag(null, "shared-user");
8361 serializer.attribute(null, "name", usr.name);
8362 serializer.attribute(null, "userId",
8363 Integer.toString(usr.userId));
8364 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8365 serializer.startTag(null, "perms");
8366 for (String name : usr.grantedPermissions) {
8367 serializer.startTag(null, "item");
8368 serializer.attribute(null, "name", name);
8369 serializer.endTag(null, "item");
8370 }
8371 serializer.endTag(null, "perms");
8372 serializer.endTag(null, "shared-user");
8373 }
8374
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008375 if (mPackagesToBeCleaned.size() > 0) {
8376 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8377 serializer.startTag(null, "cleaning-package");
8378 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8379 serializer.endTag(null, "cleaning-package");
8380 }
8381 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008382
8383 if (mRenamedPackages.size() > 0) {
8384 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8385 serializer.startTag(null, "renamed-package");
8386 serializer.attribute(null, "new", e.getKey());
8387 serializer.attribute(null, "old", e.getValue());
8388 serializer.endTag(null, "renamed-package");
8389 }
8390 }
8391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008392 serializer.endTag(null, "packages");
8393
8394 serializer.endDocument();
8395
8396 str.flush();
8397 str.close();
8398
8399 // New settings successfully written, old ones are no longer
8400 // needed.
8401 mBackupSettingsFilename.delete();
8402 FileUtils.setPermissions(mSettingsFilename.toString(),
8403 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8404 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8405 |FileUtils.S_IROTH,
8406 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008407
8408 // Write package list file now, use a JournaledFile.
8409 //
8410 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8411 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8412
8413 str = new FileOutputStream(journal.chooseForWrite());
8414 try {
8415 StringBuilder sb = new StringBuilder();
8416 for (PackageSetting pkg : mPackages.values()) {
8417 ApplicationInfo ai = pkg.pkg.applicationInfo;
8418 String dataPath = ai.dataDir;
8419 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8420
8421 // Avoid any application that has a space in its path
8422 // or that is handled by the system.
8423 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8424 continue;
8425
8426 // we store on each line the following information for now:
8427 //
8428 // pkgName - package name
8429 // userId - application-specific user id
8430 // debugFlag - 0 or 1 if the package is debuggable.
8431 // dataPath - path to package's data path
8432 //
8433 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8434 //
8435 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8436 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8437 // system/core/run-as/run-as.c
8438 //
8439 sb.setLength(0);
8440 sb.append(ai.packageName);
8441 sb.append(" ");
8442 sb.append((int)ai.uid);
8443 sb.append(isDebug ? " 1 " : " 0 ");
8444 sb.append(dataPath);
8445 sb.append("\n");
8446 str.write(sb.toString().getBytes());
8447 }
8448 str.flush();
8449 str.close();
8450 journal.commit();
8451 }
8452 catch (Exception e) {
8453 journal.rollback();
8454 }
8455
8456 FileUtils.setPermissions(mPackageListFilename.toString(),
8457 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8458 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8459 |FileUtils.S_IROTH,
8460 -1, -1);
8461
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008462 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008463
8464 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008465 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 -08008466 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008467 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 -08008468 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008469 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008470 if (mSettingsFilename.exists()) {
8471 if (!mSettingsFilename.delete()) {
8472 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8473 }
8474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 //Debug.stopMethodTracing();
8476 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008477
8478 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008479 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008480 serializer.startTag(null, "updated-package");
8481 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008482 if (pkg.realName != null) {
8483 serializer.attribute(null, "realName", pkg.realName);
8484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008485 serializer.attribute(null, "codePath", pkg.codePathString);
8486 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008487 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008488 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8489 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8490 }
8491 if (pkg.sharedUser == null) {
8492 serializer.attribute(null, "userId",
8493 Integer.toString(pkg.userId));
8494 } else {
8495 serializer.attribute(null, "sharedUserId",
8496 Integer.toString(pkg.userId));
8497 }
8498 serializer.startTag(null, "perms");
8499 if (pkg.sharedUser == null) {
8500 // If this is a shared user, the permissions will
8501 // be written there. We still need to write an
8502 // empty permissions list so permissionsFixed will
8503 // be set.
8504 for (final String name : pkg.grantedPermissions) {
8505 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008506 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008507 // We only need to write signature or system permissions but this wont
8508 // match the semantics of grantedPermissions. So write all permissions.
8509 serializer.startTag(null, "item");
8510 serializer.attribute(null, "name", name);
8511 serializer.endTag(null, "item");
8512 }
8513 }
8514 }
8515 serializer.endTag(null, "perms");
8516 serializer.endTag(null, "updated-package");
8517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008518
8519 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008520 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008521 serializer.startTag(null, "package");
8522 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008523 if (pkg.realName != null) {
8524 serializer.attribute(null, "realName", pkg.realName);
8525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008526 serializer.attribute(null, "codePath", pkg.codePathString);
8527 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8528 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8529 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008530 serializer.attribute(null, "flags",
8531 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008532 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008533 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008534 if (pkg.sharedUser == null) {
8535 serializer.attribute(null, "userId",
8536 Integer.toString(pkg.userId));
8537 } else {
8538 serializer.attribute(null, "sharedUserId",
8539 Integer.toString(pkg.userId));
8540 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008541 if (pkg.uidError) {
8542 serializer.attribute(null, "uidError", "true");
8543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008544 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8545 serializer.attribute(null, "enabled",
8546 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8547 ? "true" : "false");
8548 }
8549 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8550 serializer.attribute(null, "installStatus", "false");
8551 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008552 if (pkg.installerPackageName != null) {
8553 serializer.attribute(null, "installer", pkg.installerPackageName);
8554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008555 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8556 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8557 serializer.startTag(null, "perms");
8558 if (pkg.sharedUser == null) {
8559 // If this is a shared user, the permissions will
8560 // be written there. We still need to write an
8561 // empty permissions list so permissionsFixed will
8562 // be set.
8563 for (final String name : pkg.grantedPermissions) {
8564 serializer.startTag(null, "item");
8565 serializer.attribute(null, "name", name);
8566 serializer.endTag(null, "item");
8567 }
8568 }
8569 serializer.endTag(null, "perms");
8570 }
8571 if (pkg.disabledComponents.size() > 0) {
8572 serializer.startTag(null, "disabled-components");
8573 for (final String name : pkg.disabledComponents) {
8574 serializer.startTag(null, "item");
8575 serializer.attribute(null, "name", name);
8576 serializer.endTag(null, "item");
8577 }
8578 serializer.endTag(null, "disabled-components");
8579 }
8580 if (pkg.enabledComponents.size() > 0) {
8581 serializer.startTag(null, "enabled-components");
8582 for (final String name : pkg.enabledComponents) {
8583 serializer.startTag(null, "item");
8584 serializer.attribute(null, "name", name);
8585 serializer.endTag(null, "item");
8586 }
8587 serializer.endTag(null, "enabled-components");
8588 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 serializer.endTag(null, "package");
8591 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 void writePermission(XmlSerializer serializer, BasePermission bp)
8594 throws XmlPullParserException, java.io.IOException {
8595 if (bp.type != BasePermission.TYPE_BUILTIN
8596 && bp.sourcePackage != null) {
8597 serializer.startTag(null, "item");
8598 serializer.attribute(null, "name", bp.name);
8599 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008600 if (bp.protectionLevel !=
8601 PermissionInfo.PROTECTION_NORMAL) {
8602 serializer.attribute(null, "protection",
8603 Integer.toString(bp.protectionLevel));
8604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008605 if (DEBUG_SETTINGS) Log.v(TAG,
8606 "Writing perm: name=" + bp.name + " type=" + bp.type);
8607 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8608 PermissionInfo pi = bp.perm != null ? bp.perm.info
8609 : bp.pendingInfo;
8610 if (pi != null) {
8611 serializer.attribute(null, "type", "dynamic");
8612 if (pi.icon != 0) {
8613 serializer.attribute(null, "icon",
8614 Integer.toString(pi.icon));
8615 }
8616 if (pi.nonLocalizedLabel != null) {
8617 serializer.attribute(null, "label",
8618 pi.nonLocalizedLabel.toString());
8619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008620 }
8621 }
8622 serializer.endTag(null, "item");
8623 }
8624 }
8625
8626 String getReadMessagesLP() {
8627 return mReadMessages.toString();
8628 }
8629
Oscar Montemayora8529f62009-11-18 10:14:20 -08008630 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008631 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8632 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008633 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634 while(its.hasNext()) {
8635 String key = its.next();
8636 PackageSetting ps = mPackages.get(key);
8637 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008638 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639 }
8640 }
8641 return ret;
8642 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 boolean readLP() {
8645 FileInputStream str = null;
8646 if (mBackupSettingsFilename.exists()) {
8647 try {
8648 str = new FileInputStream(mBackupSettingsFilename);
8649 mReadMessages.append("Reading from backup settings file\n");
8650 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008651 if (mSettingsFilename.exists()) {
8652 // If both the backup and settings file exist, we
8653 // ignore the settings since it might have been
8654 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008655 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008656 mSettingsFilename.delete();
8657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008658 } catch (java.io.IOException e) {
8659 // We'll try for the normal settings file.
8660 }
8661 }
8662
8663 mPastSignatures.clear();
8664
8665 try {
8666 if (str == null) {
8667 if (!mSettingsFilename.exists()) {
8668 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008669 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008670 return false;
8671 }
8672 str = new FileInputStream(mSettingsFilename);
8673 }
8674 XmlPullParser parser = Xml.newPullParser();
8675 parser.setInput(str, null);
8676
8677 int type;
8678 while ((type=parser.next()) != XmlPullParser.START_TAG
8679 && type != XmlPullParser.END_DOCUMENT) {
8680 ;
8681 }
8682
8683 if (type != XmlPullParser.START_TAG) {
8684 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008685 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 return false;
8687 }
8688
8689 int outerDepth = parser.getDepth();
8690 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8691 && (type != XmlPullParser.END_TAG
8692 || parser.getDepth() > outerDepth)) {
8693 if (type == XmlPullParser.END_TAG
8694 || type == XmlPullParser.TEXT) {
8695 continue;
8696 }
8697
8698 String tagName = parser.getName();
8699 if (tagName.equals("package")) {
8700 readPackageLP(parser);
8701 } else if (tagName.equals("permissions")) {
8702 readPermissionsLP(mPermissions, parser);
8703 } else if (tagName.equals("permission-trees")) {
8704 readPermissionsLP(mPermissionTrees, parser);
8705 } else if (tagName.equals("shared-user")) {
8706 readSharedUserLP(parser);
8707 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008708 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 } else if (tagName.equals("preferred-activities")) {
8710 readPreferredActivitiesLP(parser);
8711 } else if(tagName.equals("updated-package")) {
8712 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008713 } else if (tagName.equals("cleaning-package")) {
8714 String name = parser.getAttributeValue(null, "name");
8715 if (name != null) {
8716 mPackagesToBeCleaned.add(name);
8717 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008718 } else if (tagName.equals("renamed-package")) {
8719 String nname = parser.getAttributeValue(null, "new");
8720 String oname = parser.getAttributeValue(null, "old");
8721 if (nname != null && oname != null) {
8722 mRenamedPackages.put(nname, oname);
8723 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008724 } else if (tagName.equals("last-platform-version")) {
8725 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8726 try {
8727 String internal = parser.getAttributeValue(null, "internal");
8728 if (internal != null) {
8729 mInternalSdkPlatform = Integer.parseInt(internal);
8730 }
8731 String external = parser.getAttributeValue(null, "external");
8732 if (external != null) {
8733 mInternalSdkPlatform = Integer.parseInt(external);
8734 }
8735 } catch (NumberFormatException e) {
8736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008738 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 + parser.getName());
8740 XmlUtils.skipCurrentTag(parser);
8741 }
8742 }
8743
8744 str.close();
8745
8746 } catch(XmlPullParserException e) {
8747 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008748 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749
8750 } catch(java.io.IOException e) {
8751 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008752 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753
8754 }
8755
8756 int N = mPendingPackages.size();
8757 for (int i=0; i<N; i++) {
8758 final PendingPackage pp = mPendingPackages.get(i);
8759 Object idObj = getUserIdLP(pp.sharedId);
8760 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008761 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008762 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008763 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008764 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008765 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766 + pp.name);
8767 continue;
8768 }
8769 p.copyFrom(pp);
8770 } else if (idObj != null) {
8771 String msg = "Bad package setting: package " + pp.name
8772 + " has shared uid " + pp.sharedId
8773 + " that is not a shared uid\n";
8774 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008775 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 } else {
8777 String msg = "Bad package setting: package " + pp.name
8778 + " has shared uid " + pp.sharedId
8779 + " that is not defined\n";
8780 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008781 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782 }
8783 }
8784 mPendingPackages.clear();
8785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786 mReadMessages.append("Read completed successfully: "
8787 + mPackages.size() + " packages, "
8788 + mSharedUsers.size() + " shared uids\n");
8789
8790 return true;
8791 }
8792
8793 private int readInt(XmlPullParser parser, String ns, String name,
8794 int defValue) {
8795 String v = parser.getAttributeValue(ns, name);
8796 try {
8797 if (v == null) {
8798 return defValue;
8799 }
8800 return Integer.parseInt(v);
8801 } catch (NumberFormatException e) {
8802 reportSettingsProblem(Log.WARN,
8803 "Error in package manager settings: attribute " +
8804 name + " has bad integer value " + v + " at "
8805 + parser.getPositionDescription());
8806 }
8807 return defValue;
8808 }
8809
8810 private void readPermissionsLP(HashMap<String, BasePermission> out,
8811 XmlPullParser parser)
8812 throws IOException, XmlPullParserException {
8813 int outerDepth = parser.getDepth();
8814 int type;
8815 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8816 && (type != XmlPullParser.END_TAG
8817 || parser.getDepth() > outerDepth)) {
8818 if (type == XmlPullParser.END_TAG
8819 || type == XmlPullParser.TEXT) {
8820 continue;
8821 }
8822
8823 String tagName = parser.getName();
8824 if (tagName.equals("item")) {
8825 String name = parser.getAttributeValue(null, "name");
8826 String sourcePackage = parser.getAttributeValue(null, "package");
8827 String ptype = parser.getAttributeValue(null, "type");
8828 if (name != null && sourcePackage != null) {
8829 boolean dynamic = "dynamic".equals(ptype);
8830 BasePermission bp = new BasePermission(name, sourcePackage,
8831 dynamic
8832 ? BasePermission.TYPE_DYNAMIC
8833 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008834 bp.protectionLevel = readInt(parser, null, "protection",
8835 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 if (dynamic) {
8837 PermissionInfo pi = new PermissionInfo();
8838 pi.packageName = sourcePackage.intern();
8839 pi.name = name.intern();
8840 pi.icon = readInt(parser, null, "icon", 0);
8841 pi.nonLocalizedLabel = parser.getAttributeValue(
8842 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008843 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008844 bp.pendingInfo = pi;
8845 }
8846 out.put(bp.name, bp);
8847 } else {
8848 reportSettingsProblem(Log.WARN,
8849 "Error in package manager settings: permissions has"
8850 + " no name at " + parser.getPositionDescription());
8851 }
8852 } else {
8853 reportSettingsProblem(Log.WARN,
8854 "Unknown element reading permissions: "
8855 + parser.getName() + " at "
8856 + parser.getPositionDescription());
8857 }
8858 XmlUtils.skipCurrentTag(parser);
8859 }
8860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008862 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008863 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008865 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 String codePathStr = parser.getAttributeValue(null, "codePath");
8867 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008868 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 resourcePathStr = codePathStr;
8870 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008871 String version = parser.getAttributeValue(null, "version");
8872 int versionCode = 0;
8873 if (version != null) {
8874 try {
8875 versionCode = Integer.parseInt(version);
8876 } catch (NumberFormatException e) {
8877 }
8878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 int pkgFlags = 0;
8881 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008882 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008883 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008884 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 String timeStampStr = parser.getAttributeValue(null, "ts");
8886 if (timeStampStr != null) {
8887 try {
8888 long timeStamp = Long.parseLong(timeStampStr);
8889 ps.setTimeStamp(timeStamp, timeStampStr);
8890 } catch (NumberFormatException e) {
8891 }
8892 }
8893 String idStr = parser.getAttributeValue(null, "userId");
8894 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8895 if(ps.userId <= 0) {
8896 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8897 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8898 }
8899 int outerDepth = parser.getDepth();
8900 int type;
8901 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8902 && (type != XmlPullParser.END_TAG
8903 || parser.getDepth() > outerDepth)) {
8904 if (type == XmlPullParser.END_TAG
8905 || type == XmlPullParser.TEXT) {
8906 continue;
8907 }
8908
8909 String tagName = parser.getName();
8910 if (tagName.equals("perms")) {
8911 readGrantedPermissionsLP(parser,
8912 ps.grantedPermissions);
8913 } else {
8914 reportSettingsProblem(Log.WARN,
8915 "Unknown element under <updated-package>: "
8916 + parser.getName());
8917 XmlUtils.skipCurrentTag(parser);
8918 }
8919 }
8920 mDisabledSysPackages.put(name, ps);
8921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923 private void readPackageLP(XmlPullParser parser)
8924 throws XmlPullParserException, IOException {
8925 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008926 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 String idStr = null;
8928 String sharedIdStr = null;
8929 String codePathStr = null;
8930 String resourcePathStr = null;
8931 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008932 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008933 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 int pkgFlags = 0;
8935 String timeStampStr;
8936 long timeStamp = 0;
8937 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008938 String version = null;
8939 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940 try {
8941 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008942 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008944 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8946 codePathStr = parser.getAttributeValue(null, "codePath");
8947 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008948 version = parser.getAttributeValue(null, "version");
8949 if (version != null) {
8950 try {
8951 versionCode = Integer.parseInt(version);
8952 } catch (NumberFormatException e) {
8953 }
8954 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008955 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008956
8957 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008958 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008959 try {
8960 pkgFlags = Integer.parseInt(systemStr);
8961 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008962 }
8963 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008964 // For backward compatibility
8965 systemStr = parser.getAttributeValue(null, "system");
8966 if (systemStr != null) {
8967 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8968 } else {
8969 // Old settings that don't specify system... just treat
8970 // them as system, good enough.
8971 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008973 }
8974 timeStampStr = parser.getAttributeValue(null, "ts");
8975 if (timeStampStr != null) {
8976 try {
8977 timeStamp = Long.parseLong(timeStampStr);
8978 } catch (NumberFormatException e) {
8979 }
8980 }
8981 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8982 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8983 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8984 if (resourcePathStr == null) {
8985 resourcePathStr = codePathStr;
8986 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008987 if (realName != null) {
8988 realName = realName.intern();
8989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008990 if (name == null) {
8991 reportSettingsProblem(Log.WARN,
8992 "Error in package manager settings: <package> has no name at "
8993 + parser.getPositionDescription());
8994 } else if (codePathStr == null) {
8995 reportSettingsProblem(Log.WARN,
8996 "Error in package manager settings: <package> has no codePath at "
8997 + parser.getPositionDescription());
8998 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008999 packageSetting = addPackageLP(name.intern(), realName,
9000 new File(codePathStr), new File(resourcePathStr),
9001 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009002 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9003 + ": userId=" + userId + " pkg=" + packageSetting);
9004 if (packageSetting == null) {
9005 reportSettingsProblem(Log.ERROR,
9006 "Failure adding uid " + userId
9007 + " while parsing settings at "
9008 + parser.getPositionDescription());
9009 } else {
9010 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9011 }
9012 } else if (sharedIdStr != null) {
9013 userId = sharedIdStr != null
9014 ? Integer.parseInt(sharedIdStr) : 0;
9015 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009016 packageSetting = new PendingPackage(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 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9020 mPendingPackages.add((PendingPackage) packageSetting);
9021 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9022 + ": sharedUserId=" + userId + " pkg="
9023 + packageSetting);
9024 } else {
9025 reportSettingsProblem(Log.WARN,
9026 "Error in package manager settings: package "
9027 + name + " has bad sharedId " + sharedIdStr
9028 + " at " + parser.getPositionDescription());
9029 }
9030 } else {
9031 reportSettingsProblem(Log.WARN,
9032 "Error in package manager settings: package "
9033 + name + " has bad userId " + idStr + " at "
9034 + parser.getPositionDescription());
9035 }
9036 } catch (NumberFormatException e) {
9037 reportSettingsProblem(Log.WARN,
9038 "Error in package manager settings: package "
9039 + name + " has bad userId " + idStr + " at "
9040 + parser.getPositionDescription());
9041 }
9042 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009043 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009044 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045 final String enabledStr = parser.getAttributeValue(null, "enabled");
9046 if (enabledStr != null) {
9047 if (enabledStr.equalsIgnoreCase("true")) {
9048 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9049 } else if (enabledStr.equalsIgnoreCase("false")) {
9050 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9051 } else if (enabledStr.equalsIgnoreCase("default")) {
9052 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9053 } else {
9054 reportSettingsProblem(Log.WARN,
9055 "Error in package manager settings: package "
9056 + name + " has bad enabled value: " + idStr
9057 + " at " + parser.getPositionDescription());
9058 }
9059 } else {
9060 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9061 }
9062 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9063 if (installStatusStr != null) {
9064 if (installStatusStr.equalsIgnoreCase("false")) {
9065 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9066 } else {
9067 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9068 }
9069 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009071 int outerDepth = parser.getDepth();
9072 int type;
9073 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9074 && (type != XmlPullParser.END_TAG
9075 || parser.getDepth() > outerDepth)) {
9076 if (type == XmlPullParser.END_TAG
9077 || type == XmlPullParser.TEXT) {
9078 continue;
9079 }
9080
9081 String tagName = parser.getName();
9082 if (tagName.equals("disabled-components")) {
9083 readDisabledComponentsLP(packageSetting, parser);
9084 } else if (tagName.equals("enabled-components")) {
9085 readEnabledComponentsLP(packageSetting, parser);
9086 } else if (tagName.equals("sigs")) {
9087 packageSetting.signatures.readXml(parser, mPastSignatures);
9088 } else if (tagName.equals("perms")) {
9089 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009090 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 packageSetting.permissionsFixed = true;
9092 } else {
9093 reportSettingsProblem(Log.WARN,
9094 "Unknown element under <package>: "
9095 + parser.getName());
9096 XmlUtils.skipCurrentTag(parser);
9097 }
9098 }
9099 } else {
9100 XmlUtils.skipCurrentTag(parser);
9101 }
9102 }
9103
9104 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9105 XmlPullParser parser)
9106 throws IOException, XmlPullParserException {
9107 int outerDepth = parser.getDepth();
9108 int type;
9109 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9110 && (type != XmlPullParser.END_TAG
9111 || parser.getDepth() > outerDepth)) {
9112 if (type == XmlPullParser.END_TAG
9113 || type == XmlPullParser.TEXT) {
9114 continue;
9115 }
9116
9117 String tagName = parser.getName();
9118 if (tagName.equals("item")) {
9119 String name = parser.getAttributeValue(null, "name");
9120 if (name != null) {
9121 packageSetting.disabledComponents.add(name.intern());
9122 } else {
9123 reportSettingsProblem(Log.WARN,
9124 "Error in package manager settings: <disabled-components> has"
9125 + " no name at " + parser.getPositionDescription());
9126 }
9127 } else {
9128 reportSettingsProblem(Log.WARN,
9129 "Unknown element under <disabled-components>: "
9130 + parser.getName());
9131 }
9132 XmlUtils.skipCurrentTag(parser);
9133 }
9134 }
9135
9136 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9137 XmlPullParser parser)
9138 throws IOException, XmlPullParserException {
9139 int outerDepth = parser.getDepth();
9140 int type;
9141 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9142 && (type != XmlPullParser.END_TAG
9143 || parser.getDepth() > outerDepth)) {
9144 if (type == XmlPullParser.END_TAG
9145 || type == XmlPullParser.TEXT) {
9146 continue;
9147 }
9148
9149 String tagName = parser.getName();
9150 if (tagName.equals("item")) {
9151 String name = parser.getAttributeValue(null, "name");
9152 if (name != null) {
9153 packageSetting.enabledComponents.add(name.intern());
9154 } else {
9155 reportSettingsProblem(Log.WARN,
9156 "Error in package manager settings: <enabled-components> has"
9157 + " no name at " + parser.getPositionDescription());
9158 }
9159 } else {
9160 reportSettingsProblem(Log.WARN,
9161 "Unknown element under <enabled-components>: "
9162 + parser.getName());
9163 }
9164 XmlUtils.skipCurrentTag(parser);
9165 }
9166 }
9167
9168 private void readSharedUserLP(XmlPullParser parser)
9169 throws XmlPullParserException, IOException {
9170 String name = null;
9171 String idStr = null;
9172 int pkgFlags = 0;
9173 SharedUserSetting su = null;
9174 try {
9175 name = parser.getAttributeValue(null, "name");
9176 idStr = parser.getAttributeValue(null, "userId");
9177 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9178 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9179 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9180 }
9181 if (name == null) {
9182 reportSettingsProblem(Log.WARN,
9183 "Error in package manager settings: <shared-user> has no name at "
9184 + parser.getPositionDescription());
9185 } else if (userId == 0) {
9186 reportSettingsProblem(Log.WARN,
9187 "Error in package manager settings: shared-user "
9188 + name + " has bad userId " + idStr + " at "
9189 + parser.getPositionDescription());
9190 } else {
9191 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9192 reportSettingsProblem(Log.ERROR,
9193 "Occurred while parsing settings at "
9194 + parser.getPositionDescription());
9195 }
9196 }
9197 } catch (NumberFormatException e) {
9198 reportSettingsProblem(Log.WARN,
9199 "Error in package manager settings: package "
9200 + name + " has bad userId " + idStr + " at "
9201 + parser.getPositionDescription());
9202 };
9203
9204 if (su != null) {
9205 int outerDepth = parser.getDepth();
9206 int type;
9207 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9208 && (type != XmlPullParser.END_TAG
9209 || parser.getDepth() > outerDepth)) {
9210 if (type == XmlPullParser.END_TAG
9211 || type == XmlPullParser.TEXT) {
9212 continue;
9213 }
9214
9215 String tagName = parser.getName();
9216 if (tagName.equals("sigs")) {
9217 su.signatures.readXml(parser, mPastSignatures);
9218 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009219 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009220 } else {
9221 reportSettingsProblem(Log.WARN,
9222 "Unknown element under <shared-user>: "
9223 + parser.getName());
9224 XmlUtils.skipCurrentTag(parser);
9225 }
9226 }
9227
9228 } else {
9229 XmlUtils.skipCurrentTag(parser);
9230 }
9231 }
9232
9233 private void readGrantedPermissionsLP(XmlPullParser parser,
9234 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9235 int outerDepth = parser.getDepth();
9236 int type;
9237 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9238 && (type != XmlPullParser.END_TAG
9239 || parser.getDepth() > outerDepth)) {
9240 if (type == XmlPullParser.END_TAG
9241 || type == XmlPullParser.TEXT) {
9242 continue;
9243 }
9244
9245 String tagName = parser.getName();
9246 if (tagName.equals("item")) {
9247 String name = parser.getAttributeValue(null, "name");
9248 if (name != null) {
9249 outPerms.add(name.intern());
9250 } else {
9251 reportSettingsProblem(Log.WARN,
9252 "Error in package manager settings: <perms> has"
9253 + " no name at " + parser.getPositionDescription());
9254 }
9255 } else {
9256 reportSettingsProblem(Log.WARN,
9257 "Unknown element under <perms>: "
9258 + parser.getName());
9259 }
9260 XmlUtils.skipCurrentTag(parser);
9261 }
9262 }
9263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009264 private void readPreferredActivitiesLP(XmlPullParser parser)
9265 throws XmlPullParserException, IOException {
9266 int outerDepth = parser.getDepth();
9267 int type;
9268 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9269 && (type != XmlPullParser.END_TAG
9270 || parser.getDepth() > outerDepth)) {
9271 if (type == XmlPullParser.END_TAG
9272 || type == XmlPullParser.TEXT) {
9273 continue;
9274 }
9275
9276 String tagName = parser.getName();
9277 if (tagName.equals("item")) {
9278 PreferredActivity pa = new PreferredActivity(parser);
9279 if (pa.mParseError == null) {
9280 mPreferredActivities.addFilter(pa);
9281 } else {
9282 reportSettingsProblem(Log.WARN,
9283 "Error in package manager settings: <preferred-activity> "
9284 + pa.mParseError + " at "
9285 + parser.getPositionDescription());
9286 }
9287 } else {
9288 reportSettingsProblem(Log.WARN,
9289 "Unknown element under <preferred-activities>: "
9290 + parser.getName());
9291 XmlUtils.skipCurrentTag(parser);
9292 }
9293 }
9294 }
9295
9296 // Returns -1 if we could not find an available UserId to assign
9297 private int newUserIdLP(Object obj) {
9298 // Let's be stupidly inefficient for now...
9299 final int N = mUserIds.size();
9300 for (int i=0; i<N; i++) {
9301 if (mUserIds.get(i) == null) {
9302 mUserIds.set(i, obj);
9303 return FIRST_APPLICATION_UID + i;
9304 }
9305 }
9306
9307 // None left?
9308 if (N >= MAX_APPLICATION_UIDS) {
9309 return -1;
9310 }
9311
9312 mUserIds.add(obj);
9313 return FIRST_APPLICATION_UID + N;
9314 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009316 public PackageSetting getDisabledSystemPkg(String name) {
9317 synchronized(mPackages) {
9318 PackageSetting ps = mDisabledSysPackages.get(name);
9319 return ps;
9320 }
9321 }
9322
9323 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9324 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9325 if (Config.LOGV) {
9326 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9327 + " componentName = " + componentInfo.name);
9328 Log.v(TAG, "enabledComponents: "
9329 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9330 Log.v(TAG, "disabledComponents: "
9331 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9332 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009333 if (packageSettings == null) {
9334 if (false) {
9335 Log.w(TAG, "WAITING FOR DEBUGGER");
9336 Debug.waitForDebugger();
9337 Log.i(TAG, "We will crash!");
9338 }
9339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009340 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9341 || ((componentInfo.enabled
9342 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9343 || (componentInfo.applicationInfo.enabled
9344 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9345 && !packageSettings.disabledComponents.contains(componentInfo.name))
9346 || packageSettings.enabledComponents.contains(componentInfo.name));
9347 }
9348 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009349
9350 // ------- apps on sdcard specific code -------
9351 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009352 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009353 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009354 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009355 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009356
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009357 private String getEncryptKey() {
9358 try {
9359 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9360 if (sdEncKey == null) {
9361 sdEncKey = SystemKeyStore.getInstance().
9362 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9363 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009364 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009365 return null;
9366 }
9367 }
9368 return sdEncKey;
9369 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009370 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009371 return null;
9372 }
9373 }
9374
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009375 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009376 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009377 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009378 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009379 if (list != null) {
9380 int idx = 0;
9381 int idList[] = new int[MAX_CONTAINERS];
9382 boolean neverFound = true;
9383 for (String name : list) {
9384 // Ignore null entries
9385 if (name == null) {
9386 continue;
9387 }
9388 int sidx = name.indexOf(prefix);
9389 if (sidx == -1) {
9390 // Not a temp file. just ignore
9391 continue;
9392 }
9393 String subStr = name.substring(sidx + prefix.length());
9394 idList[idx] = -1;
9395 if (subStr != null) {
9396 try {
9397 int cid = Integer.parseInt(subStr);
9398 idList[idx++] = cid;
9399 neverFound = false;
9400 } catch (NumberFormatException e) {
9401 }
9402 }
9403 }
9404 if (!neverFound) {
9405 // Sort idList
9406 Arrays.sort(idList);
9407 for (int j = 1; j <= idList.length; j++) {
9408 if (idList[j-1] != j) {
9409 tmpIdx = j;
9410 break;
9411 }
9412 }
9413 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009414 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009415 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009416 }
9417
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009418 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009419 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009420 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009421 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9422 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9423 throw new SecurityException("Media status can only be updated by the system");
9424 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009425 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009426 Log.i(TAG, "Updating external media status from " +
9427 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9428 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009429 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9430 mediaStatus+", mMediaMounted=" + mMediaMounted);
9431 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009432 if (reportStatus) {
9433 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9434 }
9435 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009436 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009437 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009438 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009439 // Queue up an async operation since the package installation may take a little while.
9440 mHandler.post(new Runnable() {
9441 public void run() {
9442 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009443 try {
9444 updateExternalMediaStatusInner(mediaStatus);
9445 } finally {
9446 if (reportStatus) {
9447 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9448 }
9449 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009450 }
9451 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009452 }
9453
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009454 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009455 // If we are up here that means there are packages to be
9456 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009457 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009458 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009459 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009460 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009461 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009462
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009463 int uidList[] = new int[list.length];
9464 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009465 HashSet<String> removeCids = new HashSet<String>();
9466 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009467 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009468 for (String cid : list) {
9469 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009470 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9471 boolean failed = true;
9472 try {
9473 String pkgName = args.getPackageName();
9474 if (pkgName == null) {
9475 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009476 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009477 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9478 PackageSetting ps = mSettings.mPackages.get(pkgName);
9479 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009480 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009481 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9482 " corresponds to pkg : " + pkgName +
9483 " at code path: " + ps.codePathString);
9484 // We do have a valid package installed on sdcard
9485 processCids.put(args, ps.codePathString);
9486 failed = false;
9487 int uid = ps.userId;
9488 if (uid != -1) {
9489 uidList[num++] = uid;
9490 }
9491 }
9492 } finally {
9493 if (failed) {
9494 // Stale container on sdcard. Just delete
9495 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9496 removeCids.add(cid);
9497 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009498 }
9499 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009500 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009501 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009502 int uidArr[] = null;
9503 if (num > 0) {
9504 // Sort uid list
9505 Arrays.sort(uidList, 0, num);
9506 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009507 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009508 uidArr[0] = uidList[0];
9509 int di = 0;
9510 for (int i = 1; i < num; i++) {
9511 if (uidList[i-1] != uidList[i]) {
9512 uidArr[di++] = uidList[i];
9513 }
9514 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009515 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009516 // Process packages with valid entries.
9517 if (mediaStatus) {
9518 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009519 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009520 startCleaningPackages();
9521 } else {
9522 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009523 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009524 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009525 }
9526
9527 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009528 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009529 int size = pkgList.size();
9530 if (size > 0) {
9531 // Send broadcasts here
9532 Bundle extras = new Bundle();
9533 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9534 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009535 if (uidArr != null) {
9536 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9537 }
9538 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9539 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009540 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009541 }
9542 }
9543
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009544 /*
9545 * Look at potentially valid container ids from processCids
9546 * If package information doesn't match the one on record
9547 * or package scanning fails, the cid is added to list of
9548 * removeCids and cleaned up. Since cleaning up containers
9549 * involves destroying them, we do not want any parse
9550 * references to such stale containers. So force gc's
9551 * to avoid unnecessary crashes.
9552 */
9553 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009554 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009555 ArrayList<String> pkgList = new ArrayList<String>();
9556 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009557 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009558 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009559 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009560 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9561 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009562 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009563 try {
9564 // Make sure there are no container errors first.
9565 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9566 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009567 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009568 " when installing from sdcard");
9569 continue;
9570 }
9571 // Check code path here.
9572 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009573 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009574 " does not match one in settings " + codePath);
9575 continue;
9576 }
9577 // Parse package
9578 int parseFlags = PackageParser.PARSE_CHATTY |
Jeff Brown07330792010-03-30 19:57:08 -07009579 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009580 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009581 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009582 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9583 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009584 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009585 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009586 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009587 retCode = PackageManager.INSTALL_SUCCEEDED;
9588 pkgList.add(pkg.packageName);
9589 // Post process args
9590 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9591 }
9592 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009593 Slog.i(TAG, "Failed to install pkg from " +
9594 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009595 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009596 }
9597
9598 } finally {
9599 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9600 // Don't destroy container here. Wait till gc clears things up.
9601 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009602 }
9603 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009604 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009605 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009606 // If the platform SDK has changed since the last time we booted,
9607 // we need to re-grant app permission to catch any new ones that
9608 // appear. This is really a hack, and means that apps can in some
9609 // cases get permissions that the user didn't initially explicitly
9610 // allow... it would be nice to have some better way to handle
9611 // this situation.
9612 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9613 != mSdkVersion;
9614 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9615 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9616 + "; regranting permissions for external storage");
9617 mSettings.mExternalSdkPlatform = mSdkVersion;
9618
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009619 // Make sure group IDs have been assigned, and any permission
9620 // changes in other apps are accounted for
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009621 updatePermissionsLP(null, null, true, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009622 // Persist settings
9623 mSettings.writeLP();
9624 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009625 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009626 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009627 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009628 }
9629 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009630 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009631 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009632 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009633 if (removeCids != null) {
9634 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009635 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009636 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009637 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009638 }
9639
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009640 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009641 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009642 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009643 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009644 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009645 Set<SdInstallArgs> keys = processCids.keySet();
9646 for (SdInstallArgs args : keys) {
9647 String cid = args.cid;
9648 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009649 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009650 // Delete package internally
9651 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9652 synchronized (mInstallLock) {
9653 boolean res = deletePackageLI(pkgName, false,
9654 PackageManager.DONT_DELETE_DATA, outInfo);
9655 if (res) {
9656 pkgList.add(pkgName);
9657 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009658 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009659 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009660 }
9661 }
9662 }
9663 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009664 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009665 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9666 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9667 boolean ordered, boolean sticky) throws RemoteException {
9668 // Force gc now that everyone is done cleaning up, to release
9669 // references on assets.
9670 Runtime.getRuntime().gc();
9671 }
9672 });
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009673 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009674 // Just unmount all valid containers.
9675 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009676 synchronized (mInstallLock) {
9677 args.doPostDeleteLI(false);
9678 }
9679 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009680 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009681
9682 public void movePackage(final String packageName,
9683 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009684 mContext.enforceCallingOrSelfPermission(
9685 android.Manifest.permission.MOVE_PACKAGE, null);
9686 int returnCode = PackageManager.MOVE_SUCCEEDED;
9687 int currFlags = 0;
9688 int newFlags = 0;
9689 synchronized (mPackages) {
9690 PackageParser.Package pkg = mPackages.get(packageName);
9691 if (pkg == null) {
9692 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009693 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009694 // Disable moving fwd locked apps and system packages
9695 if (pkg.applicationInfo != null &&
9696 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9697 Slog.w(TAG, "Cannot move system application");
9698 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9699 } else if (pkg.applicationInfo != null &&
9700 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9701 Slog.w(TAG, "Cannot move forward locked app.");
9702 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009703 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009704 // Find install location first
9705 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9706 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9707 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009708 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009709 } else {
9710 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9711 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9712 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9713 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9714 if (newFlags == currFlags) {
9715 Slog.w(TAG, "No move required. Trying to move to same location");
9716 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9717 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009718 }
9719 }
9720 }
9721 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9722 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9723 } else {
9724 Message msg = mHandler.obtainMessage(INIT_COPY);
9725 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9726 pkg.applicationInfo.publicSourceDir);
9727 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9728 packageName);
9729 msg.obj = mp;
9730 mHandler.sendMessage(msg);
9731 }
9732 }
9733 }
9734
9735 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9736 // Queue up an async operation since the package deletion may take a little while.
9737 mHandler.post(new Runnable() {
9738 public void run() {
9739 mHandler.removeCallbacks(this);
9740 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009741 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9742 int uidArr[] = null;
9743 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009744 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009745 PackageParser.Package pkg = mPackages.get(mp.packageName);
9746 if (pkg == null ) {
9747 Slog.w(TAG, " Package " + mp.packageName +
9748 " doesn't exist. Aborting move");
9749 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9750 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9751 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9752 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9753 " Aborting move and returning error");
9754 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9755 } else {
9756 uidArr = new int[] { pkg.applicationInfo.uid };
9757 pkgList = new ArrayList<String>();
9758 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009759 }
9760 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009761 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9762 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009763 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009764 // Update package code and resource paths
9765 synchronized (mInstallLock) {
9766 synchronized (mPackages) {
9767 PackageParser.Package pkg = mPackages.get(mp.packageName);
9768 // Recheck for package again.
9769 if (pkg == null ) {
9770 Slog.w(TAG, " Package " + mp.packageName +
9771 " doesn't exist. Aborting move");
9772 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9773 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9774 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9775 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9776 " Aborting move and returning error");
9777 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9778 } else {
9779 String oldCodePath = pkg.mPath;
9780 String newCodePath = mp.targetArgs.getCodePath();
9781 String newResPath = mp.targetArgs.getResourcePath();
9782 pkg.mPath = newCodePath;
9783 // Move dex files around
9784 if (moveDexFilesLI(pkg)
9785 != PackageManager.INSTALL_SUCCEEDED) {
9786 // Moving of dex files failed. Set
9787 // error code and abort move.
9788 pkg.mPath = pkg.mScanPath;
9789 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9790 } else {
9791 pkg.mScanPath = newCodePath;
9792 pkg.applicationInfo.sourceDir = newCodePath;
9793 pkg.applicationInfo.publicSourceDir = newResPath;
9794 PackageSetting ps = (PackageSetting) pkg.mExtras;
9795 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9796 ps.codePathString = ps.codePath.getPath();
9797 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9798 ps.resourcePathString = ps.resourcePath.getPath();
9799 // Set the application info flag correctly.
9800 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9801 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9802 } else {
9803 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9804 }
9805 ps.setFlags(pkg.applicationInfo.flags);
9806 mAppDirs.remove(oldCodePath);
9807 mAppDirs.put(newCodePath, pkg);
9808 // Persist settings
9809 mSettings.writeLP();
9810 }
9811 }
9812 }
9813 // Send resources available broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009814 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009815 }
9816 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009817 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009818 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009819 // Clean up failed installation
9820 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009821 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009822 }
9823 } else {
9824 // Force a gc to clear things up.
9825 Runtime.getRuntime().gc();
9826 // Delete older code
9827 synchronized (mInstallLock) {
9828 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009829 }
9830 }
9831 IPackageMoveObserver observer = mp.observer;
9832 if (observer != null) {
9833 try {
9834 observer.packageMoved(mp.packageName, returnCode);
9835 } catch (RemoteException e) {
9836 Log.i(TAG, "Observer no longer exists.");
9837 }
9838 }
9839 }
9840 });
9841 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009842
9843 public boolean setInstallLocation(int loc) {
9844 mContext.enforceCallingOrSelfPermission(
9845 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9846 if (getInstallLocation() == loc) {
9847 return true;
9848 }
9849 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9850 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9851 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9852 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9853 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9854 return true;
9855 }
9856 return false;
9857 }
9858
9859 public int getInstallLocation() {
9860 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9861 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009863}
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009864