blob: e6663d4b27ef0498b895085ed0a0b27019df6dc7 [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 Amalapurapudaec17222010-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 Amalapurapudaec17222010-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 Hackbornc14b9ccd2009-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 Hackbornc14b9ccd2009-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 Hackbornc14b9ccd2009-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 Hackbornc14b9ccd2009-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) {
2499 if (ps == null || !ps.codePath.equals(srcFile)
2500 || ps.getTimeStamp() != srcFile.lastModified()) {
2501 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2502 if (!pp.collectCertificates(pkg, parseFlags)) {
2503 mLastScanError = pp.getParseError();
2504 return false;
2505 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002506 } else {
2507 // Lets implicitly assign existing certificates.
2508 pkg.mSignatures = ps.signatures.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 }
2510 }
2511 return true;
2512 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 /*
2515 * Scan a package and return the newly parsed package.
2516 * Returns null in case of errors and the error code is stored in mLastScanError
2517 */
2518 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002519 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002521 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002523 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002526 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 if (pkg == null) {
2528 mLastScanError = pp.getParseError();
2529 return null;
2530 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002531 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 PackageSetting updatedPkg;
2533 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002534 // Look to see if we already know about this package.
2535 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002536 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002537 // This package has been renamed to its original name. Let's
2538 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002539 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002540 }
2541 // If there was no original package, see one for the real package name.
2542 if (ps == null) {
2543 ps = mSettings.peekPackageLP(pkg.packageName);
2544 }
2545 // Check to see if this package could be hiding/updating a system
2546 // package. Must look for it either under the original or real
2547 // package name depending on our state.
2548 updatedPkg = mSettings.mDisabledSysPackages.get(
2549 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002551 // First check if this is a system package that may involve an update
2552 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2553 if (!ps.codePath.equals(scanFile)) {
2554 // The path has changed from what was last scanned... check the
2555 // version of the new path against what we have stored to determine
2556 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002557 if (pkg.mVersionCode < ps.versionCode) {
2558 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002559 // Ignore entry. Skip it.
2560 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2561 + "ignored: updated version " + ps.versionCode
2562 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002563 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2564 return null;
2565 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002566 // The current app on the system partion is better than
2567 // what we have updated to on the data partition; switch
2568 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002569 // At this point, its safely assumed that package installation for
2570 // apps in system partition will go through. If not there won't be a working
2571 // version of the app
2572 synchronized (mPackages) {
2573 // Just remove the loaded entries from package lists.
2574 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002575 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002576 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002577 + "reverting from " + ps.codePathString
2578 + ": new version " + pkg.mVersionCode
2579 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002580 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2581 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002582 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 }
2585 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002586 if (updatedPkg != null) {
2587 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2588 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2589 }
2590 // Verify certificates against what was last scanned
2591 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002592 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002593 return null;
2594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 // The apk is forward locked (not public) if its code and resources
2596 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002597 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002599 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002600 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002601
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002602 String codePath = null;
2603 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002604 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2605 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002606 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002607 } else {
2608 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002609 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002610 }
2611 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002612 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002613 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002614 codePath = pkg.mScanPath;
2615 // Set application objects path explicitly.
2616 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002618 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 }
2620
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002621 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2622 String destCodePath, String destResPath) {
2623 pkg.mPath = pkg.mScanPath = destCodePath;
2624 pkg.applicationInfo.sourceDir = destCodePath;
2625 pkg.applicationInfo.publicSourceDir = destResPath;
2626 }
2627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 private static String fixProcessName(String defProcessName,
2629 String processName, int uid) {
2630 if (processName == null) {
2631 return defProcessName;
2632 }
2633 return processName;
2634 }
2635
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002636 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002637 PackageParser.Package pkg) {
2638 if (pkgSetting.signatures.mSignatures != null) {
2639 // Already existing package. Make sure signatures match
2640 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2641 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002642 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002643 + " signatures do not match the previously installed version; ignoring!");
2644 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 return false;
2646 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002647 }
2648 // Check for shared user signatures
2649 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2650 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2651 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2652 Slog.e(TAG, "Package " + pkg.packageName
2653 + " has no signatures that match those in shared user "
2654 + pkgSetting.sharedUser.name + "; ignoring!");
2655 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2656 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 }
2659 return true;
2660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002661
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002662 public boolean performDexOpt(String packageName) {
2663 if (!mNoDexOpt) {
2664 return false;
2665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002666
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002667 PackageParser.Package p;
2668 synchronized (mPackages) {
2669 p = mPackages.get(packageName);
2670 if (p == null || p.mDidDexOpt) {
2671 return false;
2672 }
2673 }
2674 synchronized (mInstallLock) {
2675 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2676 }
2677 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002678
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002679 static final int DEX_OPT_SKIPPED = 0;
2680 static final int DEX_OPT_PERFORMED = 1;
2681 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002682
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002683 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2684 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002685 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002686 String path = pkg.mScanPath;
2687 int ret = 0;
2688 try {
2689 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002690 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002691 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002692 pkg.mDidDexOpt = true;
2693 performed = true;
2694 }
2695 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002696 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002697 ret = -1;
2698 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002699 Slog.w(TAG, "IOException reading apk: " + path, e);
2700 ret = -1;
2701 } catch (dalvik.system.StaleDexCacheError e) {
2702 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2703 ret = -1;
2704 } catch (Exception e) {
2705 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002706 ret = -1;
2707 }
2708 if (ret < 0) {
2709 //error from installer
2710 return DEX_OPT_FAILED;
2711 }
2712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002713
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002714 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2715 }
2716
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002717 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2718 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002719 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002720 + " to " + newPkg.packageName
2721 + ": old package not in system partition");
2722 return false;
2723 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002724 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002725 + " to " + newPkg.packageName
2726 + ": old package still exists");
2727 return false;
2728 }
2729 return true;
2730 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002731
2732 private File getDataPathForPackage(PackageParser.Package pkg) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002733 return new File(mAppDataDir, pkg.packageName);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002734 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002735
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002736 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2737 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002738 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002739 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2740 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002741 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002742 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002743 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2744 return null;
2745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 mScanningPath = scanFile;
2747 if (pkg == null) {
2748 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2749 return null;
2750 }
2751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2753 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2754 }
2755
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002756 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 synchronized (mPackages) {
2758 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002759 Slog.w(TAG, "*************************************************");
2760 Slog.w(TAG, "Core android package being redefined. Skipping.");
2761 Slog.w(TAG, " file=" + mScanningPath);
2762 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2764 return null;
2765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 // Set up information for our fall-back user intent resolution
2768 // activity.
2769 mPlatformPackage = pkg;
2770 pkg.mVersionCode = mSdkVersion;
2771 mAndroidApplication = pkg.applicationInfo;
2772 mResolveActivity.applicationInfo = mAndroidApplication;
2773 mResolveActivity.name = ResolverActivity.class.getName();
2774 mResolveActivity.packageName = mAndroidApplication.packageName;
2775 mResolveActivity.processName = mAndroidApplication.processName;
2776 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2777 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2778 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2779 mResolveActivity.exported = true;
2780 mResolveActivity.enabled = true;
2781 mResolveInfo.activityInfo = mResolveActivity;
2782 mResolveInfo.priority = 0;
2783 mResolveInfo.preferredOrder = 0;
2784 mResolveInfo.match = 0;
2785 mResolveComponentName = new ComponentName(
2786 mAndroidApplication.packageName, mResolveActivity.name);
2787 }
2788 }
2789
2790 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002791 TAG, "Scanning package " + pkg.packageName);
2792 if (mPackages.containsKey(pkg.packageName)
2793 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002794 Slog.w(TAG, "*************************************************");
2795 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002797 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2799 return null;
2800 }
2801
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002802 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002803 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2804 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 SharedUserSetting suid = null;
2807 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002808
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002809 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2810 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002811 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002812 pkg.mRealPackage = null;
2813 pkg.mAdoptPermissions = null;
2814 }
2815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 synchronized (mPackages) {
2817 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002818 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2819 if (mTmpSharedLibraries == null ||
2820 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2821 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2822 }
2823 int num = 0;
2824 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2825 for (int i=0; i<N; i++) {
2826 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002828 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002830 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2832 return null;
2833 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002834 mTmpSharedLibraries[num] = file;
2835 num++;
2836 }
2837 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2838 for (int i=0; i<N; i++) {
2839 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2840 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002841 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002842 + " desires unavailable shared library "
2843 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2844 } else {
2845 mTmpSharedLibraries[num] = file;
2846 num++;
2847 }
2848 }
2849 if (num > 0) {
2850 pkg.usesLibraryFiles = new String[num];
2851 System.arraycopy(mTmpSharedLibraries, 0,
2852 pkg.usesLibraryFiles, 0, num);
2853 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002854
Dianne Hackborn49237342009-08-27 20:08:01 -07002855 if (pkg.reqFeatures != null) {
2856 N = pkg.reqFeatures.size();
2857 for (int i=0; i<N; i++) {
2858 FeatureInfo fi = pkg.reqFeatures.get(i);
2859 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2860 // Don't care.
2861 continue;
2862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002863
Dianne Hackborn49237342009-08-27 20:08:01 -07002864 if (fi.name != null) {
2865 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002866 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002867 + " requires unavailable feature "
2868 + fi.name + "; failing!");
2869 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2870 return null;
2871 }
2872 }
2873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 }
2875 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 if (pkg.mSharedUserId != null) {
2878 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2879 pkg.applicationInfo.flags, true);
2880 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002881 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 + " for shared user failed");
2883 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2884 return null;
2885 }
2886 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2887 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2888 + suid.userId + "): packages=" + suid.packages);
2889 }
2890 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002891
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002892 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002893 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002894 Log.w(TAG, "WAITING FOR DEBUGGER");
2895 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002896 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2897 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002898 }
2899 }
2900
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002901 // Check if we are renaming from an original package name.
2902 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002903 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002904 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002905 // This package may need to be renamed to a previously
2906 // installed name. Let's check on that...
2907 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002908 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002909 // This package had originally been installed as the
2910 // original name, and we have already taken care of
2911 // transitioning to the new one. Just update the new
2912 // one to continue using the old name.
2913 realName = pkg.mRealPackage;
2914 if (!pkg.packageName.equals(renamed)) {
2915 // Callers into this function may have already taken
2916 // care of renaming the package; only do it here if
2917 // it is not already done.
2918 pkg.setPackageName(renamed);
2919 }
2920
Dianne Hackbornc1552392010-03-03 16:19:01 -08002921 } else {
2922 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2923 if ((origPackage=mSettings.peekPackageLP(
2924 pkg.mOriginalPackages.get(i))) != null) {
2925 // We do have the package already installed under its
2926 // original name... should we use it?
2927 if (!verifyPackageUpdate(origPackage, pkg)) {
2928 // New package is not compatible with original.
2929 origPackage = null;
2930 continue;
2931 } else if (origPackage.sharedUser != null) {
2932 // Make sure uid is compatible between packages.
2933 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002934 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002935 + " to " + pkg.packageName + ": old uid "
2936 + origPackage.sharedUser.name
2937 + " differs from " + pkg.mSharedUserId);
2938 origPackage = null;
2939 continue;
2940 }
2941 } else {
2942 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2943 + pkg.packageName + " to old name " + origPackage.name);
2944 }
2945 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002946 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002947 }
2948 }
2949 }
2950
2951 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002952 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002953 + " was transferred to another, but its .apk remains");
2954 }
2955
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002956 // Just create the setting, don't add it yet. For already existing packages
2957 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002958 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 destResourceFile, pkg.applicationInfo.flags, true, false);
2960 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002961 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2963 return null;
2964 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002965
2966 if (pkgSetting.origPackage != null) {
2967 // If we are first transitioning from an original package,
2968 // fix up the new package's name now. We need to do this after
2969 // looking up the package under its new name, so getPackageLP
2970 // can take care of fiddling things correctly.
2971 pkg.setPackageName(origPackage.name);
2972
2973 // File a report about this.
2974 String msg = "New package " + pkgSetting.realName
2975 + " renamed to replace old package " + pkgSetting.name;
2976 reportSettingsProblem(Log.WARN, msg);
2977
2978 // Make a note of it.
2979 mTransferedPackages.add(origPackage.name);
2980
2981 // No longer need to retain this.
2982 pkgSetting.origPackage = null;
2983 }
2984
2985 if (realName != null) {
2986 // Make a note of it.
2987 mTransferedPackages.add(pkg.packageName);
2988 }
2989
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002990 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2992 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 pkg.applicationInfo.uid = pkgSetting.userId;
2995 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002996
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002997 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002998 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 return null;
3000 }
3001 // The signature has changed, but this package is in the system
3002 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003003 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 // However... if this package is part of a shared user, but it
3005 // doesn't match the signature of the shared user, let's fail.
3006 // What this means is that you can't change the signatures
3007 // associated with an overall shared user, which doesn't seem all
3008 // that unreasonable.
3009 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003010 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3011 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3012 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3014 return null;
3015 }
3016 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003017 // File a report about this.
3018 String msg = "System package " + pkg.packageName
3019 + " signature changed; retaining data.";
3020 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003022
The Android Open Source Project10592532009-03-18 17:39:46 -07003023 // Verify that this new package doesn't have any content providers
3024 // that conflict with existing packages. Only do this if the
3025 // package isn't already installed, since we don't want to break
3026 // things that are installed.
3027 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3028 int N = pkg.providers.size();
3029 int i;
3030 for (i=0; i<N; i++) {
3031 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003032 if (p.info.authority != null) {
3033 String names[] = p.info.authority.split(";");
3034 for (int j = 0; j < names.length; j++) {
3035 if (mProviders.containsKey(names[j])) {
3036 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003037 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003038 " (in package " + pkg.applicationInfo.packageName +
3039 ") is already used by "
3040 + ((other != null && other.getComponentName() != null)
3041 ? other.getComponentName().getPackageName() : "?"));
3042 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3043 return null;
3044 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003045 }
3046 }
3047 }
3048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 }
3050
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003051 final String pkgName = pkg.packageName;
3052
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003053 if (pkg.mAdoptPermissions != null) {
3054 // This package wants to adopt ownership of permissions from
3055 // another package.
3056 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3057 String origName = pkg.mAdoptPermissions.get(i);
3058 PackageSetting orig = mSettings.peekPackageLP(origName);
3059 if (orig != null) {
3060 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003061 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003062 + origName + " to " + pkg.packageName);
3063 mSettings.transferPermissions(origName, pkg.packageName);
3064 }
3065 }
3066 }
3067 }
3068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 long scanFileTime = scanFile.lastModified();
3070 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3071 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3072 pkg.applicationInfo.processName = fixProcessName(
3073 pkg.applicationInfo.packageName,
3074 pkg.applicationInfo.processName,
3075 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076
3077 File dataPath;
3078 if (mPlatformPackage == pkg) {
3079 // The system package is special.
3080 dataPath = new File (Environment.getDataDirectory(), "system");
3081 pkg.applicationInfo.dataDir = dataPath.getPath();
3082 } else {
3083 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003084 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003085
3086 boolean uidError = false;
3087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 if (dataPath.exists()) {
3089 mOutPermissions[1] = 0;
3090 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3091 if (mOutPermissions[1] == pkg.applicationInfo.uid
3092 || !Process.supportsProcesses()) {
3093 pkg.applicationInfo.dataDir = dataPath.getPath();
3094 } else {
3095 boolean recovered = false;
3096 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3097 // If this is a system app, we can at least delete its
3098 // current data so the application will still work.
3099 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003100 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003101 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 // Old data gone!
3103 String msg = "System package " + pkg.packageName
3104 + " has changed from uid: "
3105 + mOutPermissions[1] + " to "
3106 + pkg.applicationInfo.uid + "; old data erased";
3107 reportSettingsProblem(Log.WARN, msg);
3108 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 // And now re-install the app.
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003111 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 pkg.applicationInfo.uid);
3113 if (ret == -1) {
3114 // Ack should not happen!
3115 msg = "System package " + pkg.packageName
3116 + " could not have data directory re-created after delete.";
3117 reportSettingsProblem(Log.WARN, msg);
3118 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3119 return null;
3120 }
3121 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 if (!recovered) {
3124 mHasSystemUidErrors = true;
3125 }
3126 }
3127 if (!recovered) {
3128 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3129 + pkg.applicationInfo.uid + "/fs_"
3130 + mOutPermissions[1];
3131 String msg = "Package " + pkg.packageName
3132 + " has mismatched uid: "
3133 + mOutPermissions[1] + " on disk, "
3134 + pkg.applicationInfo.uid + " in settings";
3135 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003136 mSettings.mReadMessages.append(msg);
3137 mSettings.mReadMessages.append('\n');
3138 uidError = true;
3139 if (!pkgSetting.uidError) {
3140 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
3143 }
3144 }
3145 pkg.applicationInfo.dataDir = dataPath.getPath();
3146 } else {
3147 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3148 Log.v(TAG, "Want this data dir: " + dataPath);
3149 //invoke installer to do the actual installation
3150 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003151 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152 pkg.applicationInfo.uid);
3153 if(ret < 0) {
3154 // Error from installer
3155 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3156 return null;
3157 }
3158 } else {
3159 dataPath.mkdirs();
3160 if (dataPath.exists()) {
3161 FileUtils.setPermissions(
3162 dataPath.toString(),
3163 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3164 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3165 }
3166 }
3167 if (dataPath.exists()) {
3168 pkg.applicationInfo.dataDir = dataPath.getPath();
3169 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003170 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171 pkg.applicationInfo.dataDir = null;
3172 }
3173 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003174
3175 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 }
3177
3178 // Perform shared library installation and dex validation and
3179 // optimization, if this is not a system app.
3180 if (mInstaller != null) {
3181 String path = scanFile.getPath();
3182 if (scanFileNewer) {
3183 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003184 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3185 if (err != PackageManager.INSTALL_SUCCEEDED) {
3186 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 return null;
3188 }
3189 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003190 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003191
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003192 if ((scanMode&SCAN_NO_DEX) == 0) {
3193 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003194 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3195 return null;
3196 }
3197 }
3198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 if (mFactoryTest && pkg.requestedPermissions.contains(
3201 android.Manifest.permission.FACTORY_TEST)) {
3202 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3203 }
3204
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003205 // Request the ActivityManager to kill the process(only for existing packages)
3206 // so that we do not end up in a confused state while the user is still using the older
3207 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003208 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003209 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003210 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003211 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003214 // We don't expect installation to fail beyond this point,
3215 if ((scanMode&SCAN_MONITOR) != 0) {
3216 mAppDirs.put(pkg.mPath, pkg);
3217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003219 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003221 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003222 // Make sure we don't accidentally delete its data.
3223 mSettings.mPackagesToBeCleaned.remove(pkgName);
3224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 int N = pkg.providers.size();
3226 StringBuilder r = null;
3227 int i;
3228 for (i=0; i<N; i++) {
3229 PackageParser.Provider p = pkg.providers.get(i);
3230 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3231 p.info.processName, pkg.applicationInfo.uid);
3232 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3233 p.info.name), p);
3234 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003235 if (p.info.authority != null) {
3236 String names[] = p.info.authority.split(";");
3237 p.info.authority = null;
3238 for (int j = 0; j < names.length; j++) {
3239 if (j == 1 && p.syncable) {
3240 // We only want the first authority for a provider to possibly be
3241 // syncable, so if we already added this provider using a different
3242 // authority clear the syncable flag. We copy the provider before
3243 // changing it because the mProviders object contains a reference
3244 // to a provider that we don't want to change.
3245 // Only do this for the second authority since the resulting provider
3246 // object can be the same for all future authorities for this provider.
3247 p = new PackageParser.Provider(p);
3248 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003250 if (!mProviders.containsKey(names[j])) {
3251 mProviders.put(names[j], p);
3252 if (p.info.authority == null) {
3253 p.info.authority = names[j];
3254 } else {
3255 p.info.authority = p.info.authority + ";" + names[j];
3256 }
3257 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3258 Log.d(TAG, "Registered content provider: " + names[j] +
3259 ", className = " + p.info.name +
3260 ", isSyncable = " + p.info.isSyncable);
3261 } else {
3262 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003263 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003264 " (in package " + pkg.applicationInfo.packageName +
3265 "): name already used by "
3266 + ((other != null && other.getComponentName() != null)
3267 ? other.getComponentName().getPackageName() : "?"));
3268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 }
3270 }
3271 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3272 if (r == null) {
3273 r = new StringBuilder(256);
3274 } else {
3275 r.append(' ');
3276 }
3277 r.append(p.info.name);
3278 }
3279 }
3280 if (r != null) {
3281 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3282 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 N = pkg.services.size();
3285 r = null;
3286 for (i=0; i<N; i++) {
3287 PackageParser.Service s = pkg.services.get(i);
3288 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3289 s.info.processName, pkg.applicationInfo.uid);
3290 mServices.addService(s);
3291 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3292 if (r == null) {
3293 r = new StringBuilder(256);
3294 } else {
3295 r.append(' ');
3296 }
3297 r.append(s.info.name);
3298 }
3299 }
3300 if (r != null) {
3301 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3302 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 N = pkg.receivers.size();
3305 r = null;
3306 for (i=0; i<N; i++) {
3307 PackageParser.Activity a = pkg.receivers.get(i);
3308 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3309 a.info.processName, pkg.applicationInfo.uid);
3310 mReceivers.addActivity(a, "receiver");
3311 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3312 if (r == null) {
3313 r = new StringBuilder(256);
3314 } else {
3315 r.append(' ');
3316 }
3317 r.append(a.info.name);
3318 }
3319 }
3320 if (r != null) {
3321 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3322 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 N = pkg.activities.size();
3325 r = null;
3326 for (i=0; i<N; i++) {
3327 PackageParser.Activity a = pkg.activities.get(i);
3328 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3329 a.info.processName, pkg.applicationInfo.uid);
3330 mActivities.addActivity(a, "activity");
3331 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3332 if (r == null) {
3333 r = new StringBuilder(256);
3334 } else {
3335 r.append(' ');
3336 }
3337 r.append(a.info.name);
3338 }
3339 }
3340 if (r != null) {
3341 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3342 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 N = pkg.permissionGroups.size();
3345 r = null;
3346 for (i=0; i<N; i++) {
3347 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3348 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3349 if (cur == null) {
3350 mPermissionGroups.put(pg.info.name, pg);
3351 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3352 if (r == null) {
3353 r = new StringBuilder(256);
3354 } else {
3355 r.append(' ');
3356 }
3357 r.append(pg.info.name);
3358 }
3359 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003360 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 + pg.info.packageName + " ignored: original from "
3362 + cur.info.packageName);
3363 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3364 if (r == null) {
3365 r = new StringBuilder(256);
3366 } else {
3367 r.append(' ');
3368 }
3369 r.append("DUP:");
3370 r.append(pg.info.name);
3371 }
3372 }
3373 }
3374 if (r != null) {
3375 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3376 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 N = pkg.permissions.size();
3379 r = null;
3380 for (i=0; i<N; i++) {
3381 PackageParser.Permission p = pkg.permissions.get(i);
3382 HashMap<String, BasePermission> permissionMap =
3383 p.tree ? mSettings.mPermissionTrees
3384 : mSettings.mPermissions;
3385 p.group = mPermissionGroups.get(p.info.group);
3386 if (p.info.group == null || p.group != null) {
3387 BasePermission bp = permissionMap.get(p.info.name);
3388 if (bp == null) {
3389 bp = new BasePermission(p.info.name, p.info.packageName,
3390 BasePermission.TYPE_NORMAL);
3391 permissionMap.put(p.info.name, bp);
3392 }
3393 if (bp.perm == null) {
3394 if (bp.sourcePackage == null
3395 || bp.sourcePackage.equals(p.info.packageName)) {
3396 BasePermission tree = findPermissionTreeLP(p.info.name);
3397 if (tree == null
3398 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003399 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 bp.perm = p;
3401 bp.uid = pkg.applicationInfo.uid;
3402 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3403 if (r == null) {
3404 r = new StringBuilder(256);
3405 } else {
3406 r.append(' ');
3407 }
3408 r.append(p.info.name);
3409 }
3410 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003411 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 + p.info.packageName + " ignored: base tree "
3413 + tree.name + " is from package "
3414 + tree.sourcePackage);
3415 }
3416 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003417 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 + p.info.packageName + " ignored: original from "
3419 + bp.sourcePackage);
3420 }
3421 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3422 if (r == null) {
3423 r = new StringBuilder(256);
3424 } else {
3425 r.append(' ');
3426 }
3427 r.append("DUP:");
3428 r.append(p.info.name);
3429 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003430 if (bp.perm == p) {
3431 bp.protectionLevel = p.info.protectionLevel;
3432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003434 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 + p.info.packageName + " ignored: no group "
3436 + p.group);
3437 }
3438 }
3439 if (r != null) {
3440 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3441 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 N = pkg.instrumentation.size();
3444 r = null;
3445 for (i=0; i<N; i++) {
3446 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3447 a.info.packageName = pkg.applicationInfo.packageName;
3448 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3449 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3450 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003451 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3453 if (r == null) {
3454 r = new StringBuilder(256);
3455 } else {
3456 r.append(' ');
3457 }
3458 r.append(a.info.name);
3459 }
3460 }
3461 if (r != null) {
3462 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3463 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003464
Dianne Hackborn854060af2009-07-09 18:14:31 -07003465 if (pkg.protectedBroadcasts != null) {
3466 N = pkg.protectedBroadcasts.size();
3467 for (i=0; i<N; i++) {
3468 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3469 }
3470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 pkgSetting.setTimeStamp(scanFileTime);
3473 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 return pkg;
3476 }
3477
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003478 private void killApplication(String pkgName, int uid) {
3479 // Request the ActivityManager to kill the process(only for existing packages)
3480 // so that we do not end up in a confused state while the user is still using the older
3481 // version of the application while the new one gets installed.
3482 IActivityManager am = ActivityManagerNative.getDefault();
3483 if (am != null) {
3484 try {
3485 am.killApplicationWithUid(pkgName, uid);
3486 } catch (RemoteException e) {
3487 }
3488 }
3489 }
3490
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003491 // The following constants are returned by cachePackageSharedLibsForAbiLI
3492 // to indicate if native shared libraries were found in the package.
3493 // Values are:
3494 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3495 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3496 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3497 // in package (and not installed)
3498 //
3499 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3500 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3501 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003503 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3504 // and automatically copy them to /data/data/<appname>/lib if present.
3505 //
3506 // NOTE: this method may throw an IOException if the library cannot
3507 // be copied to its final destination, e.g. if there isn't enough
3508 // room left on the data partition, or a ZipException if the package
3509 // file is malformed.
3510 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003511 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3512 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003513 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3514 final String apkLib = "lib/";
3515 final int apkLibLen = apkLib.length();
3516 final int cpuAbiLen = cpuAbi.length();
3517 final String libPrefix = "lib";
3518 final int libPrefixLen = libPrefix.length();
3519 final String libSuffix = ".so";
3520 final int libSuffixLen = libSuffix.length();
3521 boolean hasNativeLibraries = false;
3522 boolean installedNativeLibraries = false;
3523
3524 // the minimum length of a valid native shared library of the form
3525 // lib/<something>/lib<name>.so.
3526 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3527
3528 ZipFile zipFile = new ZipFile(scanFile);
3529 Enumeration<ZipEntry> entries =
3530 (Enumeration<ZipEntry>) zipFile.entries();
3531
3532 while (entries.hasMoreElements()) {
3533 ZipEntry entry = entries.nextElement();
3534 // skip directories
3535 if (entry.isDirectory()) {
3536 continue;
3537 }
3538 String entryName = entry.getName();
3539
3540 // check that the entry looks like lib/<something>/lib<name>.so
3541 // here, but don't check the ABI just yet.
3542 //
3543 // - must be sufficiently long
3544 // - must end with libSuffix, i.e. ".so"
3545 // - must start with apkLib, i.e. "lib/"
3546 if (entryName.length() < minEntryLen ||
3547 !entryName.endsWith(libSuffix) ||
3548 !entryName.startsWith(apkLib) ) {
3549 continue;
3550 }
3551
3552 // file name must start with libPrefix, i.e. "lib"
3553 int lastSlash = entryName.lastIndexOf('/');
3554
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003555 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003556 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3557 continue;
3558 }
3559
3560 hasNativeLibraries = true;
3561
3562 // check the cpuAbi now, between lib/ and /lib<name>.so
3563 //
3564 if (lastSlash != apkLibLen + cpuAbiLen ||
3565 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3566 continue;
3567
3568 // extract the library file name, ensure it doesn't contain
3569 // weird characters. we're guaranteed here that it doesn't contain
3570 // a directory separator though.
3571 String libFileName = entryName.substring(lastSlash+1);
3572 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3573 continue;
3574 }
3575
3576 installedNativeLibraries = true;
3577
3578 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3579 File.separator + libFileName;
3580 File sharedLibraryFile = new File(sharedLibraryFilePath);
3581 if (! sharedLibraryFile.exists() ||
3582 sharedLibraryFile.length() != entry.getSize() ||
3583 sharedLibraryFile.lastModified() != entry.getTime()) {
3584 if (Config.LOGD) {
3585 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003587 if (mInstaller == null) {
3588 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003589 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003590 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003591 sharedLibraryFile);
3592 }
3593 }
3594 if (!hasNativeLibraries)
3595 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3596
3597 if (!installedNativeLibraries)
3598 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3599
3600 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3601 }
3602
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003603 // Find the gdbserver executable program in a package at
3604 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3605 //
3606 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3607 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3608 //
3609 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3610 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3611 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3612 final String GDBSERVER = "gdbserver";
3613 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3614
3615 ZipFile zipFile = new ZipFile(scanFile);
3616 Enumeration<ZipEntry> entries =
3617 (Enumeration<ZipEntry>) zipFile.entries();
3618
3619 while (entries.hasMoreElements()) {
3620 ZipEntry entry = entries.nextElement();
3621 // skip directories
3622 if (entry.isDirectory()) {
3623 continue;
3624 }
3625 String entryName = entry.getName();
3626
3627 if (!entryName.equals(apkGdbServerPath)) {
3628 continue;
3629 }
3630
3631 String installGdbServerPath = installGdbServerDir.getPath() +
3632 "/" + GDBSERVER;
3633 File installGdbServerFile = new File(installGdbServerPath);
3634 if (! installGdbServerFile.exists() ||
3635 installGdbServerFile.length() != entry.getSize() ||
3636 installGdbServerFile.lastModified() != entry.getTime()) {
3637 if (Config.LOGD) {
3638 Log.d(TAG, "Caching gdbserver " + entry.getName());
3639 }
3640 if (mInstaller == null) {
3641 installGdbServerDir.mkdir();
3642 }
3643 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3644 installGdbServerFile);
3645 }
3646 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3647 }
3648 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3649 }
3650
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003651 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3652 // and copy them to /data/data/<appname>/lib.
3653 //
3654 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3655 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3656 // one if ro.product.cpu.abi2 is defined.
3657 //
3658 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3659 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003660 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003661 try {
3662 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3663
3664 // some architectures are capable of supporting several CPU ABIs
3665 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3666 // this is indicated by the definition of the ro.product.cpu.abi2
3667 // system property.
3668 //
3669 // only scan the package twice in case of ABI mismatch
3670 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003671 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003672 if (cpuAbi2 != null) {
3673 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003675
3676 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003677 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003678 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003680
3681 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3682 cpuAbi = cpuAbi2;
3683 }
3684 }
3685
3686 // for debuggable packages, also extract gdbserver from lib/<abi>
3687 // into /data/data/<appname>/lib too.
3688 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3689 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3690 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3691 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3692 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003695 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003696 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003697 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003699 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003700 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003702 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 }
3704
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003705 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003706 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003707 File binaryDir,
3708 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 InputStream inputStream = zipFile.getInputStream(entry);
3710 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003711 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003713 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 // now need to be left as world readable and owned by the system.
3715 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3716 ! tempFile.setLastModified(entry.getTime()) ||
3717 FileUtils.setPermissions(tempFilePath,
3718 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003719 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003721 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 // Failed to properly write file.
3723 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003724 throw new IOException("Couldn't create cached binary "
3725 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 }
3727 } finally {
3728 inputStream.close();
3729 }
3730 }
3731
3732 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3733 if (chatty && Config.LOGD) Log.d(
3734 TAG, "Removing package " + pkg.applicationInfo.packageName );
3735
3736 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 mPackages.remove(pkg.applicationInfo.packageName);
3740 if (pkg.mPath != null) {
3741 mAppDirs.remove(pkg.mPath);
3742 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 PackageSetting ps = (PackageSetting)pkg.mExtras;
3745 if (ps != null && ps.sharedUser != null) {
3746 // XXX don't do this until the data is removed.
3747 if (false) {
3748 ps.sharedUser.packages.remove(ps);
3749 if (ps.sharedUser.packages.size() == 0) {
3750 // Remove.
3751 }
3752 }
3753 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 int N = pkg.providers.size();
3756 StringBuilder r = null;
3757 int i;
3758 for (i=0; i<N; i++) {
3759 PackageParser.Provider p = pkg.providers.get(i);
3760 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3761 p.info.name));
3762 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 /* The is another ContentProvider with this authority when
3765 * this app was installed so this authority is null,
3766 * Ignore it as we don't have to unregister the provider.
3767 */
3768 continue;
3769 }
3770 String names[] = p.info.authority.split(";");
3771 for (int j = 0; j < names.length; j++) {
3772 if (mProviders.get(names[j]) == p) {
3773 mProviders.remove(names[j]);
3774 if (chatty && Config.LOGD) Log.d(
3775 TAG, "Unregistered content provider: " + names[j] +
3776 ", className = " + p.info.name +
3777 ", isSyncable = " + p.info.isSyncable);
3778 }
3779 }
3780 if (chatty) {
3781 if (r == null) {
3782 r = new StringBuilder(256);
3783 } else {
3784 r.append(' ');
3785 }
3786 r.append(p.info.name);
3787 }
3788 }
3789 if (r != null) {
3790 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3791 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 N = pkg.services.size();
3794 r = null;
3795 for (i=0; i<N; i++) {
3796 PackageParser.Service s = pkg.services.get(i);
3797 mServices.removeService(s);
3798 if (chatty) {
3799 if (r == null) {
3800 r = new StringBuilder(256);
3801 } else {
3802 r.append(' ');
3803 }
3804 r.append(s.info.name);
3805 }
3806 }
3807 if (r != null) {
3808 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3809 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 N = pkg.receivers.size();
3812 r = null;
3813 for (i=0; i<N; i++) {
3814 PackageParser.Activity a = pkg.receivers.get(i);
3815 mReceivers.removeActivity(a, "receiver");
3816 if (chatty) {
3817 if (r == null) {
3818 r = new StringBuilder(256);
3819 } else {
3820 r.append(' ');
3821 }
3822 r.append(a.info.name);
3823 }
3824 }
3825 if (r != null) {
3826 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3827 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 N = pkg.activities.size();
3830 r = null;
3831 for (i=0; i<N; i++) {
3832 PackageParser.Activity a = pkg.activities.get(i);
3833 mActivities.removeActivity(a, "activity");
3834 if (chatty) {
3835 if (r == null) {
3836 r = new StringBuilder(256);
3837 } else {
3838 r.append(' ');
3839 }
3840 r.append(a.info.name);
3841 }
3842 }
3843 if (r != null) {
3844 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 N = pkg.permissions.size();
3848 r = null;
3849 for (i=0; i<N; i++) {
3850 PackageParser.Permission p = pkg.permissions.get(i);
3851 boolean tree = false;
3852 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3853 if (bp == null) {
3854 tree = true;
3855 bp = mSettings.mPermissionTrees.get(p.info.name);
3856 }
3857 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003858 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 if (chatty) {
3860 if (r == null) {
3861 r = new StringBuilder(256);
3862 } else {
3863 r.append(' ');
3864 }
3865 r.append(p.info.name);
3866 }
3867 }
3868 }
3869 if (r != null) {
3870 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 N = pkg.instrumentation.size();
3874 r = null;
3875 for (i=0; i<N; i++) {
3876 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003877 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 if (chatty) {
3879 if (r == null) {
3880 r = new StringBuilder(256);
3881 } else {
3882 r.append(' ');
3883 }
3884 r.append(a.info.name);
3885 }
3886 }
3887 if (r != null) {
3888 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3889 }
3890 }
3891 }
3892
3893 private static final boolean isPackageFilename(String name) {
3894 return name != null && name.endsWith(".apk");
3895 }
3896
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003897 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3898 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3899 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3900 return true;
3901 }
3902 }
3903 return false;
3904 }
3905
3906 private void updatePermissionsLP(String changingPkg,
3907 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 // Make sure there are no dangling permission trees.
3909 Iterator<BasePermission> it = mSettings.mPermissionTrees
3910 .values().iterator();
3911 while (it.hasNext()) {
3912 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003913 if (bp.packageSetting == null) {
3914 // We may not yet have parsed the package, so just see if
3915 // we still know about its settings.
3916 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3917 }
3918 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003919 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 + " from package " + bp.sourcePackage);
3921 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003922 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3923 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3924 Slog.i(TAG, "Removing old permission tree: " + bp.name
3925 + " from package " + bp.sourcePackage);
3926 grantPermissions = true;
3927 it.remove();
3928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 }
3930 }
3931
3932 // Make sure all dynamic permissions have been assigned to a package,
3933 // and make sure there are no dangling permissions.
3934 it = mSettings.mPermissions.values().iterator();
3935 while (it.hasNext()) {
3936 BasePermission bp = it.next();
3937 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3938 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3939 + bp.name + " pkg=" + bp.sourcePackage
3940 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003941 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 BasePermission tree = findPermissionTreeLP(bp.name);
3943 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003944 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 bp.perm = new PackageParser.Permission(tree.perm.owner,
3946 new PermissionInfo(bp.pendingInfo));
3947 bp.perm.info.packageName = tree.perm.info.packageName;
3948 bp.perm.info.name = bp.name;
3949 bp.uid = tree.uid;
3950 }
3951 }
3952 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003953 if (bp.packageSetting == null) {
3954 // We may not yet have parsed the package, so just see if
3955 // we still know about its settings.
3956 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3957 }
3958 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003959 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 + " from package " + bp.sourcePackage);
3961 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003962 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3963 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3964 Slog.i(TAG, "Removing old permission: " + bp.name
3965 + " from package " + bp.sourcePackage);
3966 grantPermissions = true;
3967 it.remove();
3968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 }
3970 }
3971
3972 // Now update the permissions for all packages, in particular
3973 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003974 if (grantPermissions) {
3975 for (PackageParser.Package pkg : mPackages.values()) {
3976 if (pkg != pkgInfo) {
3977 grantPermissionsLP(pkg, false);
3978 }
3979 }
3980 }
3981
3982 if (pkgInfo != null) {
3983 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 }
3985 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3988 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3989 if (ps == null) {
3990 return;
3991 }
3992 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003993 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 if (replace) {
3996 ps.permissionsFixed = false;
3997 if (gp == ps) {
3998 gp.grantedPermissions.clear();
3999 gp.gids = mGlobalGids;
4000 }
4001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 if (gp.gids == null) {
4004 gp.gids = mGlobalGids;
4005 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 final int N = pkg.requestedPermissions.size();
4008 for (int i=0; i<N; i++) {
4009 String name = pkg.requestedPermissions.get(i);
4010 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 if (false) {
4012 if (gp != ps) {
4013 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004014 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 }
4016 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004017 if (bp != null && bp.packageSetting != null) {
4018 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004020 boolean allowedSig = false;
4021 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4022 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004024 } else if (bp.packageSetting == null) {
4025 // This permission is invalid; skip it.
4026 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004027 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4028 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4029 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004031 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004033 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4035 // For updated system applications, the signatureOrSystem permission
4036 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004037 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4039 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4040 if(sysPs.grantedPermissions.contains(perm)) {
4041 allowed = true;
4042 } else {
4043 allowed = false;
4044 }
4045 } else {
4046 allowed = true;
4047 }
4048 }
4049 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004050 if (allowed) {
4051 allowedSig = true;
4052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 } else {
4054 allowed = false;
4055 }
4056 if (false) {
4057 if (gp != ps) {
4058 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4059 }
4060 }
4061 if (allowed) {
4062 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4063 && ps.permissionsFixed) {
4064 // If this is an existing, non-system package, then
4065 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004066 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004068 // Except... if this is a permission that was added
4069 // to the platform (note: need to only do this when
4070 // updating the platform).
4071 final int NP = PackageParser.NEW_PERMISSIONS.length;
4072 for (int ip=0; ip<NP; ip++) {
4073 final PackageParser.NewPermissionInfo npi
4074 = PackageParser.NEW_PERMISSIONS[ip];
4075 if (npi.name.equals(perm)
4076 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4077 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004078 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004079 + pkg.packageName);
4080 break;
4081 }
4082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 }
4084 }
4085 if (allowed) {
4086 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004087 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 gp.grantedPermissions.add(perm);
4089 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004090 } else if (!ps.haveGids) {
4091 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 }
4093 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004094 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 + " to package " + pkg.packageName
4096 + " because it was previously installed without");
4097 }
4098 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004099 if (gp.grantedPermissions.remove(perm)) {
4100 changedPermission = true;
4101 gp.gids = removeInts(gp.gids, bp.gids);
4102 Slog.i(TAG, "Un-granting permission " + perm
4103 + " from package " + pkg.packageName
4104 + " (protectionLevel=" + bp.protectionLevel
4105 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4106 + ")");
4107 } else {
4108 Slog.w(TAG, "Not granting permission " + perm
4109 + " to package " + pkg.packageName
4110 + " (protectionLevel=" + bp.protectionLevel
4111 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4112 + ")");
4113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 }
4115 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004116 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 + " in package " + pkg.packageName);
4118 }
4119 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004120
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004121 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004122 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4123 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 // This is the first that we have heard about this package, so the
4125 // permissions we have now selected are fixed until explicitly
4126 // changed.
4127 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004129 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 private final class ActivityIntentResolver
4133 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004134 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004136 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004137 }
4138
Mihai Preda074edef2009-05-18 17:13:31 +02004139 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004141 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4143 }
4144
Mihai Predaeae850c2009-05-13 10:13:48 +02004145 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4146 ArrayList<PackageParser.Activity> packageActivities) {
4147 if (packageActivities == null) {
4148 return null;
4149 }
4150 mFlags = flags;
4151 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4152 int N = packageActivities.size();
4153 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4154 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004155
4156 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004157 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004158 intentFilters = packageActivities.get(i).intents;
4159 if (intentFilters != null && intentFilters.size() > 0) {
4160 listCut.add(intentFilters);
4161 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004162 }
4163 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4164 }
4165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004167 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 if (SHOW_INFO || Config.LOGV) Log.v(
4169 TAG, " " + type + " " +
4170 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4171 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4172 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004173 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4175 if (SHOW_INFO || Config.LOGV) {
4176 Log.v(TAG, " IntentFilter:");
4177 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4178 }
4179 if (!intent.debugCheck()) {
4180 Log.w(TAG, "==> For Activity " + a.info.name);
4181 }
4182 addFilter(intent);
4183 }
4184 }
4185
4186 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004187 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 if (SHOW_INFO || Config.LOGV) Log.v(
4189 TAG, " " + type + " " +
4190 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4191 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4192 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004193 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4195 if (SHOW_INFO || Config.LOGV) {
4196 Log.v(TAG, " IntentFilter:");
4197 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4198 }
4199 removeFilter(intent);
4200 }
4201 }
4202
4203 @Override
4204 protected boolean allowFilterResult(
4205 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4206 ActivityInfo filterAi = filter.activity.info;
4207 for (int i=dest.size()-1; i>=0; i--) {
4208 ActivityInfo destAi = dest.get(i).activityInfo;
4209 if (destAi.name == filterAi.name
4210 && destAi.packageName == filterAi.packageName) {
4211 return false;
4212 }
4213 }
4214 return true;
4215 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004218 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4219 return info.activity.owner.packageName;
4220 }
4221
4222 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4224 int match) {
4225 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4226 return null;
4227 }
4228 final PackageParser.Activity activity = info.activity;
4229 if (mSafeMode && (activity.info.applicationInfo.flags
4230 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4231 return null;
4232 }
4233 final ResolveInfo res = new ResolveInfo();
4234 res.activityInfo = PackageParser.generateActivityInfo(activity,
4235 mFlags);
4236 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4237 res.filter = info;
4238 }
4239 res.priority = info.getPriority();
4240 res.preferredOrder = activity.owner.mPreferredOrder;
4241 //System.out.println("Result: " + res.activityInfo.className +
4242 // " = " + res.priority);
4243 res.match = match;
4244 res.isDefault = info.hasDefault;
4245 res.labelRes = info.labelRes;
4246 res.nonLocalizedLabel = info.nonLocalizedLabel;
4247 res.icon = info.icon;
4248 return res;
4249 }
4250
4251 @Override
4252 protected void sortResults(List<ResolveInfo> results) {
4253 Collections.sort(results, mResolvePrioritySorter);
4254 }
4255
4256 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004257 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004259 out.print(prefix); out.print(
4260 Integer.toHexString(System.identityHashCode(filter.activity)));
4261 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004262 out.print(filter.activity.getComponentShortName());
4263 out.print(" filter ");
4264 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 }
4266
4267// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4268// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4269// final List<ResolveInfo> retList = Lists.newArrayList();
4270// while (i.hasNext()) {
4271// final ResolveInfo resolveInfo = i.next();
4272// if (isEnabledLP(resolveInfo.activityInfo)) {
4273// retList.add(resolveInfo);
4274// }
4275// }
4276// return retList;
4277// }
4278
4279 // Keys are String (activity class name), values are Activity.
4280 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4281 = new HashMap<ComponentName, PackageParser.Activity>();
4282 private int mFlags;
4283 }
4284
4285 private final class ServiceIntentResolver
4286 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004287 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004289 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 }
4291
Mihai Preda074edef2009-05-18 17:13:31 +02004292 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004294 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4296 }
4297
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004298 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4299 ArrayList<PackageParser.Service> packageServices) {
4300 if (packageServices == null) {
4301 return null;
4302 }
4303 mFlags = flags;
4304 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4305 int N = packageServices.size();
4306 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4307 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4308
4309 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4310 for (int i = 0; i < N; ++i) {
4311 intentFilters = packageServices.get(i).intents;
4312 if (intentFilters != null && intentFilters.size() > 0) {
4313 listCut.add(intentFilters);
4314 }
4315 }
4316 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4317 }
4318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004320 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 if (SHOW_INFO || Config.LOGV) Log.v(
4322 TAG, " " + (s.info.nonLocalizedLabel != null
4323 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4324 if (SHOW_INFO || Config.LOGV) Log.v(
4325 TAG, " Class=" + s.info.name);
4326 int NI = s.intents.size();
4327 int j;
4328 for (j=0; j<NI; j++) {
4329 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4330 if (SHOW_INFO || Config.LOGV) {
4331 Log.v(TAG, " IntentFilter:");
4332 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4333 }
4334 if (!intent.debugCheck()) {
4335 Log.w(TAG, "==> For Service " + s.info.name);
4336 }
4337 addFilter(intent);
4338 }
4339 }
4340
4341 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004342 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 if (SHOW_INFO || Config.LOGV) Log.v(
4344 TAG, " " + (s.info.nonLocalizedLabel != null
4345 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4346 if (SHOW_INFO || Config.LOGV) Log.v(
4347 TAG, " Class=" + s.info.name);
4348 int NI = s.intents.size();
4349 int j;
4350 for (j=0; j<NI; j++) {
4351 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4352 if (SHOW_INFO || Config.LOGV) {
4353 Log.v(TAG, " IntentFilter:");
4354 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4355 }
4356 removeFilter(intent);
4357 }
4358 }
4359
4360 @Override
4361 protected boolean allowFilterResult(
4362 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4363 ServiceInfo filterSi = filter.service.info;
4364 for (int i=dest.size()-1; i>=0; i--) {
4365 ServiceInfo destAi = dest.get(i).serviceInfo;
4366 if (destAi.name == filterSi.name
4367 && destAi.packageName == filterSi.packageName) {
4368 return false;
4369 }
4370 }
4371 return true;
4372 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004375 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4376 return info.service.owner.packageName;
4377 }
4378
4379 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4381 int match) {
4382 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4383 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4384 return null;
4385 }
4386 final PackageParser.Service service = info.service;
4387 if (mSafeMode && (service.info.applicationInfo.flags
4388 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4389 return null;
4390 }
4391 final ResolveInfo res = new ResolveInfo();
4392 res.serviceInfo = PackageParser.generateServiceInfo(service,
4393 mFlags);
4394 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4395 res.filter = filter;
4396 }
4397 res.priority = info.getPriority();
4398 res.preferredOrder = service.owner.mPreferredOrder;
4399 //System.out.println("Result: " + res.activityInfo.className +
4400 // " = " + res.priority);
4401 res.match = match;
4402 res.isDefault = info.hasDefault;
4403 res.labelRes = info.labelRes;
4404 res.nonLocalizedLabel = info.nonLocalizedLabel;
4405 res.icon = info.icon;
4406 return res;
4407 }
4408
4409 @Override
4410 protected void sortResults(List<ResolveInfo> results) {
4411 Collections.sort(results, mResolvePrioritySorter);
4412 }
4413
4414 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004415 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004417 out.print(prefix); out.print(
4418 Integer.toHexString(System.identityHashCode(filter.service)));
4419 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004420 out.print(filter.service.getComponentShortName());
4421 out.print(" filter ");
4422 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004423 }
4424
4425// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4426// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4427// final List<ResolveInfo> retList = Lists.newArrayList();
4428// while (i.hasNext()) {
4429// final ResolveInfo resolveInfo = (ResolveInfo) i;
4430// if (isEnabledLP(resolveInfo.serviceInfo)) {
4431// retList.add(resolveInfo);
4432// }
4433// }
4434// return retList;
4435// }
4436
4437 // Keys are String (activity class name), values are Activity.
4438 private final HashMap<ComponentName, PackageParser.Service> mServices
4439 = new HashMap<ComponentName, PackageParser.Service>();
4440 private int mFlags;
4441 };
4442
4443 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4444 new Comparator<ResolveInfo>() {
4445 public int compare(ResolveInfo r1, ResolveInfo r2) {
4446 int v1 = r1.priority;
4447 int v2 = r2.priority;
4448 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4449 if (v1 != v2) {
4450 return (v1 > v2) ? -1 : 1;
4451 }
4452 v1 = r1.preferredOrder;
4453 v2 = r2.preferredOrder;
4454 if (v1 != v2) {
4455 return (v1 > v2) ? -1 : 1;
4456 }
4457 if (r1.isDefault != r2.isDefault) {
4458 return r1.isDefault ? -1 : 1;
4459 }
4460 v1 = r1.match;
4461 v2 = r2.match;
4462 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4463 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4464 }
4465 };
4466
4467 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4468 new Comparator<ProviderInfo>() {
4469 public int compare(ProviderInfo p1, ProviderInfo p2) {
4470 final int v1 = p1.initOrder;
4471 final int v2 = p2.initOrder;
4472 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4473 }
4474 };
4475
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004476 private static final void sendPackageBroadcast(String action, String pkg,
4477 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 IActivityManager am = ActivityManagerNative.getDefault();
4479 if (am != null) {
4480 try {
4481 final Intent intent = new Intent(action,
4482 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4483 if (extras != null) {
4484 intent.putExtras(extras);
4485 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004486 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004487 am.broadcastIntent(null, intent, null, finishedReceiver,
4488 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 } catch (RemoteException ex) {
4490 }
4491 }
4492 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004493
4494 public String nextPackageToClean(String lastPackage) {
4495 synchronized (mPackages) {
4496 if (!mMediaMounted) {
4497 // If the external storage is no longer mounted at this point,
4498 // the caller may not have been able to delete all of this
4499 // packages files and can not delete any more. Bail.
4500 return null;
4501 }
4502 if (lastPackage != null) {
4503 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4504 }
4505 return mSettings.mPackagesToBeCleaned.size() > 0
4506 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4507 }
4508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004510 void schedulePackageCleaning(String packageName) {
4511 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4512 }
4513
4514 void startCleaningPackages() {
4515 synchronized (mPackages) {
4516 if (!mMediaMounted) {
4517 return;
4518 }
4519 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4520 return;
4521 }
4522 }
4523 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4524 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4525 IActivityManager am = ActivityManagerNative.getDefault();
4526 if (am != null) {
4527 try {
4528 am.startService(null, intent, null);
4529 } catch (RemoteException e) {
4530 }
4531 }
4532 }
4533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 private final class AppDirObserver extends FileObserver {
4535 public AppDirObserver(String path, int mask, boolean isrom) {
4536 super(path, mask);
4537 mRootDir = path;
4538 mIsRom = isrom;
4539 }
4540
4541 public void onEvent(int event, String path) {
4542 String removedPackage = null;
4543 int removedUid = -1;
4544 String addedPackage = null;
4545 int addedUid = -1;
4546
4547 synchronized (mInstallLock) {
4548 String fullPathStr = null;
4549 File fullPath = null;
4550 if (path != null) {
4551 fullPath = new File(mRootDir, path);
4552 fullPathStr = fullPath.getPath();
4553 }
4554
4555 if (Config.LOGV) Log.v(
4556 TAG, "File " + fullPathStr + " changed: "
4557 + Integer.toHexString(event));
4558
4559 if (!isPackageFilename(path)) {
4560 if (Config.LOGV) Log.v(
4561 TAG, "Ignoring change of non-package file: " + fullPathStr);
4562 return;
4563 }
4564
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004565 // Ignore packages that are being installed or
4566 // have just been installed.
4567 if (ignoreCodePath(fullPathStr)) {
4568 return;
4569 }
4570 PackageParser.Package p = null;
4571 synchronized (mPackages) {
4572 p = mAppDirs.get(fullPathStr);
4573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004574 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004575 if (p != null) {
4576 removePackageLI(p, true);
4577 removedPackage = p.applicationInfo.packageName;
4578 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004579 }
4580 }
4581
4582 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004584 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004585 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4586 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 PackageParser.PARSE_CHATTY |
4588 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004589 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 if (p != null) {
4591 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004592 updatePermissionsLP(p.packageName, p,
4593 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 }
4595 addedPackage = p.applicationInfo.packageName;
4596 addedUid = p.applicationInfo.uid;
4597 }
4598 }
4599 }
4600
4601 synchronized (mPackages) {
4602 mSettings.writeLP();
4603 }
4604 }
4605
4606 if (removedPackage != null) {
4607 Bundle extras = new Bundle(1);
4608 extras.putInt(Intent.EXTRA_UID, removedUid);
4609 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004610 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4611 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 }
4613 if (addedPackage != null) {
4614 Bundle extras = new Bundle(1);
4615 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004616 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4617 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618 }
4619 }
4620
4621 private final String mRootDir;
4622 private final boolean mIsRom;
4623 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 /* Called when a downloaded package installation has been confirmed by the user */
4626 public void installPackage(
4627 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004628 installPackage(packageURI, observer, flags, null);
4629 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004630
Jacek Surazski65e13172009-04-28 15:26:38 +02004631 /* Called when a downloaded package installation has been confirmed by the user */
4632 public void installPackage(
4633 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4634 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 mContext.enforceCallingOrSelfPermission(
4636 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004637
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004638 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004639 msg.obj = new InstallParams(packageURI, observer, flags,
4640 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004641 mHandler.sendMessage(msg);
4642 }
4643
Christopher Tate1bb69062010-02-19 17:02:12 -08004644 public void finishPackageInstall(int token) {
4645 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4646 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4647 mHandler.sendMessage(msg);
4648 }
4649
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004650 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 // Queue up an async operation since the package installation may take a little while.
4652 mHandler.post(new Runnable() {
4653 public void run() {
4654 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004655 // Result object to be returned
4656 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004657 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004658 res.uid = -1;
4659 res.pkg = null;
4660 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004661 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004662 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004663 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004664 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004665 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004666 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004667 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004668
4669 // A restore should be performed at this point if (a) the install
4670 // succeeded, (b) the operation is not an update, and (c) the new
4671 // package has a backupAgent defined.
4672 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004673 boolean doRestore = (!update
4674 && res.pkg != null
4675 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004676
4677 // Set up the post-install work request bookkeeping. This will be used
4678 // and cleaned up by the post-install event handling regardless of whether
4679 // there's a restore pass performed. Token values are >= 1.
4680 int token;
4681 if (mNextInstallToken < 0) mNextInstallToken = 1;
4682 token = mNextInstallToken++;
4683
4684 PostInstallData data = new PostInstallData(args, res);
4685 mRunningInstalls.put(token, data);
4686 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4687
4688 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4689 // Pass responsibility to the Backup Manager. It will perform a
4690 // restore if appropriate, then pass responsibility back to the
4691 // Package Manager to run the post-install observer callbacks
4692 // and broadcasts.
4693 IBackupManager bm = IBackupManager.Stub.asInterface(
4694 ServiceManager.getService(Context.BACKUP_SERVICE));
4695 if (bm != null) {
4696 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4697 + " to BM for possible restore");
4698 try {
4699 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4700 } catch (RemoteException e) {
4701 // can't happen; the backup manager is local
4702 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004703 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004704 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004705 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004706 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004707 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004708 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004710 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004711
4712 if (!doRestore) {
4713 // No restore possible, or the Backup Manager was mysteriously not
4714 // available -- just fire the post-install work request directly.
4715 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4716 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4717 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 }
4720 });
4721 }
4722
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004723 abstract class HandlerParams {
4724 final static int MAX_RETRIES = 4;
4725 int retry = 0;
4726 final void startCopy() {
4727 try {
4728 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4729 retry++;
4730 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004731 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004732 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4733 handleServiceError();
4734 return;
4735 } else {
4736 handleStartCopy();
4737 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4738 mHandler.sendEmptyMessage(MCS_UNBIND);
4739 }
4740 } catch (RemoteException e) {
4741 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4742 mHandler.sendEmptyMessage(MCS_RECONNECT);
4743 }
4744 handleReturnCode();
4745 }
4746
4747 final void serviceError() {
4748 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4749 handleServiceError();
4750 handleReturnCode();
4751 }
4752 abstract void handleStartCopy() throws RemoteException;
4753 abstract void handleServiceError();
4754 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004755 }
4756
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004757 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004758 final IPackageInstallObserver observer;
4759 int flags;
4760 final Uri packageURI;
4761 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004762 private InstallArgs mArgs;
4763 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004764 InstallParams(Uri packageURI,
4765 IPackageInstallObserver observer, int flags,
4766 String installerPackageName) {
4767 this.packageURI = packageURI;
4768 this.flags = flags;
4769 this.observer = observer;
4770 this.installerPackageName = installerPackageName;
4771 }
4772
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004773 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4774 String packageName = pkgLite.packageName;
4775 int installLocation = pkgLite.installLocation;
4776 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4777 synchronized (mPackages) {
4778 PackageParser.Package pkg = mPackages.get(packageName);
4779 if (pkg != null) {
4780 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4781 // Check for updated system application.
4782 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4783 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004784 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004785 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4786 }
4787 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4788 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004789 if (onSd) {
4790 // Install flag overrides everything.
4791 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4792 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004793 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004794 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4795 // Application explicitly specified internal.
4796 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4797 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4798 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004799 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004800 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004801 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4802 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4803 }
4804 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004805 }
4806 }
4807 } else {
4808 // Invalid install. Return error code
4809 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4810 }
4811 }
4812 }
4813 // All the special cases have been taken care of.
4814 // Return result based on recommended install location.
4815 if (onSd) {
4816 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4817 }
4818 return pkgLite.recommendedInstallLocation;
4819 }
4820
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004821 /*
4822 * Invoke remote method to get package information and install
4823 * location values. Override install location based on default
4824 * policy if needed and then create install arguments based
4825 * on the install location.
4826 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004827 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004828 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004829 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4830 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004831 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4832 if (onInt && onSd) {
4833 // Check if both bits are set.
4834 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4835 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4836 } else if (fwdLocked && onSd) {
4837 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004838 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004839 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004840 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004841 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004842 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004843 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004844 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4845 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4846 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4847 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4848 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004849 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4850 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4851 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004852 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4853 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004854 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004855 // Override with defaults if needed.
4856 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004857 if (!onSd && !onInt) {
4858 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004859 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4860 // Set the flag to install on external media.
4861 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004862 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004863 } else {
4864 // Make sure the flag for installing on external
4865 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004866 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004867 flags &= ~PackageManager.INSTALL_EXTERNAL;
4868 }
4869 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004870 }
4871 }
4872 // Create the file args now.
4873 mArgs = createInstallArgs(this);
4874 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4875 // Create copy only if we are not in an erroneous state.
4876 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004877 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004878 }
4879 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004880 }
4881
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004882 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004883 void handleReturnCode() {
4884 processPendingInstall(mArgs, mRet);
4885 }
4886
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004887 @Override
4888 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004889 mArgs = createInstallArgs(this);
4890 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004891 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004892 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004893
4894 /*
4895 * Utility class used in movePackage api.
4896 * srcArgs and targetArgs are not set for invalid flags and make
4897 * sure to do null checks when invoking methods on them.
4898 * We probably want to return ErrorPrams for both failed installs
4899 * and moves.
4900 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004901 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004902 final IPackageMoveObserver observer;
4903 final int flags;
4904 final String packageName;
4905 final InstallArgs srcArgs;
4906 final InstallArgs targetArgs;
4907 int mRet;
4908 MoveParams(InstallArgs srcArgs,
4909 IPackageMoveObserver observer,
4910 int flags, String packageName) {
4911 this.srcArgs = srcArgs;
4912 this.observer = observer;
4913 this.flags = flags;
4914 this.packageName = packageName;
4915 if (srcArgs != null) {
4916 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4917 targetArgs = createInstallArgs(packageUri, flags, packageName);
4918 } else {
4919 targetArgs = null;
4920 }
4921 }
4922
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004923 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004924 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4925 // Check for storage space on target medium
4926 if (!targetArgs.checkFreeStorage(mContainerService)) {
4927 Log.w(TAG, "Insufficient storage to install");
4928 return;
4929 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004930 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004931 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004932 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004933 if (DEBUG_SD_INSTALL) {
4934 StringBuilder builder = new StringBuilder();
4935 if (srcArgs != null) {
4936 builder.append("src: ");
4937 builder.append(srcArgs.getCodePath());
4938 }
4939 if (targetArgs != null) {
4940 builder.append(" target : ");
4941 builder.append(targetArgs.getCodePath());
4942 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004943 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004944 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004945 }
4946
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004947 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004948 void handleReturnCode() {
4949 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004950 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4951 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4952 currentStatus = PackageManager.MOVE_SUCCEEDED;
4953 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4954 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4955 }
4956 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004957 }
4958
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004959 @Override
4960 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004962 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004963 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004964
4965 private InstallArgs createInstallArgs(InstallParams params) {
4966 if (installOnSd(params.flags)) {
4967 return new SdInstallArgs(params);
4968 } else {
4969 return new FileInstallArgs(params);
4970 }
4971 }
4972
4973 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4974 if (installOnSd(flags)) {
4975 return new SdInstallArgs(fullCodePath, fullResourcePath);
4976 } else {
4977 return new FileInstallArgs(fullCodePath, fullResourcePath);
4978 }
4979 }
4980
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004981 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4982 if (installOnSd(flags)) {
4983 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4984 return new SdInstallArgs(packageURI, cid);
4985 } else {
4986 return new FileInstallArgs(packageURI, pkgName);
4987 }
4988 }
4989
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004990 static abstract class InstallArgs {
4991 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004992 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004993 final int flags;
4994 final Uri packageURI;
4995 final String installerPackageName;
4996
4997 InstallArgs(Uri packageURI,
4998 IPackageInstallObserver observer, int flags,
4999 String installerPackageName) {
5000 this.packageURI = packageURI;
5001 this.flags = flags;
5002 this.observer = observer;
5003 this.installerPackageName = installerPackageName;
5004 }
5005
5006 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005007 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005008 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005009 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005010 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005011 abstract String getCodePath();
5012 abstract String getResourcePath();
5013 // Need installer lock especially for dex file removal.
5014 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005015 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005016 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005017 }
5018
5019 class FileInstallArgs extends InstallArgs {
5020 File installDir;
5021 String codeFileName;
5022 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005023 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005024
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005025 FileInstallArgs(InstallParams params) {
5026 super(params.packageURI, params.observer,
5027 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005028 }
5029
5030 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5031 super(null, null, 0, null);
5032 File codeFile = new File(fullCodePath);
5033 installDir = codeFile.getParentFile();
5034 codeFileName = fullCodePath;
5035 resourceFileName = fullResourcePath;
5036 }
5037
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005038 FileInstallArgs(Uri packageURI, String pkgName) {
5039 super(packageURI, null, 0, null);
5040 boolean fwdLocked = isFwdLocked(flags);
5041 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5042 String apkName = getNextCodePath(null, pkgName, ".apk");
5043 codeFileName = new File(installDir, apkName + ".apk").getPath();
5044 resourceFileName = getResourcePathFromCodePath();
5045 }
5046
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005047 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5048 return imcs.checkFreeStorage(false, packageURI);
5049 }
5050
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005051 String getCodePath() {
5052 return codeFileName;
5053 }
5054
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005055 void createCopyFile() {
5056 boolean fwdLocked = isFwdLocked(flags);
5057 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5058 codeFileName = createTempPackageFile(installDir).getPath();
5059 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005060 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005061 }
5062
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005063 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005064 if (temp) {
5065 // Generate temp file name
5066 createCopyFile();
5067 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005068 // Get a ParcelFileDescriptor to write to the output file
5069 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005070 if (!created) {
5071 try {
5072 codeFile.createNewFile();
5073 // Set permissions
5074 if (!setPermissions()) {
5075 // Failed setting permissions.
5076 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5077 }
5078 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005079 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005080 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5081 }
5082 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005083 ParcelFileDescriptor out = null;
5084 try {
5085 out = ParcelFileDescriptor.open(codeFile,
5086 ParcelFileDescriptor.MODE_READ_WRITE);
5087 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005088 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005089 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5090 }
5091 // Copy the resource now
5092 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5093 try {
5094 if (imcs.copyResource(packageURI, out)) {
5095 ret = PackageManager.INSTALL_SUCCEEDED;
5096 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005097 } finally {
5098 try { if (out != null) out.close(); } catch (IOException e) {}
5099 }
5100 return ret;
5101 }
5102
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005103 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005104 if (status != PackageManager.INSTALL_SUCCEEDED) {
5105 cleanUp();
5106 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005107 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005108 }
5109
5110 boolean doRename(int status, final String pkgName, String oldCodePath) {
5111 if (status != PackageManager.INSTALL_SUCCEEDED) {
5112 cleanUp();
5113 return false;
5114 } else {
5115 // Rename based on packageName
5116 File codeFile = new File(getCodePath());
5117 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5118 File desFile = new File(installDir, apkName + ".apk");
5119 if (!codeFile.renameTo(desFile)) {
5120 return false;
5121 }
5122 // Reset paths since the file has been renamed.
5123 codeFileName = desFile.getPath();
5124 resourceFileName = getResourcePathFromCodePath();
5125 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005126 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005127 // Failed setting permissions.
5128 return false;
5129 }
5130 return true;
5131 }
5132 }
5133
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005134 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005135 if (status != PackageManager.INSTALL_SUCCEEDED) {
5136 cleanUp();
5137 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005138 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005139 }
5140
5141 String getResourcePath() {
5142 return resourceFileName;
5143 }
5144
5145 String getResourcePathFromCodePath() {
5146 String codePath = getCodePath();
5147 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5148 String apkNameOnly = getApkName(codePath);
5149 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5150 } else {
5151 return codePath;
5152 }
5153 }
5154
5155 private boolean cleanUp() {
5156 boolean ret = true;
5157 String sourceDir = getCodePath();
5158 String publicSourceDir = getResourcePath();
5159 if (sourceDir != null) {
5160 File sourceFile = new File(sourceDir);
5161 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005162 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005163 ret = false;
5164 }
5165 // Delete application's code and resources
5166 sourceFile.delete();
5167 }
5168 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5169 final File publicSourceFile = new File(publicSourceDir);
5170 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005171 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005172 }
5173 if (publicSourceFile.exists()) {
5174 publicSourceFile.delete();
5175 }
5176 }
5177 return ret;
5178 }
5179
5180 void cleanUpResourcesLI() {
5181 String sourceDir = getCodePath();
5182 if (cleanUp() && mInstaller != null) {
5183 int retCode = mInstaller.rmdex(sourceDir);
5184 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005185 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005186 + " at location "
5187 + sourceDir + ", retcode=" + retCode);
5188 // we don't consider this to be a failure of the core package deletion
5189 }
5190 }
5191 }
5192
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005193 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005194 // TODO Do this in a more elegant way later on. for now just a hack
5195 if (!isFwdLocked(flags)) {
5196 final int filePermissions =
5197 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5198 |FileUtils.S_IROTH;
5199 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5200 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005201 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005202 getCodePath()
5203 + ". The return code was: " + retCode);
5204 // TODO Define new internal error
5205 return false;
5206 }
5207 return true;
5208 }
5209 return true;
5210 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005211
5212 boolean doPostDeleteLI(boolean delete) {
5213 cleanUpResourcesLI();
5214 return true;
5215 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005216 }
5217
5218 class SdInstallArgs extends InstallArgs {
5219 String cid;
5220 String cachePath;
5221 static final String RES_FILE_NAME = "pkg.apk";
5222
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005223 SdInstallArgs(InstallParams params) {
5224 super(params.packageURI, params.observer,
5225 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005226 }
5227
5228 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005229 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005230 // Extract cid from fullCodePath
5231 int eidx = fullCodePath.lastIndexOf("/");
5232 String subStr1 = fullCodePath.substring(0, eidx);
5233 int sidx = subStr1.lastIndexOf("/");
5234 cid = subStr1.substring(sidx+1, eidx);
5235 cachePath = subStr1;
5236 }
5237
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005238 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005239 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5240 this.cid = cid;
5241 }
5242
5243 SdInstallArgs(Uri packageURI, String cid) {
5244 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005245 this.cid = cid;
5246 }
5247
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005248 void createCopyFile() {
5249 cid = getTempContainerId();
5250 }
5251
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005252 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5253 return imcs.checkFreeStorage(true, packageURI);
5254 }
5255
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005256 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005257 if (temp) {
5258 createCopyFile();
5259 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005260 cachePath = imcs.copyResourceToContainer(
5261 packageURI, cid,
5262 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005263 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5264 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005265 }
5266
5267 @Override
5268 String getCodePath() {
5269 return cachePath + "/" + RES_FILE_NAME;
5270 }
5271
5272 @Override
5273 String getResourcePath() {
5274 return cachePath + "/" + RES_FILE_NAME;
5275 }
5276
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005277 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005278 if (status != PackageManager.INSTALL_SUCCEEDED) {
5279 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005280 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005281 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005282 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005283 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005284 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005285 if (cachePath == null) {
5286 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5287 }
5288 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005289 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005290 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005291 }
5292
5293 boolean doRename(int status, final String pkgName,
5294 String oldCodePath) {
5295 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005296 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005297 if (PackageHelper.isContainerMounted(cid)) {
5298 // Unmount the container
5299 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005300 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005301 return false;
5302 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005303 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005304 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005305 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5306 " which might be stale. Will try to clean up.");
5307 // Clean up the stale container and proceed to recreate.
5308 if (!PackageHelper.destroySdDir(newCacheId)) {
5309 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5310 return false;
5311 }
5312 // Successfully cleaned up stale container. Try to rename again.
5313 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5314 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5315 + " inspite of cleaning it up.");
5316 return false;
5317 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005318 }
5319 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005320 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005321 newCachePath = PackageHelper.mountSdDir(newCacheId,
5322 getEncryptKey(), Process.SYSTEM_UID);
5323 } else {
5324 newCachePath = PackageHelper.getSdDir(newCacheId);
5325 }
5326 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005327 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005328 return false;
5329 }
5330 Log.i(TAG, "Succesfully renamed " + cid +
5331 " at path: " + cachePath + " to " + newCacheId +
5332 " at new path: " + newCachePath);
5333 cid = newCacheId;
5334 cachePath = newCachePath;
5335 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005336 }
5337
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005338 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005339 if (status != PackageManager.INSTALL_SUCCEEDED) {
5340 cleanUp();
5341 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005342 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005343 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005344 PackageHelper.mountSdDir(cid,
5345 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005346 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005347 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005348 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005349 }
5350
5351 private void cleanUp() {
5352 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005353 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005354 }
5355
5356 void cleanUpResourcesLI() {
5357 String sourceFile = getCodePath();
5358 // Remove dex file
5359 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005360 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005361 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005362 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005363 + " at location "
5364 + sourceFile.toString() + ", retcode=" + retCode);
5365 // we don't consider this to be a failure of the core package deletion
5366 }
5367 }
5368 cleanUp();
5369 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005370
5371 boolean matchContainer(String app) {
5372 if (cid.startsWith(app)) {
5373 return true;
5374 }
5375 return false;
5376 }
5377
5378 String getPackageName() {
5379 int idx = cid.lastIndexOf("-");
5380 if (idx == -1) {
5381 return cid;
5382 }
5383 return cid.substring(0, idx);
5384 }
5385
5386 boolean doPostDeleteLI(boolean delete) {
5387 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005388 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005389 if (mounted) {
5390 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005391 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005392 }
5393 if (ret && delete) {
5394 cleanUpResourcesLI();
5395 }
5396 return ret;
5397 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005398 };
5399
5400 // Utility method used to create code paths based on package name and available index.
5401 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5402 String idxStr = "";
5403 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005404 // Fall back to default value of idx=1 if prefix is not
5405 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005406 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005407 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005408 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005409 if (subStr.endsWith(suffix)) {
5410 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005411 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005412 // If oldCodePath already contains prefix find out the
5413 // ending index to either increment or decrement.
5414 int sidx = subStr.lastIndexOf(prefix);
5415 if (sidx != -1) {
5416 subStr = subStr.substring(sidx + prefix.length());
5417 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005418 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5419 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005420 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005421 try {
5422 idx = Integer.parseInt(subStr);
5423 if (idx <= 1) {
5424 idx++;
5425 } else {
5426 idx--;
5427 }
5428 } catch(NumberFormatException e) {
5429 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005430 }
5431 }
5432 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005433 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005434 return prefix + idxStr;
5435 }
5436
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005437 // Utility method used to ignore ADD/REMOVE events
5438 // by directory observer.
5439 private static boolean ignoreCodePath(String fullPathStr) {
5440 String apkName = getApkName(fullPathStr);
5441 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5442 if (idx != -1 && ((idx+1) < apkName.length())) {
5443 // Make sure the package ends with a numeral
5444 String version = apkName.substring(idx+1);
5445 try {
5446 Integer.parseInt(version);
5447 return true;
5448 } catch (NumberFormatException e) {}
5449 }
5450 return false;
5451 }
5452
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005453 // Utility method that returns the relative package path with respect
5454 // to the installation directory. Like say for /data/data/com.test-1.apk
5455 // string com.test-1 is returned.
5456 static String getApkName(String codePath) {
5457 if (codePath == null) {
5458 return null;
5459 }
5460 int sidx = codePath.lastIndexOf("/");
5461 int eidx = codePath.lastIndexOf(".");
5462 if (eidx == -1) {
5463 eidx = codePath.length();
5464 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005465 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005466 return null;
5467 }
5468 return codePath.substring(sidx+1, eidx);
5469 }
5470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005471 class PackageInstalledInfo {
5472 String name;
5473 int uid;
5474 PackageParser.Package pkg;
5475 int returnCode;
5476 PackageRemovedInfo removedInfo;
5477 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 /*
5480 * Install a non-existing package.
5481 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005482 private void installNewPackageLI(PackageParser.Package pkg,
5483 int parseFlags,
5484 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005485 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005487 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005488
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005489 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490 res.name = pkgName;
5491 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005492 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5493 // A package with the same name is already installed, though
5494 // it has been renamed to an older name. The package we
5495 // are trying to install should be installed as an update to
5496 // the existing one, but that has not been requested, so bail.
5497 Slog.w(TAG, "Attempt to re-install " + pkgName
5498 + " without first uninstalling package running as "
5499 + mSettings.mRenamedPackages.get(pkgName));
5500 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5501 return;
5502 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005503 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005505 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506 + " without first uninstalling.");
5507 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5508 return;
5509 }
5510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005511 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005512 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005513 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005514 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5516 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5517 }
5518 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005519 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005520 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 res);
5522 // delete the partially installed application. the data directory will have to be
5523 // restored if it was already existing
5524 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5525 // remove package from internal structures. Note that we want deletePackageX to
5526 // delete the package data and cache directories that it created in
5527 // scanPackageLocked, unless those directories existed before we even tried to
5528 // install.
5529 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005530 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005531 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5532 res.removedInfo);
5533 }
5534 }
5535 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005536
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005537 private void replacePackageLI(PackageParser.Package pkg,
5538 int parseFlags,
5539 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005540 String installerPackageName, PackageInstalledInfo res) {
5541
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005542 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005543 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 // First find the old package info and check signatures
5545 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005546 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005547 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005548 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5550 return;
5551 }
5552 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005553 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005554 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005555 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005557 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 }
5559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005562 PackageParser.Package pkg,
5563 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005564 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 PackageParser.Package newPackage = null;
5566 String pkgName = deletedPackage.packageName;
5567 boolean deletedPkg = true;
5568 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005569
Jacek Surazski65e13172009-04-28 15:26:38 +02005570 String oldInstallerPackageName = null;
5571 synchronized (mPackages) {
5572 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005576 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 res.removedInfo)) {
5578 // If the existing package was'nt successfully deleted
5579 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5580 deletedPkg = false;
5581 } else {
5582 // Successfully deleted the old package. Now proceed with re-installation
5583 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005584 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005586 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005587 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5588 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005589 }
5590 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005591 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005592 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005593 res);
5594 updatedSettings = true;
5595 }
5596 }
5597
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005598 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 // remove package from internal structures. Note that we want deletePackageX to
5600 // delete the package data and cache directories that it created in
5601 // scanPackageLocked, unless those directories existed before we even tried to
5602 // install.
5603 if(updatedSettings) {
5604 deletePackageLI(
5605 pkgName, true,
5606 PackageManager.DONT_DELETE_DATA,
5607 res.removedInfo);
5608 }
5609 // Since we failed to install the new package we need to restore the old
5610 // package that we deleted.
5611 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005612 File restoreFile = new File(deletedPackage.mPath);
5613 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005614 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005615 return;
5616 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005617 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005618 boolean oldOnSd = isExternal(deletedPackage);
5619 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5620 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5621 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5622 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5623 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5624 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5625 return;
5626 }
5627 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005628 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005629 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5630 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005631 mSettings.writeLP();
5632 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005633 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 }
5635 }
5636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005639 PackageParser.Package pkg,
5640 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005641 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 PackageParser.Package newPackage = null;
5643 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005644 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005645 PackageParser.PARSE_IS_SYSTEM;
5646 String packageName = deletedPackage.packageName;
5647 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5648 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005649 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 return;
5651 }
5652 PackageParser.Package oldPkg;
5653 PackageSetting oldPkgSetting;
5654 synchronized (mPackages) {
5655 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005656 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5658 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005659 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 return;
5661 }
5662 }
5663 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5664 res.removedInfo.removedPackage = packageName;
5665 // Remove existing system package
5666 removePackageLI(oldPkg, true);
5667 synchronized (mPackages) {
5668 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5669 }
5670
5671 // Successfully disabled the old package. Now proceed with re-installation
5672 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5673 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005674 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005676 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5678 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5679 }
5680 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005681 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 updatedSettings = true;
5683 }
5684
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005685 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686 // Re installation failed. Restore old information
5687 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005688 if (newPackage != null) {
5689 removePackageLI(newPackage, true);
5690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005692 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005693 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005694 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 // Restore the old system information in Settings
5696 synchronized(mPackages) {
5697 if(updatedSettings) {
5698 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005699 mSettings.setInstallerPackageName(packageName,
5700 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 }
5702 mSettings.writeLP();
5703 }
5704 }
5705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005706
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005707 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005708 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005709 int retCode;
5710 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5711 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5712 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005713 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005714 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5715 }
5716 }
5717 return PackageManager.INSTALL_SUCCEEDED;
5718 }
5719
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005720 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005721 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005722 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 synchronized (mPackages) {
5724 //write settings. the installStatus will be incomplete at this stage.
5725 //note that the new package setting would have already been
5726 //added to mPackages. It hasn't been persisted yet.
5727 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5728 mSettings.writeLP();
5729 }
5730
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005731 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005732 != PackageManager.INSTALL_SUCCEEDED) {
5733 // Discontinue if moving dex files failed.
5734 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005735 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005736 if((res.returnCode = setPermissionsLI(newPackage))
5737 != PackageManager.INSTALL_SUCCEEDED) {
5738 if (mInstaller != null) {
5739 mInstaller.rmdex(newPackage.mScanPath);
5740 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005741 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005742 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005743 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005746 updatePermissionsLP(newPackage.packageName, newPackage,
5747 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 res.name = pkgName;
5749 res.uid = newPackage.applicationInfo.uid;
5750 res.pkg = newPackage;
5751 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005752 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005753 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5754 //to update install status
5755 mSettings.writeLP();
5756 }
5757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005758
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005759 private void installPackageLI(InstallArgs args,
5760 boolean newInstall, PackageInstalledInfo res) {
5761 int pFlags = args.flags;
5762 String installerPackageName = args.installerPackageName;
5763 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005764 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005765 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005766 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005767 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005768 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005769 // Result object to be returned
5770 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5771
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005772 // Retrieve PackageSettings and parse package
5773 int parseFlags = PackageParser.PARSE_CHATTY |
5774 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5775 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5776 parseFlags |= mDefParseFlags;
5777 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5778 pp.setSeparateProcesses(mSeparateProcesses);
5779 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5780 null, mMetrics, parseFlags);
5781 if (pkg == null) {
5782 res.returnCode = pp.getParseError();
5783 return;
5784 }
5785 String pkgName = res.name = pkg.packageName;
5786 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5787 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5788 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5789 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005791 }
5792 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5793 res.returnCode = pp.getParseError();
5794 return;
5795 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005796 // Get rid of all references to package scan path via parser.
5797 pp = null;
5798 String oldCodePath = null;
5799 boolean systemApp = false;
5800 synchronized (mPackages) {
5801 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005802 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5803 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005804 if (pkg.mOriginalPackages != null
5805 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005806 && mPackages.containsKey(oldName)) {
5807 // This package is derived from an original package,
5808 // and this device has been updating from that original
5809 // name. We must continue using the original name, so
5810 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005811 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005812 pkgName = pkg.packageName;
5813 replace = true;
5814 } else if (mPackages.containsKey(pkgName)) {
5815 // This package, under its official name, already exists
5816 // on the device; we should replace it.
5817 replace = true;
5818 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005819 }
5820 PackageSetting ps = mSettings.mPackages.get(pkgName);
5821 if (ps != null) {
5822 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5823 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5824 systemApp = (ps.pkg.applicationInfo.flags &
5825 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005826 }
5827 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005829
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005830 if (systemApp && onSd) {
5831 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005832 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005833 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5834 return;
5835 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005836
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005837 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5838 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5839 return;
5840 }
5841 // Set application objects path explicitly after the rename
5842 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005843 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005844 replacePackageLI(pkg, parseFlags, scanMode,
5845 installerPackageName, res);
5846 } else {
5847 installNewPackageLI(pkg, parseFlags, scanMode,
5848 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 }
5850 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005851
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005852 private int setPermissionsLI(PackageParser.Package newPackage) {
5853 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005854 int retCode = 0;
5855 // TODO Gross hack but fix later. Ideally move this to be a post installation
5856 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005857 if ((newPackage.applicationInfo.flags
5858 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5859 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 try {
5861 extractPublicFiles(newPackage, destResourceFile);
5862 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005863 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 -08005864 " forward-locked app.");
5865 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5866 } finally {
5867 //TODO clean up the extracted public files
5868 }
5869 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005870 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 newPackage.applicationInfo.uid);
5872 } else {
5873 final int filePermissions =
5874 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005875 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005876 newPackage.applicationInfo.uid);
5877 }
5878 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005879 // The permissions on the resource file was set when it was copied for
5880 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005884 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005885 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005886 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005887 // TODO Define new internal error
5888 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 }
5890 return PackageManager.INSTALL_SUCCEEDED;
5891 }
5892
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005893 private boolean isForwardLocked(PackageParser.Package pkg) {
5894 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 }
5896
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005897 private boolean isExternal(PackageParser.Package pkg) {
5898 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
5899 }
5900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005901 private void extractPublicFiles(PackageParser.Package newPackage,
5902 File publicZipFile) throws IOException {
5903 final ZipOutputStream publicZipOutStream =
5904 new ZipOutputStream(new FileOutputStream(publicZipFile));
5905 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5906
5907 // Copy manifest, resources.arsc and res directory to public zip
5908
5909 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5910 while (privateZipEntries.hasMoreElements()) {
5911 final ZipEntry zipEntry = privateZipEntries.nextElement();
5912 final String zipEntryName = zipEntry.getName();
5913 if ("AndroidManifest.xml".equals(zipEntryName)
5914 || "resources.arsc".equals(zipEntryName)
5915 || zipEntryName.startsWith("res/")) {
5916 try {
5917 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5918 } catch (IOException e) {
5919 try {
5920 publicZipOutStream.close();
5921 throw e;
5922 } finally {
5923 publicZipFile.delete();
5924 }
5925 }
5926 }
5927 }
5928
5929 publicZipOutStream.close();
5930 FileUtils.setPermissions(
5931 publicZipFile.getAbsolutePath(),
5932 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5933 -1, -1);
5934 }
5935
5936 private static void copyZipEntry(ZipEntry zipEntry,
5937 ZipFile inZipFile,
5938 ZipOutputStream outZipStream) throws IOException {
5939 byte[] buffer = new byte[4096];
5940 int num;
5941
5942 ZipEntry newEntry;
5943 if (zipEntry.getMethod() == ZipEntry.STORED) {
5944 // Preserve the STORED method of the input entry.
5945 newEntry = new ZipEntry(zipEntry);
5946 } else {
5947 // Create a new entry so that the compressed len is recomputed.
5948 newEntry = new ZipEntry(zipEntry.getName());
5949 }
5950 outZipStream.putNextEntry(newEntry);
5951
5952 InputStream data = inZipFile.getInputStream(zipEntry);
5953 while ((num = data.read(buffer)) > 0) {
5954 outZipStream.write(buffer, 0, num);
5955 }
5956 outZipStream.flush();
5957 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 private void deleteTempPackageFiles() {
5960 FilenameFilter filter = new FilenameFilter() {
5961 public boolean accept(File dir, String name) {
5962 return name.startsWith("vmdl") && name.endsWith(".tmp");
5963 }
5964 };
5965 String tmpFilesList[] = mAppInstallDir.list(filter);
5966 if(tmpFilesList == null) {
5967 return;
5968 }
5969 for(int i = 0; i < tmpFilesList.length; i++) {
5970 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5971 tmpFile.delete();
5972 }
5973 }
5974
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005975 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 File tmpPackageFile;
5977 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005978 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005979 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005980 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 return null;
5982 }
5983 try {
5984 FileUtils.setPermissions(
5985 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5986 -1, -1);
5987 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005988 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005989 return null;
5990 }
5991 return tmpPackageFile;
5992 }
5993
5994 public void deletePackage(final String packageName,
5995 final IPackageDeleteObserver observer,
5996 final int flags) {
5997 mContext.enforceCallingOrSelfPermission(
5998 android.Manifest.permission.DELETE_PACKAGES, null);
5999 // Queue up an async operation since the package deletion may take a little while.
6000 mHandler.post(new Runnable() {
6001 public void run() {
6002 mHandler.removeCallbacks(this);
6003 final boolean succeded = deletePackageX(packageName, true, true, flags);
6004 if (observer != null) {
6005 try {
6006 observer.packageDeleted(succeded);
6007 } catch (RemoteException e) {
6008 Log.i(TAG, "Observer no longer exists.");
6009 } //end catch
6010 } //end if
6011 } //end run
6012 });
6013 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 /**
6016 * This method is an internal method that could be get invoked either
6017 * to delete an installed package or to clean up a failed installation.
6018 * After deleting an installed package, a broadcast is sent to notify any
6019 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006020 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 * installation wouldn't have sent the initial broadcast either
6022 * The key steps in deleting a package are
6023 * deleting the package information in internal structures like mPackages,
6024 * deleting the packages base directories through installd
6025 * updating mSettings to reflect current status
6026 * persisting settings for later use
6027 * sending a broadcast if necessary
6028 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6030 boolean deleteCodeAndResources, int flags) {
6031 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006032 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006034 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6035 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6036 try {
6037 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006038 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006039 return false;
6040 }
6041 } catch (RemoteException e) {
6042 }
6043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 synchronized (mInstallLock) {
6045 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
6046 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006049 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
6050 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
6051
6052 // If the removed package was a system update, the old system packaged
6053 // was re-enabled; we need to broadcast this information
6054 if (systemUpdate) {
6055 Bundle extras = new Bundle(1);
6056 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6057 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6058
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006059 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6060 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006062 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08006063 // Force a gc here.
6064 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006065 // Delete the resources here after sending the broadcast to let
6066 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006067 if (info.args != null) {
6068 synchronized (mInstallLock) {
6069 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006070 }
6071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006072 return res;
6073 }
6074
6075 static class PackageRemovedInfo {
6076 String removedPackage;
6077 int uid = -1;
6078 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006079 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006080 // Clean up resources deleted packages.
6081 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 void sendBroadcast(boolean fullRemove, boolean replacing) {
6084 Bundle extras = new Bundle(1);
6085 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6086 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6087 if (replacing) {
6088 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6089 }
6090 if (removedPackage != null) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006091 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006092 }
6093 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006094 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 }
6096 }
6097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 /*
6100 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6101 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006102 * 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 -08006103 * delete a partially installed application.
6104 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006105 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 int flags) {
6107 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006108 if (outInfo != null) {
6109 outInfo.removedPackage = packageName;
6110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 removePackageLI(p, true);
6112 // Retrieve object to delete permissions for shared user later on
6113 PackageSetting deletedPs;
6114 synchronized (mPackages) {
6115 deletedPs = mSettings.mPackages.get(packageName);
6116 }
6117 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6118 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006119 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006121 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 + packageName + ", retcode=" + retCode);
6123 // we don't consider this to be a failure of the core package deletion
6124 }
6125 } else {
6126 //for emulator
6127 PackageParser.Package pkg = mPackages.get(packageName);
6128 File dataDir = new File(pkg.applicationInfo.dataDir);
6129 dataDir.delete();
6130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 }
6132 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006133 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006134 schedulePackageCleaning(packageName);
6135
6136 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6137 if (outInfo != null) {
6138 outInfo.removedUid = mSettings.removePackageLP(packageName);
6139 }
6140 if (deletedPs != null) {
6141 updatePermissionsLP(deletedPs.name, null, false, false);
6142 if (deletedPs.sharedUser != null) {
6143 // remove permissions associated with package
6144 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6145 }
6146 }
6147 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006148 // remove from preferred activities.
6149 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6150 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6151 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6152 removed.add(pa);
6153 }
6154 }
6155 for (PreferredActivity pa : removed) {
6156 mSettings.mPreferredActivities.removeFilter(pa);
6157 }
6158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006159 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006160 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 }
6162 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 /*
6165 * Tries to delete system package.
6166 */
6167 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006168 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 ApplicationInfo applicationInfo = p.applicationInfo;
6170 //applicable for non-partially installed applications only
6171 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006172 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 return false;
6174 }
6175 PackageSetting ps = null;
6176 // Confirm if the system package has been updated
6177 // An updated system app can be deleted. This will also have to restore
6178 // the system pkg from system partition
6179 synchronized (mPackages) {
6180 ps = mSettings.getDisabledSystemPkg(p.packageName);
6181 }
6182 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006183 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 return false;
6185 } else {
6186 Log.i(TAG, "Deleting system pkg from data partition");
6187 }
6188 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006189 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006190 boolean deleteCodeAndResources = false;
6191 if (ps.versionCode < p.mVersionCode) {
6192 // Delete code and resources for downgrades
6193 deleteCodeAndResources = true;
6194 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6195 flags &= ~PackageManager.DONT_DELETE_DATA;
6196 }
6197 } else {
6198 // Preserve data by setting flag
6199 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6200 flags |= PackageManager.DONT_DELETE_DATA;
6201 }
6202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6204 if (!ret) {
6205 return false;
6206 }
6207 synchronized (mPackages) {
6208 // Reinstate the old system package
6209 mSettings.enableSystemPackageLP(p.packageName);
6210 }
6211 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006212 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006214 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006217 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 return false;
6219 }
6220 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006221 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 mSettings.writeLP();
6223 }
6224 return true;
6225 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6228 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6229 ApplicationInfo applicationInfo = p.applicationInfo;
6230 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006231 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 return false;
6233 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006234 if (outInfo != null) {
6235 outInfo.uid = applicationInfo.uid;
6236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237
6238 // Delete package data from internal structures and also remove data if flag is set
6239 removePackageDataLI(p, outInfo, flags);
6240
6241 // Delete application code and resources
6242 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006243 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006244 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006245 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006246 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6247 PackageManager.INSTALL_FORWARD_LOCK : 0;
6248 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006249 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 }
6251 return true;
6252 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 /*
6255 * This method handles package deletion in general
6256 */
6257 private boolean deletePackageLI(String packageName,
6258 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6259 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006260 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 return false;
6262 }
6263 PackageParser.Package p;
6264 boolean dataOnly = false;
6265 synchronized (mPackages) {
6266 p = mPackages.get(packageName);
6267 if (p == null) {
6268 //this retrieves partially installed apps
6269 dataOnly = true;
6270 PackageSetting ps = mSettings.mPackages.get(packageName);
6271 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006272 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 return false;
6274 }
6275 p = ps.pkg;
6276 }
6277 }
6278 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006279 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 return false;
6281 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 if (dataOnly) {
6284 // Delete application data first
6285 removePackageDataLI(p, outInfo, flags);
6286 return true;
6287 }
6288 // At this point the package should have ApplicationInfo associated with it
6289 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006290 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 return false;
6292 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006293 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6295 Log.i(TAG, "Removing system package:"+p.packageName);
6296 // When an updated system application is deleted we delete the existing resources as well and
6297 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006298 ret = deleteSystemPackageLI(p, flags, outInfo);
6299 } else {
6300 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006301 // Kill application pre-emptively especially for apps on sd.
6302 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006303 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006305 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 public void clearApplicationUserData(final String packageName,
6309 final IPackageDataObserver observer) {
6310 mContext.enforceCallingOrSelfPermission(
6311 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6312 // Queue up an async operation since the package deletion may take a little while.
6313 mHandler.post(new Runnable() {
6314 public void run() {
6315 mHandler.removeCallbacks(this);
6316 final boolean succeeded;
6317 synchronized (mInstallLock) {
6318 succeeded = clearApplicationUserDataLI(packageName);
6319 }
6320 if (succeeded) {
6321 // invoke DeviceStorageMonitor's update method to clear any notifications
6322 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6323 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6324 if (dsm != null) {
6325 dsm.updateMemory();
6326 }
6327 }
6328 if(observer != null) {
6329 try {
6330 observer.onRemoveCompleted(packageName, succeeded);
6331 } catch (RemoteException e) {
6332 Log.i(TAG, "Observer no longer exists.");
6333 }
6334 } //end if observer
6335 } //end run
6336 });
6337 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 private boolean clearApplicationUserDataLI(String packageName) {
6340 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006341 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 return false;
6343 }
6344 PackageParser.Package p;
6345 boolean dataOnly = false;
6346 synchronized (mPackages) {
6347 p = mPackages.get(packageName);
6348 if(p == null) {
6349 dataOnly = true;
6350 PackageSetting ps = mSettings.mPackages.get(packageName);
6351 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006352 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 return false;
6354 }
6355 p = ps.pkg;
6356 }
6357 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 if(!dataOnly) {
6360 //need to check this only for fully installed applications
6361 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006362 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 return false;
6364 }
6365 final ApplicationInfo applicationInfo = p.applicationInfo;
6366 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006367 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 return false;
6369 }
6370 }
6371 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006372 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006374 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 + packageName);
6376 return false;
6377 }
6378 }
6379 return true;
6380 }
6381
6382 public void deleteApplicationCacheFiles(final String packageName,
6383 final IPackageDataObserver observer) {
6384 mContext.enforceCallingOrSelfPermission(
6385 android.Manifest.permission.DELETE_CACHE_FILES, null);
6386 // Queue up an async operation since the package deletion may take a little while.
6387 mHandler.post(new Runnable() {
6388 public void run() {
6389 mHandler.removeCallbacks(this);
6390 final boolean succeded;
6391 synchronized (mInstallLock) {
6392 succeded = deleteApplicationCacheFilesLI(packageName);
6393 }
6394 if(observer != null) {
6395 try {
6396 observer.onRemoveCompleted(packageName, succeded);
6397 } catch (RemoteException e) {
6398 Log.i(TAG, "Observer no longer exists.");
6399 }
6400 } //end if observer
6401 } //end run
6402 });
6403 }
6404
6405 private boolean deleteApplicationCacheFilesLI(String packageName) {
6406 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006407 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 return false;
6409 }
6410 PackageParser.Package p;
6411 synchronized (mPackages) {
6412 p = mPackages.get(packageName);
6413 }
6414 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006415 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 return false;
6417 }
6418 final ApplicationInfo applicationInfo = p.applicationInfo;
6419 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006420 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 return false;
6422 }
6423 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006424 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006426 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006427 + packageName);
6428 return false;
6429 }
6430 }
6431 return true;
6432 }
6433
6434 public void getPackageSizeInfo(final String packageName,
6435 final IPackageStatsObserver observer) {
6436 mContext.enforceCallingOrSelfPermission(
6437 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6438 // Queue up an async operation since the package deletion may take a little while.
6439 mHandler.post(new Runnable() {
6440 public void run() {
6441 mHandler.removeCallbacks(this);
6442 PackageStats lStats = new PackageStats(packageName);
6443 final boolean succeded;
6444 synchronized (mInstallLock) {
6445 succeded = getPackageSizeInfoLI(packageName, lStats);
6446 }
6447 if(observer != null) {
6448 try {
6449 observer.onGetStatsCompleted(lStats, succeded);
6450 } catch (RemoteException e) {
6451 Log.i(TAG, "Observer no longer exists.");
6452 }
6453 } //end if observer
6454 } //end run
6455 });
6456 }
6457
6458 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6459 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006460 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 return false;
6462 }
6463 PackageParser.Package p;
6464 boolean dataOnly = false;
6465 synchronized (mPackages) {
6466 p = mPackages.get(packageName);
6467 if(p == null) {
6468 dataOnly = true;
6469 PackageSetting ps = mSettings.mPackages.get(packageName);
6470 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006471 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 return false;
6473 }
6474 p = ps.pkg;
6475 }
6476 }
6477 String publicSrcDir = null;
6478 if(!dataOnly) {
6479 final ApplicationInfo applicationInfo = p.applicationInfo;
6480 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006481 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 return false;
6483 }
6484 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6485 }
6486 if (mInstaller != null) {
6487 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006488 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 if (res < 0) {
6490 return false;
6491 } else {
6492 return true;
6493 }
6494 }
6495 return true;
6496 }
6497
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 public void addPackageToPreferred(String packageName) {
6500 mContext.enforceCallingOrSelfPermission(
6501 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006502 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006503 }
6504
6505 public void removePackageFromPreferred(String packageName) {
6506 mContext.enforceCallingOrSelfPermission(
6507 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006508 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006509 }
6510
6511 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006512 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 }
6514
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006515 int getUidTargetSdkVersionLockedLP(int uid) {
6516 Object obj = mSettings.getUserIdLP(uid);
6517 if (obj instanceof SharedUserSetting) {
6518 SharedUserSetting sus = (SharedUserSetting)obj;
6519 final int N = sus.packages.size();
6520 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6521 Iterator<PackageSetting> it = sus.packages.iterator();
6522 int i=0;
6523 while (it.hasNext()) {
6524 PackageSetting ps = it.next();
6525 if (ps.pkg != null) {
6526 int v = ps.pkg.applicationInfo.targetSdkVersion;
6527 if (v < vers) vers = v;
6528 }
6529 }
6530 return vers;
6531 } else if (obj instanceof PackageSetting) {
6532 PackageSetting ps = (PackageSetting)obj;
6533 if (ps.pkg != null) {
6534 return ps.pkg.applicationInfo.targetSdkVersion;
6535 }
6536 }
6537 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6538 }
6539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 public void addPreferredActivity(IntentFilter filter, int match,
6541 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006542 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006543 if (mContext.checkCallingOrSelfPermission(
6544 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6545 != PackageManager.PERMISSION_GRANTED) {
6546 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6547 < Build.VERSION_CODES.FROYO) {
6548 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6549 + Binder.getCallingUid());
6550 return;
6551 }
6552 mContext.enforceCallingOrSelfPermission(
6553 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6554 }
6555
6556 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6558 mSettings.mPreferredActivities.addFilter(
6559 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006560 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006561 }
6562 }
6563
Satish Sampath8dbe6122009-06-02 23:35:54 +01006564 public void replacePreferredActivity(IntentFilter filter, int match,
6565 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006566 if (filter.countActions() != 1) {
6567 throw new IllegalArgumentException(
6568 "replacePreferredActivity expects filter to have only 1 action.");
6569 }
6570 if (filter.countCategories() != 1) {
6571 throw new IllegalArgumentException(
6572 "replacePreferredActivity expects filter to have only 1 category.");
6573 }
6574 if (filter.countDataAuthorities() != 0
6575 || filter.countDataPaths() != 0
6576 || filter.countDataSchemes() != 0
6577 || filter.countDataTypes() != 0) {
6578 throw new IllegalArgumentException(
6579 "replacePreferredActivity expects filter to have no data authorities, " +
6580 "paths, schemes or types.");
6581 }
6582 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006583 if (mContext.checkCallingOrSelfPermission(
6584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6585 != PackageManager.PERMISSION_GRANTED) {
6586 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6587 < Build.VERSION_CODES.FROYO) {
6588 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6589 + Binder.getCallingUid());
6590 return;
6591 }
6592 mContext.enforceCallingOrSelfPermission(
6593 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6594 }
6595
Satish Sampath8dbe6122009-06-02 23:35:54 +01006596 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6597 String action = filter.getAction(0);
6598 String category = filter.getCategory(0);
6599 while (it.hasNext()) {
6600 PreferredActivity pa = it.next();
6601 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6602 it.remove();
6603 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6604 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6605 }
6606 }
6607 addPreferredActivity(filter, match, set, activity);
6608 }
6609 }
6610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006613 int uid = Binder.getCallingUid();
6614 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006615 if (pkg == null || pkg.applicationInfo.uid != uid) {
6616 if (mContext.checkCallingOrSelfPermission(
6617 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6618 != PackageManager.PERMISSION_GRANTED) {
6619 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6620 < Build.VERSION_CODES.FROYO) {
6621 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6622 + Binder.getCallingUid());
6623 return;
6624 }
6625 mContext.enforceCallingOrSelfPermission(
6626 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6627 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006628 }
6629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006631 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 }
6633 }
6634 }
6635
6636 boolean clearPackagePreferredActivitiesLP(String packageName) {
6637 boolean changed = false;
6638 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6639 while (it.hasNext()) {
6640 PreferredActivity pa = it.next();
6641 if (pa.mActivity.getPackageName().equals(packageName)) {
6642 it.remove();
6643 changed = true;
6644 }
6645 }
6646 return changed;
6647 }
6648
6649 public int getPreferredActivities(List<IntentFilter> outFilters,
6650 List<ComponentName> outActivities, String packageName) {
6651
6652 int num = 0;
6653 synchronized (mPackages) {
6654 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6655 while (it.hasNext()) {
6656 PreferredActivity pa = it.next();
6657 if (packageName == null
6658 || pa.mActivity.getPackageName().equals(packageName)) {
6659 if (outFilters != null) {
6660 outFilters.add(new IntentFilter(pa));
6661 }
6662 if (outActivities != null) {
6663 outActivities.add(pa.mActivity);
6664 }
6665 }
6666 }
6667 }
6668
6669 return num;
6670 }
6671
6672 public void setApplicationEnabledSetting(String appPackageName,
6673 int newState, int flags) {
6674 setEnabledSetting(appPackageName, null, newState, flags);
6675 }
6676
6677 public void setComponentEnabledSetting(ComponentName componentName,
6678 int newState, int flags) {
6679 setEnabledSetting(componentName.getPackageName(),
6680 componentName.getClassName(), newState, flags);
6681 }
6682
6683 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006684 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6686 || newState == COMPONENT_ENABLED_STATE_ENABLED
6687 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6688 throw new IllegalArgumentException("Invalid new component state: "
6689 + newState);
6690 }
6691 PackageSetting pkgSetting;
6692 final int uid = Binder.getCallingUid();
6693 final int permission = mContext.checkCallingPermission(
6694 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6695 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006696 boolean sendNow = false;
6697 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006698 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006700 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006702 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006704 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006706 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 }
6708 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006709 "Unknown component: " + packageName
6710 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 }
6712 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6713 throw new SecurityException(
6714 "Permission Denial: attempt to change component state from pid="
6715 + Binder.getCallingPid()
6716 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6717 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006718 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006720 if (pkgSetting.enabled == newState) {
6721 // Nothing to do
6722 return;
6723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 pkgSetting.enabled = newState;
6725 } else {
6726 // We're dealing with a component level state change
6727 switch (newState) {
6728 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006729 if (!pkgSetting.enableComponentLP(className)) {
6730 return;
6731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732 break;
6733 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006734 if (!pkgSetting.disableComponentLP(className)) {
6735 return;
6736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 break;
6738 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006739 if (!pkgSetting.restoreComponentLP(className)) {
6740 return;
6741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006742 break;
6743 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006744 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006745 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 }
6747 }
6748 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006749 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006750 components = mPendingBroadcasts.get(packageName);
6751 boolean newPackage = components == null;
6752 if (newPackage) {
6753 components = new ArrayList<String>();
6754 }
6755 if (!components.contains(componentName)) {
6756 components.add(componentName);
6757 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006758 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6759 sendNow = true;
6760 // Purge entry from pending broadcast list if another one exists already
6761 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006762 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006763 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006764 if (newPackage) {
6765 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006766 }
6767 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6768 // Schedule a message
6769 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6770 }
6771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 long callingId = Binder.clearCallingIdentity();
6775 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006776 if (sendNow) {
6777 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006778 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006780 } finally {
6781 Binder.restoreCallingIdentity(callingId);
6782 }
6783 }
6784
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006785 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006786 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6787 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6788 + " components=" + componentNames);
6789 Bundle extras = new Bundle(4);
6790 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6791 String nameList[] = new String[componentNames.size()];
6792 componentNames.toArray(nameList);
6793 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006794 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6795 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006796 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006797 }
6798
Jacek Surazski65e13172009-04-28 15:26:38 +02006799 public String getInstallerPackageName(String packageName) {
6800 synchronized (mPackages) {
6801 PackageSetting pkg = mSettings.mPackages.get(packageName);
6802 if (pkg == null) {
6803 throw new IllegalArgumentException("Unknown package: " + packageName);
6804 }
6805 return pkg.installerPackageName;
6806 }
6807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 public int getApplicationEnabledSetting(String appPackageName) {
6810 synchronized (mPackages) {
6811 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6812 if (pkg == null) {
6813 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6814 }
6815 return pkg.enabled;
6816 }
6817 }
6818
6819 public int getComponentEnabledSetting(ComponentName componentName) {
6820 synchronized (mPackages) {
6821 final String packageNameStr = componentName.getPackageName();
6822 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6823 if (pkg == null) {
6824 throw new IllegalArgumentException("Unknown component: " + componentName);
6825 }
6826 final String classNameStr = componentName.getClassName();
6827 return pkg.currentEnabledStateLP(classNameStr);
6828 }
6829 }
6830
6831 public void enterSafeMode() {
6832 if (!mSystemReady) {
6833 mSafeMode = true;
6834 }
6835 }
6836
6837 public void systemReady() {
6838 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006839
6840 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006841 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006842 mContext.getContentResolver(),
6843 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006844 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006845 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006846 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006848 }
6849
6850 public boolean isSafeMode() {
6851 return mSafeMode;
6852 }
6853
6854 public boolean hasSystemUidErrors() {
6855 return mHasSystemUidErrors;
6856 }
6857
6858 static String arrayToString(int[] array) {
6859 StringBuffer buf = new StringBuffer(128);
6860 buf.append('[');
6861 if (array != null) {
6862 for (int i=0; i<array.length; i++) {
6863 if (i > 0) buf.append(", ");
6864 buf.append(array[i]);
6865 }
6866 }
6867 buf.append(']');
6868 return buf.toString();
6869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006871 @Override
6872 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6873 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6874 != PackageManager.PERMISSION_GRANTED) {
6875 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6876 + Binder.getCallingPid()
6877 + ", uid=" + Binder.getCallingUid()
6878 + " without permission "
6879 + android.Manifest.permission.DUMP);
6880 return;
6881 }
6882
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006883 String packageName = null;
6884
6885 int opti = 0;
6886 while (opti < args.length) {
6887 String opt = args[opti];
6888 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6889 break;
6890 }
6891 opti++;
6892 if ("-a".equals(opt)) {
6893 // Right now we only know how to print all.
6894 } else if ("-h".equals(opt)) {
6895 pw.println("Package manager dump options:");
6896 pw.println(" [-h] [cmd] ...");
6897 pw.println(" cmd may be one of:");
6898 pw.println(" [package.name]: info about given package");
6899 return;
6900 } else {
6901 pw.println("Unknown argument: " + opt + "; use -h for help");
6902 }
6903 }
6904
6905 // Is the caller requesting to dump a particular piece of data?
6906 if (opti < args.length) {
6907 String cmd = args[opti];
6908 opti++;
6909 // Is this a package name?
6910 if ("android".equals(cmd) || cmd.contains(".")) {
6911 packageName = cmd;
6912 }
6913 }
6914
6915 boolean printedTitle = false;
6916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006917 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006918 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6919 printedTitle = true;
6920 }
6921 if (mReceivers.dump(pw, printedTitle
6922 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6923 " ", packageName)) {
6924 printedTitle = true;
6925 }
6926 if (mServices.dump(pw, printedTitle
6927 ? "\nService Resolver Table:" : "Service Resolver Table:",
6928 " ", packageName)) {
6929 printedTitle = true;
6930 }
6931 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6932 ? "\nPreferred Activities:" : "Preferred Activities:",
6933 " ", packageName)) {
6934 printedTitle = true;
6935 }
6936 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 {
6938 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006939 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6940 continue;
6941 }
6942 if (!printedSomething) {
6943 if (printedTitle) pw.println(" ");
6944 pw.println("Permissions:");
6945 printedSomething = true;
6946 printedTitle = true;
6947 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006948 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6949 pw.print(Integer.toHexString(System.identityHashCode(p)));
6950 pw.println("):");
6951 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6952 pw.print(" uid="); pw.print(p.uid);
6953 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006954 pw.print(" type="); pw.print(p.type);
6955 pw.print(" prot="); pw.println(p.protectionLevel);
6956 if (p.packageSetting != null) {
6957 pw.print(" packageSetting="); pw.println(p.packageSetting);
6958 }
6959 if (p.perm != null) {
6960 pw.print(" perm="); pw.println(p.perm);
6961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 }
6963 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006964 printedSomething = false;
6965 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006966 {
6967 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006968 if (packageName != null && !packageName.equals(ps.realName)
6969 && !packageName.equals(ps.name)) {
6970 continue;
6971 }
6972 if (!printedSomething) {
6973 if (printedTitle) pw.println(" ");
6974 pw.println("Packages:");
6975 printedSomething = true;
6976 printedTitle = true;
6977 }
6978 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006979 pw.print(" Package [");
6980 pw.print(ps.realName != null ? ps.realName : ps.name);
6981 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006982 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6983 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006984 if (ps.realName != null) {
6985 pw.print(" compat name="); pw.println(ps.name);
6986 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006987 pw.print(" userId="); pw.print(ps.userId);
6988 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6989 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6990 pw.print(" pkg="); pw.println(ps.pkg);
6991 pw.print(" codePath="); pw.println(ps.codePathString);
6992 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006993 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006994 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006995 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006996 pw.print(" supportsScreens=[");
6997 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006998 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006999 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007000 if (!first) pw.print(", ");
7001 first = false;
7002 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007003 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007004 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007005 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007006 if (!first) pw.print(", ");
7007 first = false;
7008 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007009 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007010 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007011 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007012 if (!first) pw.print(", ");
7013 first = false;
7014 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007016 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007017 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007018 if (!first) pw.print(", ");
7019 first = false;
7020 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007022 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007023 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7024 if (!first) pw.print(", ");
7025 first = false;
7026 pw.print("anyDensity");
7027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007029 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007030 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7031 pw.print(" signatures="); pw.println(ps.signatures);
7032 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007033 pw.print(" haveGids="); pw.println(ps.haveGids);
7034 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007035 pw.print(" installStatus="); pw.print(ps.installStatus);
7036 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 if (ps.disabledComponents.size() > 0) {
7038 pw.println(" disabledComponents:");
7039 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007040 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 }
7042 }
7043 if (ps.enabledComponents.size() > 0) {
7044 pw.println(" enabledComponents:");
7045 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007046 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007047 }
7048 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007049 if (ps.grantedPermissions.size() > 0) {
7050 pw.println(" grantedPermissions:");
7051 for (String s : ps.grantedPermissions) {
7052 pw.print(" "); pw.println(s);
7053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 }
7056 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007057 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007058 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007059 for (HashMap.Entry<String, String> e
7060 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007061 if (packageName != null && !packageName.equals(e.getKey())
7062 && !packageName.equals(e.getValue())) {
7063 continue;
7064 }
7065 if (!printedSomething) {
7066 if (printedTitle) pw.println(" ");
7067 pw.println("Renamed packages:");
7068 printedSomething = true;
7069 printedTitle = true;
7070 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007071 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7072 pw.println(e.getValue());
7073 }
7074 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007075 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007076 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007077 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007078 if (packageName != null && !packageName.equals(ps.realName)
7079 && !packageName.equals(ps.name)) {
7080 continue;
7081 }
7082 if (!printedSomething) {
7083 if (printedTitle) pw.println(" ");
7084 pw.println("Hidden system packages:");
7085 printedSomething = true;
7086 printedTitle = true;
7087 }
7088 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007089 pw.print(ps.realName != null ? ps.realName : ps.name);
7090 pw.print("] (");
7091 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7092 pw.println("):");
7093 if (ps.realName != null) {
7094 pw.print(" compat name="); pw.println(ps.name);
7095 }
7096 pw.print(" userId="); pw.println(ps.userId);
7097 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7098 pw.print(" codePath="); pw.println(ps.codePathString);
7099 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7100 }
7101 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007102 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 {
7104 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007105 if (packageName != null && su != packageSharedUser) {
7106 continue;
7107 }
7108 if (!printedSomething) {
7109 if (printedTitle) pw.println(" ");
7110 pw.println("Shared users:");
7111 printedSomething = true;
7112 printedTitle = true;
7113 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007114 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7115 pw.print(Integer.toHexString(System.identityHashCode(su)));
7116 pw.println("):");
7117 pw.print(" userId="); pw.print(su.userId);
7118 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 pw.println(" grantedPermissions:");
7120 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007121 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007123 }
7124 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007125
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007126 if (packageName == null) {
7127 if (printedTitle) pw.println(" ");
7128 printedTitle = true;
7129 pw.println("Settings parse messages:");
7130 pw.println(mSettings.mReadMessages.toString());
7131
7132 pw.println(" ");
7133 pw.println("Package warning messages:");
7134 File fname = getSettingsProblemFile();
7135 FileInputStream in;
7136 try {
7137 in = new FileInputStream(fname);
7138 int avail = in.available();
7139 byte[] data = new byte[avail];
7140 in.read(data);
7141 pw.println(new String(data));
7142 } catch (FileNotFoundException e) {
7143 } catch (IOException e) {
7144 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007146 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007147
7148 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007149 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007150 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007151 if (packageName != null && !packageName.equals(p.info.packageName)) {
7152 continue;
7153 }
7154 if (!printedSomething) {
7155 if (printedTitle) pw.println(" ");
7156 pw.println("Registered ContentProviders:");
7157 printedSomething = true;
7158 printedTitle = true;
7159 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007160 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007161 pw.println(p.toString());
7162 }
7163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007164 }
7165
7166 static final class BasePermission {
7167 final static int TYPE_NORMAL = 0;
7168 final static int TYPE_BUILTIN = 1;
7169 final static int TYPE_DYNAMIC = 2;
7170
7171 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007172 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007173 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007174 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007175 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 PackageParser.Permission perm;
7177 PermissionInfo pendingInfo;
7178 int uid;
7179 int[] gids;
7180
7181 BasePermission(String _name, String _sourcePackage, int _type) {
7182 name = _name;
7183 sourcePackage = _sourcePackage;
7184 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007185 // Default to most conservative protection level.
7186 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7187 }
7188
7189 public String toString() {
7190 return "BasePermission{"
7191 + Integer.toHexString(System.identityHashCode(this))
7192 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007193 }
7194 }
7195
7196 static class PackageSignatures {
7197 private Signature[] mSignatures;
7198
7199 PackageSignatures(Signature[] sigs) {
7200 assignSignatures(sigs);
7201 }
7202
7203 PackageSignatures() {
7204 }
7205
7206 void writeXml(XmlSerializer serializer, String tagName,
7207 ArrayList<Signature> pastSignatures) throws IOException {
7208 if (mSignatures == null) {
7209 return;
7210 }
7211 serializer.startTag(null, tagName);
7212 serializer.attribute(null, "count",
7213 Integer.toString(mSignatures.length));
7214 for (int i=0; i<mSignatures.length; i++) {
7215 serializer.startTag(null, "cert");
7216 final Signature sig = mSignatures[i];
7217 final int sigHash = sig.hashCode();
7218 final int numPast = pastSignatures.size();
7219 int j;
7220 for (j=0; j<numPast; j++) {
7221 Signature pastSig = pastSignatures.get(j);
7222 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7223 serializer.attribute(null, "index", Integer.toString(j));
7224 break;
7225 }
7226 }
7227 if (j >= numPast) {
7228 pastSignatures.add(sig);
7229 serializer.attribute(null, "index", Integer.toString(numPast));
7230 serializer.attribute(null, "key", sig.toCharsString());
7231 }
7232 serializer.endTag(null, "cert");
7233 }
7234 serializer.endTag(null, tagName);
7235 }
7236
7237 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7238 throws IOException, XmlPullParserException {
7239 String countStr = parser.getAttributeValue(null, "count");
7240 if (countStr == null) {
7241 reportSettingsProblem(Log.WARN,
7242 "Error in package manager settings: <signatures> has"
7243 + " no count at " + parser.getPositionDescription());
7244 XmlUtils.skipCurrentTag(parser);
7245 }
7246 final int count = Integer.parseInt(countStr);
7247 mSignatures = new Signature[count];
7248 int pos = 0;
7249
7250 int outerDepth = parser.getDepth();
7251 int type;
7252 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7253 && (type != XmlPullParser.END_TAG
7254 || parser.getDepth() > outerDepth)) {
7255 if (type == XmlPullParser.END_TAG
7256 || type == XmlPullParser.TEXT) {
7257 continue;
7258 }
7259
7260 String tagName = parser.getName();
7261 if (tagName.equals("cert")) {
7262 if (pos < count) {
7263 String index = parser.getAttributeValue(null, "index");
7264 if (index != null) {
7265 try {
7266 int idx = Integer.parseInt(index);
7267 String key = parser.getAttributeValue(null, "key");
7268 if (key == null) {
7269 if (idx >= 0 && idx < pastSignatures.size()) {
7270 Signature sig = pastSignatures.get(idx);
7271 if (sig != null) {
7272 mSignatures[pos] = pastSignatures.get(idx);
7273 pos++;
7274 } else {
7275 reportSettingsProblem(Log.WARN,
7276 "Error in package manager settings: <cert> "
7277 + "index " + index + " is not defined at "
7278 + parser.getPositionDescription());
7279 }
7280 } else {
7281 reportSettingsProblem(Log.WARN,
7282 "Error in package manager settings: <cert> "
7283 + "index " + index + " is out of bounds at "
7284 + parser.getPositionDescription());
7285 }
7286 } else {
7287 while (pastSignatures.size() <= idx) {
7288 pastSignatures.add(null);
7289 }
7290 Signature sig = new Signature(key);
7291 pastSignatures.set(idx, sig);
7292 mSignatures[pos] = sig;
7293 pos++;
7294 }
7295 } catch (NumberFormatException e) {
7296 reportSettingsProblem(Log.WARN,
7297 "Error in package manager settings: <cert> "
7298 + "index " + index + " is not a number at "
7299 + parser.getPositionDescription());
7300 }
7301 } else {
7302 reportSettingsProblem(Log.WARN,
7303 "Error in package manager settings: <cert> has"
7304 + " no index at " + parser.getPositionDescription());
7305 }
7306 } else {
7307 reportSettingsProblem(Log.WARN,
7308 "Error in package manager settings: too "
7309 + "many <cert> tags, expected " + count
7310 + " at " + parser.getPositionDescription());
7311 }
7312 } else {
7313 reportSettingsProblem(Log.WARN,
7314 "Unknown element under <cert>: "
7315 + parser.getName());
7316 }
7317 XmlUtils.skipCurrentTag(parser);
7318 }
7319
7320 if (pos < count) {
7321 // Should never happen -- there is an error in the written
7322 // settings -- but if it does we don't want to generate
7323 // a bad array.
7324 Signature[] newSigs = new Signature[pos];
7325 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7326 mSignatures = newSigs;
7327 }
7328 }
7329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 private void assignSignatures(Signature[] sigs) {
7331 if (sigs == null) {
7332 mSignatures = null;
7333 return;
7334 }
7335 mSignatures = new Signature[sigs.length];
7336 for (int i=0; i<sigs.length; i++) {
7337 mSignatures[i] = sigs[i];
7338 }
7339 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007341 @Override
7342 public String toString() {
7343 StringBuffer buf = new StringBuffer(128);
7344 buf.append("PackageSignatures{");
7345 buf.append(Integer.toHexString(System.identityHashCode(this)));
7346 buf.append(" [");
7347 if (mSignatures != null) {
7348 for (int i=0; i<mSignatures.length; i++) {
7349 if (i > 0) buf.append(", ");
7350 buf.append(Integer.toHexString(
7351 System.identityHashCode(mSignatures[i])));
7352 }
7353 }
7354 buf.append("]}");
7355 return buf.toString();
7356 }
7357 }
7358
7359 static class PreferredActivity extends IntentFilter {
7360 final int mMatch;
7361 final String[] mSetPackages;
7362 final String[] mSetClasses;
7363 final String[] mSetComponents;
7364 final ComponentName mActivity;
7365 final String mShortActivity;
7366 String mParseError;
7367
7368 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7369 ComponentName activity) {
7370 super(filter);
7371 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7372 mActivity = activity;
7373 mShortActivity = activity.flattenToShortString();
7374 mParseError = null;
7375 if (set != null) {
7376 final int N = set.length;
7377 String[] myPackages = new String[N];
7378 String[] myClasses = new String[N];
7379 String[] myComponents = new String[N];
7380 for (int i=0; i<N; i++) {
7381 ComponentName cn = set[i];
7382 if (cn == null) {
7383 mSetPackages = null;
7384 mSetClasses = null;
7385 mSetComponents = null;
7386 return;
7387 }
7388 myPackages[i] = cn.getPackageName().intern();
7389 myClasses[i] = cn.getClassName().intern();
7390 myComponents[i] = cn.flattenToShortString().intern();
7391 }
7392 mSetPackages = myPackages;
7393 mSetClasses = myClasses;
7394 mSetComponents = myComponents;
7395 } else {
7396 mSetPackages = null;
7397 mSetClasses = null;
7398 mSetComponents = null;
7399 }
7400 }
7401
7402 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7403 IOException {
7404 mShortActivity = parser.getAttributeValue(null, "name");
7405 mActivity = ComponentName.unflattenFromString(mShortActivity);
7406 if (mActivity == null) {
7407 mParseError = "Bad activity name " + mShortActivity;
7408 }
7409 String matchStr = parser.getAttributeValue(null, "match");
7410 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7411 String setCountStr = parser.getAttributeValue(null, "set");
7412 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7413
7414 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7415 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7416 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7417
7418 int setPos = 0;
7419
7420 int outerDepth = parser.getDepth();
7421 int type;
7422 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7423 && (type != XmlPullParser.END_TAG
7424 || parser.getDepth() > outerDepth)) {
7425 if (type == XmlPullParser.END_TAG
7426 || type == XmlPullParser.TEXT) {
7427 continue;
7428 }
7429
7430 String tagName = parser.getName();
7431 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7432 // + parser.getDepth() + " tag=" + tagName);
7433 if (tagName.equals("set")) {
7434 String name = parser.getAttributeValue(null, "name");
7435 if (name == null) {
7436 if (mParseError == null) {
7437 mParseError = "No name in set tag in preferred activity "
7438 + mShortActivity;
7439 }
7440 } else if (setPos >= setCount) {
7441 if (mParseError == null) {
7442 mParseError = "Too many set tags in preferred activity "
7443 + mShortActivity;
7444 }
7445 } else {
7446 ComponentName cn = ComponentName.unflattenFromString(name);
7447 if (cn == null) {
7448 if (mParseError == null) {
7449 mParseError = "Bad set name " + name + " in preferred activity "
7450 + mShortActivity;
7451 }
7452 } else {
7453 myPackages[setPos] = cn.getPackageName();
7454 myClasses[setPos] = cn.getClassName();
7455 myComponents[setPos] = name;
7456 setPos++;
7457 }
7458 }
7459 XmlUtils.skipCurrentTag(parser);
7460 } else if (tagName.equals("filter")) {
7461 //Log.i(TAG, "Starting to parse filter...");
7462 readFromXml(parser);
7463 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7464 // + parser.getDepth() + " tag=" + parser.getName());
7465 } else {
7466 reportSettingsProblem(Log.WARN,
7467 "Unknown element under <preferred-activities>: "
7468 + parser.getName());
7469 XmlUtils.skipCurrentTag(parser);
7470 }
7471 }
7472
7473 if (setPos != setCount) {
7474 if (mParseError == null) {
7475 mParseError = "Not enough set tags (expected " + setCount
7476 + " but found " + setPos + ") in " + mShortActivity;
7477 }
7478 }
7479
7480 mSetPackages = myPackages;
7481 mSetClasses = myClasses;
7482 mSetComponents = myComponents;
7483 }
7484
7485 public void writeToXml(XmlSerializer serializer) throws IOException {
7486 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7487 serializer.attribute(null, "name", mShortActivity);
7488 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7489 serializer.attribute(null, "set", Integer.toString(NS));
7490 for (int s=0; s<NS; s++) {
7491 serializer.startTag(null, "set");
7492 serializer.attribute(null, "name", mSetComponents[s]);
7493 serializer.endTag(null, "set");
7494 }
7495 serializer.startTag(null, "filter");
7496 super.writeToXml(serializer);
7497 serializer.endTag(null, "filter");
7498 }
7499
7500 boolean sameSet(List<ResolveInfo> query, int priority) {
7501 if (mSetPackages == null) return false;
7502 final int NQ = query.size();
7503 final int NS = mSetPackages.length;
7504 int numMatch = 0;
7505 for (int i=0; i<NQ; i++) {
7506 ResolveInfo ri = query.get(i);
7507 if (ri.priority != priority) continue;
7508 ActivityInfo ai = ri.activityInfo;
7509 boolean good = false;
7510 for (int j=0; j<NS; j++) {
7511 if (mSetPackages[j].equals(ai.packageName)
7512 && mSetClasses[j].equals(ai.name)) {
7513 numMatch++;
7514 good = true;
7515 break;
7516 }
7517 }
7518 if (!good) return false;
7519 }
7520 return numMatch == NS;
7521 }
7522 }
7523
7524 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007525 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007527 HashSet<String> grantedPermissions = new HashSet<String>();
7528 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007531 setFlags(pkgFlags);
7532 }
7533
7534 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007535 this.pkgFlags = pkgFlags & (
7536 ApplicationInfo.FLAG_SYSTEM |
7537 ApplicationInfo.FLAG_FORWARD_LOCK |
7538 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 }
7540 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 /**
7543 * Settings base class for pending and resolved classes.
7544 */
7545 static class PackageSettingBase extends GrantedPermissions {
7546 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007547 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007548 File codePath;
7549 String codePathString;
7550 File resourcePath;
7551 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 private long timeStamp;
7553 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007554 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007556 boolean uidError;
7557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558 PackageSignatures signatures = new PackageSignatures();
7559
7560 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007561 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007563 /* Explicitly disabled components */
7564 HashSet<String> disabledComponents = new HashSet<String>(0);
7565 /* Explicitly enabled components */
7566 HashSet<String> enabledComponents = new HashSet<String>(0);
7567 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7568 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007569
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007570 PackageSettingBase origPackage;
7571
Jacek Surazski65e13172009-04-28 15:26:38 +02007572 /* package name of the app that installed this package */
7573 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007575 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007576 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007577 super(pkgFlags);
7578 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007579 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007580 init(codePath, resourcePath, pVersionCode);
7581 }
7582
7583 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 this.codePath = codePath;
7585 this.codePathString = codePath.toString();
7586 this.resourcePath = resourcePath;
7587 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007588 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007589 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007590
Jacek Surazski65e13172009-04-28 15:26:38 +02007591 public void setInstallerPackageName(String packageName) {
7592 installerPackageName = packageName;
7593 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007594
Jacek Surazski65e13172009-04-28 15:26:38 +02007595 String getInstallerPackageName() {
7596 return installerPackageName;
7597 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 public void setInstallStatus(int newStatus) {
7600 installStatus = newStatus;
7601 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603 public int getInstallStatus() {
7604 return installStatus;
7605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007607 public void setTimeStamp(long newStamp) {
7608 if (newStamp != timeStamp) {
7609 timeStamp = newStamp;
7610 timeStampString = Long.toString(newStamp);
7611 }
7612 }
7613
7614 public void setTimeStamp(long newStamp, String newStampStr) {
7615 timeStamp = newStamp;
7616 timeStampString = newStampStr;
7617 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619 public long getTimeStamp() {
7620 return timeStamp;
7621 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007623 public String getTimeStampStr() {
7624 return timeStampString;
7625 }
7626
7627 public void copyFrom(PackageSettingBase base) {
7628 grantedPermissions = base.grantedPermissions;
7629 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007631 timeStamp = base.timeStamp;
7632 timeStampString = base.timeStampString;
7633 signatures = base.signatures;
7634 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007635 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 disabledComponents = base.disabledComponents;
7637 enabledComponents = base.enabledComponents;
7638 enabled = base.enabled;
7639 installStatus = base.installStatus;
7640 }
7641
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007642 boolean enableComponentLP(String componentClassName) {
7643 boolean changed = disabledComponents.remove(componentClassName);
7644 changed |= enabledComponents.add(componentClassName);
7645 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007646 }
7647
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007648 boolean disableComponentLP(String componentClassName) {
7649 boolean changed = enabledComponents.remove(componentClassName);
7650 changed |= disabledComponents.add(componentClassName);
7651 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 }
7653
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007654 boolean restoreComponentLP(String componentClassName) {
7655 boolean changed = enabledComponents.remove(componentClassName);
7656 changed |= disabledComponents.remove(componentClassName);
7657 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007658 }
7659
7660 int currentEnabledStateLP(String componentName) {
7661 if (enabledComponents.contains(componentName)) {
7662 return COMPONENT_ENABLED_STATE_ENABLED;
7663 } else if (disabledComponents.contains(componentName)) {
7664 return COMPONENT_ENABLED_STATE_DISABLED;
7665 } else {
7666 return COMPONENT_ENABLED_STATE_DEFAULT;
7667 }
7668 }
7669 }
7670
7671 /**
7672 * Settings data for a particular package we know about.
7673 */
7674 static final class PackageSetting extends PackageSettingBase {
7675 int userId;
7676 PackageParser.Package pkg;
7677 SharedUserSetting sharedUser;
7678
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007679 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007680 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007681 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007684 @Override
7685 public String toString() {
7686 return "PackageSetting{"
7687 + Integer.toHexString(System.identityHashCode(this))
7688 + " " + name + "/" + userId + "}";
7689 }
7690 }
7691
7692 /**
7693 * Settings data for a particular shared user ID we know about.
7694 */
7695 static final class SharedUserSetting extends GrantedPermissions {
7696 final String name;
7697 int userId;
7698 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7699 final PackageSignatures signatures = new PackageSignatures();
7700
7701 SharedUserSetting(String _name, int _pkgFlags) {
7702 super(_pkgFlags);
7703 name = _name;
7704 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007706 @Override
7707 public String toString() {
7708 return "SharedUserSetting{"
7709 + Integer.toHexString(System.identityHashCode(this))
7710 + " " + name + "/" + userId + "}";
7711 }
7712 }
7713
7714 /**
7715 * Holds information about dynamic settings.
7716 */
7717 private static final class Settings {
7718 private final File mSettingsFilename;
7719 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007720 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721 private final HashMap<String, PackageSetting> mPackages =
7722 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007723 // List of replaced system applications
7724 final HashMap<String, PackageSetting> mDisabledSysPackages =
7725 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007726
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007727 // These are the last platform API version we were using for
7728 // the apps installed on internal and external storage. It is
7729 // used to grant newer permissions one time during a system upgrade.
7730 int mInternalSdkPlatform;
7731 int mExternalSdkPlatform;
7732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007733 // The user's preferred activities associated with particular intent
7734 // filters.
7735 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7736 new IntentResolver<PreferredActivity, PreferredActivity>() {
7737 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007738 protected String packageForFilter(PreferredActivity filter) {
7739 return filter.mActivity.getPackageName();
7740 }
7741 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007742 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007744 out.print(prefix); out.print(
7745 Integer.toHexString(System.identityHashCode(filter)));
7746 out.print(' ');
7747 out.print(filter.mActivity.flattenToShortString());
7748 out.print(" match=0x");
7749 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007751 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007752 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007753 out.print(prefix); out.print(" ");
7754 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007755 }
7756 }
7757 }
7758 };
7759 private final HashMap<String, SharedUserSetting> mSharedUsers =
7760 new HashMap<String, SharedUserSetting>();
7761 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7762 private final SparseArray<Object> mOtherUserIds =
7763 new SparseArray<Object>();
7764
7765 // For reading/writing settings file.
7766 private final ArrayList<Signature> mPastSignatures =
7767 new ArrayList<Signature>();
7768
7769 // Mapping from permission names to info about them.
7770 final HashMap<String, BasePermission> mPermissions =
7771 new HashMap<String, BasePermission>();
7772
7773 // Mapping from permission tree names to info about them.
7774 final HashMap<String, BasePermission> mPermissionTrees =
7775 new HashMap<String, BasePermission>();
7776
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007777 // Packages that have been uninstalled and still need their external
7778 // storage data deleted.
7779 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7780
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007781 // Packages that have been renamed since they were first installed.
7782 // Keys are the new names of the packages, values are the original
7783 // names. The packages appear everwhere else under their original
7784 // names.
7785 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 private final StringBuilder mReadMessages = new StringBuilder();
7788
7789 private static final class PendingPackage extends PackageSettingBase {
7790 final int sharedId;
7791
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007792 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007793 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007794 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 this.sharedId = sharedId;
7796 }
7797 }
7798 private final ArrayList<PendingPackage> mPendingPackages
7799 = new ArrayList<PendingPackage>();
7800
7801 Settings() {
7802 File dataDir = Environment.getDataDirectory();
7803 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007804 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 systemDir.mkdirs();
7806 FileUtils.setPermissions(systemDir.toString(),
7807 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7808 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7809 -1, -1);
7810 mSettingsFilename = new File(systemDir, "packages.xml");
7811 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007812 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007813 }
7814
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007815 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007816 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 int pkgFlags, boolean create, boolean add) {
7818 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007819 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007820 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 return p;
7822 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007823
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007824 PackageSetting peekPackageLP(String name) {
7825 return mPackages.get(name);
7826 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 PackageSetting p = mPackages.get(name);
7828 if (p != null && p.codePath.getPath().equals(codePath)) {
7829 return p;
7830 }
7831 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007832 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007835 void setInstallStatus(String pkgName, int status) {
7836 PackageSetting p = mPackages.get(pkgName);
7837 if(p != null) {
7838 if(p.getInstallStatus() != status) {
7839 p.setInstallStatus(status);
7840 }
7841 }
7842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007843
Jacek Surazski65e13172009-04-28 15:26:38 +02007844 void setInstallerPackageName(String pkgName,
7845 String installerPkgName) {
7846 PackageSetting p = mPackages.get(pkgName);
7847 if(p != null) {
7848 p.setInstallerPackageName(installerPkgName);
7849 }
7850 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007851
Jacek Surazski65e13172009-04-28 15:26:38 +02007852 String getInstallerPackageName(String pkgName) {
7853 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007854 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007855 }
7856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 int getInstallStatus(String pkgName) {
7858 PackageSetting p = mPackages.get(pkgName);
7859 if(p != null) {
7860 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 return -1;
7863 }
7864
7865 SharedUserSetting getSharedUserLP(String name,
7866 int pkgFlags, boolean create) {
7867 SharedUserSetting s = mSharedUsers.get(name);
7868 if (s == null) {
7869 if (!create) {
7870 return null;
7871 }
7872 s = new SharedUserSetting(name, pkgFlags);
7873 if (MULTIPLE_APPLICATION_UIDS) {
7874 s.userId = newUserIdLP(s);
7875 } else {
7876 s.userId = FIRST_APPLICATION_UID;
7877 }
7878 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7879 // < 0 means we couldn't assign a userid; fall out and return
7880 // s, which is currently null
7881 if (s.userId >= 0) {
7882 mSharedUsers.put(name, s);
7883 }
7884 }
7885
7886 return s;
7887 }
7888
7889 int disableSystemPackageLP(String name) {
7890 PackageSetting p = mPackages.get(name);
7891 if(p == null) {
7892 Log.w(TAG, "Package:"+name+" is not an installed package");
7893 return -1;
7894 }
7895 PackageSetting dp = mDisabledSysPackages.get(name);
7896 // always make sure the system package code and resource paths dont change
7897 if(dp == null) {
7898 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7899 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7900 }
7901 mDisabledSysPackages.put(name, p);
7902 }
7903 return removePackageLP(name);
7904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 PackageSetting enableSystemPackageLP(String name) {
7907 PackageSetting p = mDisabledSysPackages.get(name);
7908 if(p == null) {
7909 Log.w(TAG, "Package:"+name+" is not disabled");
7910 return null;
7911 }
7912 // Reset flag in ApplicationInfo object
7913 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7914 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7915 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007916 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007917 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007918 mDisabledSysPackages.remove(name);
7919 return ret;
7920 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007921
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007922 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007923 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 PackageSetting p = mPackages.get(name);
7925 if (p != null) {
7926 if (p.userId == uid) {
7927 return p;
7928 }
7929 reportSettingsProblem(Log.ERROR,
7930 "Adding duplicate package, keeping first: " + name);
7931 return null;
7932 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007933 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007934 p.userId = uid;
7935 if (addUserIdLP(uid, p, name)) {
7936 mPackages.put(name, p);
7937 return p;
7938 }
7939 return null;
7940 }
7941
7942 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7943 SharedUserSetting s = mSharedUsers.get(name);
7944 if (s != null) {
7945 if (s.userId == uid) {
7946 return s;
7947 }
7948 reportSettingsProblem(Log.ERROR,
7949 "Adding duplicate shared user, keeping first: " + name);
7950 return null;
7951 }
7952 s = new SharedUserSetting(name, pkgFlags);
7953 s.userId = uid;
7954 if (addUserIdLP(uid, s, name)) {
7955 mSharedUsers.put(name, s);
7956 return s;
7957 }
7958 return null;
7959 }
7960
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007961 // Transfer ownership of permissions from one package to another.
7962 private void transferPermissions(String origPkg, String newPkg) {
7963 // Transfer ownership of permissions to the new package.
7964 for (int i=0; i<2; i++) {
7965 HashMap<String, BasePermission> permissions =
7966 i == 0 ? mPermissionTrees : mPermissions;
7967 for (BasePermission bp : permissions.values()) {
7968 if (origPkg.equals(bp.sourcePackage)) {
7969 if (DEBUG_UPGRADE) Log.v(TAG,
7970 "Moving permission " + bp.name
7971 + " from pkg " + bp.sourcePackage
7972 + " to " + newPkg);
7973 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007974 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007975 bp.perm = null;
7976 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007977 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007978 }
7979 bp.uid = 0;
7980 bp.gids = null;
7981 }
7982 }
7983 }
7984 }
7985
7986 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007987 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007988 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007989 PackageSetting p = mPackages.get(name);
7990 if (p != null) {
7991 if (!p.codePath.equals(codePath)) {
7992 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007993 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007994 // This is an updated system app with versions in both system
7995 // and data partition. Just let the most recent version
7996 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007997 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007998 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007999 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008000 // Just a change in the code path is not an issue, but
8001 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008002 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008003 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008004 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008005 }
8006 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008007 reportSettingsProblem(Log.WARN,
8008 "Package " + name + " shared user changed from "
8009 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8010 + " to "
8011 + (sharedUser != null ? sharedUser.name : "<nothing>")
8012 + "; replacing with new");
8013 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008014 } else {
8015 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8016 // If what we are scanning is a system package, then
8017 // make it so, regardless of whether it was previously
8018 // installed only in the data partition.
8019 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008021 }
8022 }
8023 if (p == null) {
8024 // Create a new PackageSettings entry. this can end up here because
8025 // of code path mismatch or user id mismatch of an updated system partition
8026 if (!create) {
8027 return null;
8028 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008029 if (origPackage != null) {
8030 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008031 p = new PackageSetting(origPackage.name, name, codePath,
8032 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008033 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8034 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008035 // Note that we will retain the new package's signature so
8036 // that we can keep its data.
8037 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008038 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008039 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008040 p.sharedUser = origPackage.sharedUser;
8041 p.userId = origPackage.userId;
8042 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008043 mRenamedPackages.put(name, origPackage.name);
8044 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008045 // Update new package state.
8046 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008047 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008048 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008049 p.setTimeStamp(codePath.lastModified());
8050 p.sharedUser = sharedUser;
8051 if (sharedUser != null) {
8052 p.userId = sharedUser.userId;
8053 } else if (MULTIPLE_APPLICATION_UIDS) {
8054 // Clone the setting here for disabled system packages
8055 PackageSetting dis = mDisabledSysPackages.get(name);
8056 if (dis != null) {
8057 // For disabled packages a new setting is created
8058 // from the existing user id. This still has to be
8059 // added to list of user id's
8060 // Copy signatures from previous setting
8061 if (dis.signatures.mSignatures != null) {
8062 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8063 }
8064 p.userId = dis.userId;
8065 // Clone permissions
8066 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008067 // Clone component info
8068 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8069 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8070 // Add new setting to list of user ids
8071 addUserIdLP(p.userId, p, name);
8072 } else {
8073 // Assign new user id
8074 p.userId = newUserIdLP(p);
8075 }
8076 } else {
8077 p.userId = FIRST_APPLICATION_UID;
8078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 }
8080 if (p.userId < 0) {
8081 reportSettingsProblem(Log.WARN,
8082 "Package " + name + " could not be assigned a valid uid");
8083 return null;
8084 }
8085 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008086 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008088 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 }
8090 }
8091 return p;
8092 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008093
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008094 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008095 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008096 String codePath = pkg.applicationInfo.sourceDir;
8097 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008098 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008099 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008100 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008101 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008102 p.codePath = new File(codePath);
8103 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008104 }
8105 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008106 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008107 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008108 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008109 p.resourcePath = new File(resourcePath);
8110 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008111 }
8112 // Update version code if needed
8113 if (pkg.mVersionCode != p.versionCode) {
8114 p.versionCode = pkg.mVersionCode;
8115 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008116 // Update signatures if needed.
8117 if (p.signatures.mSignatures == null) {
8118 p.signatures.assignSignatures(pkg.mSignatures);
8119 }
8120 // If this app defines a shared user id initialize
8121 // the shared user signatures as well.
8122 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8123 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8124 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008125 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8126 }
8127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 // Utility method that adds a PackageSetting to mPackages and
8129 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008130 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008131 SharedUserSetting sharedUser) {
8132 mPackages.put(name, p);
8133 if (sharedUser != null) {
8134 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8135 reportSettingsProblem(Log.ERROR,
8136 "Package " + p.name + " was user "
8137 + p.sharedUser + " but is now " + sharedUser
8138 + "; I am not changing its files so it will probably fail!");
8139 p.sharedUser.packages.remove(p);
8140 } else if (p.userId != sharedUser.userId) {
8141 reportSettingsProblem(Log.ERROR,
8142 "Package " + p.name + " was user id " + p.userId
8143 + " but is now user " + sharedUser
8144 + " with id " + sharedUser.userId
8145 + "; I am not changing its files so it will probably fail!");
8146 }
8147
8148 sharedUser.packages.add(p);
8149 p.sharedUser = sharedUser;
8150 p.userId = sharedUser.userId;
8151 }
8152 }
8153
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008154 /*
8155 * Update the shared user setting when a package using
8156 * specifying the shared user id is removed. The gids
8157 * associated with each permission of the deleted package
8158 * are removed from the shared user's gid list only if its
8159 * not in use by other permissions of packages in the
8160 * shared user setting.
8161 */
8162 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008164 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 return;
8166 }
8167 // No sharedUserId
8168 if (deletedPs.sharedUser == null) {
8169 return;
8170 }
8171 SharedUserSetting sus = deletedPs.sharedUser;
8172 // Update permissions
8173 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8174 boolean used = false;
8175 if (!sus.grantedPermissions.contains (eachPerm)) {
8176 continue;
8177 }
8178 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008179 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008180 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008181 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 used = true;
8183 break;
8184 }
8185 }
8186 if (!used) {
8187 // can safely delete this permission from list
8188 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008189 }
8190 }
8191 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008192 int newGids[] = globalGids;
8193 for (String eachPerm : sus.grantedPermissions) {
8194 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008195 if (bp != null) {
8196 newGids = appendInts(newGids, bp.gids);
8197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008198 }
8199 sus.gids = newGids;
8200 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008202 private int removePackageLP(String name) {
8203 PackageSetting p = mPackages.get(name);
8204 if (p != null) {
8205 mPackages.remove(name);
8206 if (p.sharedUser != null) {
8207 p.sharedUser.packages.remove(p);
8208 if (p.sharedUser.packages.size() == 0) {
8209 mSharedUsers.remove(p.sharedUser.name);
8210 removeUserIdLP(p.sharedUser.userId);
8211 return p.sharedUser.userId;
8212 }
8213 } else {
8214 removeUserIdLP(p.userId);
8215 return p.userId;
8216 }
8217 }
8218 return -1;
8219 }
8220
8221 private boolean addUserIdLP(int uid, Object obj, Object name) {
8222 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8223 return false;
8224 }
8225
8226 if (uid >= FIRST_APPLICATION_UID) {
8227 int N = mUserIds.size();
8228 final int index = uid - FIRST_APPLICATION_UID;
8229 while (index >= N) {
8230 mUserIds.add(null);
8231 N++;
8232 }
8233 if (mUserIds.get(index) != null) {
8234 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008235 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008236 + " name=" + name);
8237 return false;
8238 }
8239 mUserIds.set(index, obj);
8240 } else {
8241 if (mOtherUserIds.get(uid) != null) {
8242 reportSettingsProblem(Log.ERROR,
8243 "Adding duplicate shared id: " + uid
8244 + " name=" + name);
8245 return false;
8246 }
8247 mOtherUserIds.put(uid, obj);
8248 }
8249 return true;
8250 }
8251
8252 public Object getUserIdLP(int uid) {
8253 if (uid >= FIRST_APPLICATION_UID) {
8254 int N = mUserIds.size();
8255 final int index = uid - FIRST_APPLICATION_UID;
8256 return index < N ? mUserIds.get(index) : null;
8257 } else {
8258 return mOtherUserIds.get(uid);
8259 }
8260 }
8261
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008262 private Set<String> findPackagesWithFlag(int flag) {
8263 Set<String> ret = new HashSet<String>();
8264 for (PackageSetting ps : mPackages.values()) {
8265 // Has to match atleast all the flag bits set on flag
8266 if ((ps.pkgFlags & flag) == flag) {
8267 ret.add(ps.name);
8268 }
8269 }
8270 return ret;
8271 }
8272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273 private void removeUserIdLP(int uid) {
8274 if (uid >= FIRST_APPLICATION_UID) {
8275 int N = mUserIds.size();
8276 final int index = uid - FIRST_APPLICATION_UID;
8277 if (index < N) mUserIds.set(index, null);
8278 } else {
8279 mOtherUserIds.remove(uid);
8280 }
8281 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283 void writeLP() {
8284 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8285
8286 // Keep the old settings around until we know the new ones have
8287 // been successfully written.
8288 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008289 // Presence of backup settings file indicates that we failed
8290 // to persist settings earlier. So preserve the older
8291 // backup for future reference since the current settings
8292 // might have been corrupted.
8293 if (!mBackupSettingsFilename.exists()) {
8294 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008295 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008296 return;
8297 }
8298 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008299 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008300 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 }
8303
8304 mPastSignatures.clear();
8305
8306 try {
8307 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8308
8309 //XmlSerializer serializer = XmlUtils.serializerInstance();
8310 XmlSerializer serializer = new FastXmlSerializer();
8311 serializer.setOutput(str, "utf-8");
8312 serializer.startDocument(null, true);
8313 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8314
8315 serializer.startTag(null, "packages");
8316
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008317 serializer.startTag(null, "last-platform-version");
8318 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8319 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8320 serializer.endTag(null, "last-platform-version");
8321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008322 serializer.startTag(null, "permission-trees");
8323 for (BasePermission bp : mPermissionTrees.values()) {
8324 writePermission(serializer, bp);
8325 }
8326 serializer.endTag(null, "permission-trees");
8327
8328 serializer.startTag(null, "permissions");
8329 for (BasePermission bp : mPermissions.values()) {
8330 writePermission(serializer, bp);
8331 }
8332 serializer.endTag(null, "permissions");
8333
8334 for (PackageSetting pkg : mPackages.values()) {
8335 writePackage(serializer, pkg);
8336 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8339 writeDisabledSysPackage(serializer, pkg);
8340 }
8341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008342 serializer.startTag(null, "preferred-activities");
8343 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8344 serializer.startTag(null, "item");
8345 pa.writeToXml(serializer);
8346 serializer.endTag(null, "item");
8347 }
8348 serializer.endTag(null, "preferred-activities");
8349
8350 for (SharedUserSetting usr : mSharedUsers.values()) {
8351 serializer.startTag(null, "shared-user");
8352 serializer.attribute(null, "name", usr.name);
8353 serializer.attribute(null, "userId",
8354 Integer.toString(usr.userId));
8355 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8356 serializer.startTag(null, "perms");
8357 for (String name : usr.grantedPermissions) {
8358 serializer.startTag(null, "item");
8359 serializer.attribute(null, "name", name);
8360 serializer.endTag(null, "item");
8361 }
8362 serializer.endTag(null, "perms");
8363 serializer.endTag(null, "shared-user");
8364 }
8365
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008366 if (mPackagesToBeCleaned.size() > 0) {
8367 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8368 serializer.startTag(null, "cleaning-package");
8369 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8370 serializer.endTag(null, "cleaning-package");
8371 }
8372 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008373
8374 if (mRenamedPackages.size() > 0) {
8375 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8376 serializer.startTag(null, "renamed-package");
8377 serializer.attribute(null, "new", e.getKey());
8378 serializer.attribute(null, "old", e.getValue());
8379 serializer.endTag(null, "renamed-package");
8380 }
8381 }
8382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008383 serializer.endTag(null, "packages");
8384
8385 serializer.endDocument();
8386
8387 str.flush();
8388 str.close();
8389
8390 // New settings successfully written, old ones are no longer
8391 // needed.
8392 mBackupSettingsFilename.delete();
8393 FileUtils.setPermissions(mSettingsFilename.toString(),
8394 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8395 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8396 |FileUtils.S_IROTH,
8397 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008398
8399 // Write package list file now, use a JournaledFile.
8400 //
8401 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8402 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8403
8404 str = new FileOutputStream(journal.chooseForWrite());
8405 try {
8406 StringBuilder sb = new StringBuilder();
8407 for (PackageSetting pkg : mPackages.values()) {
8408 ApplicationInfo ai = pkg.pkg.applicationInfo;
8409 String dataPath = ai.dataDir;
8410 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8411
8412 // Avoid any application that has a space in its path
8413 // or that is handled by the system.
8414 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8415 continue;
8416
8417 // we store on each line the following information for now:
8418 //
8419 // pkgName - package name
8420 // userId - application-specific user id
8421 // debugFlag - 0 or 1 if the package is debuggable.
8422 // dataPath - path to package's data path
8423 //
8424 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8425 //
8426 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8427 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8428 // system/core/run-as/run-as.c
8429 //
8430 sb.setLength(0);
8431 sb.append(ai.packageName);
8432 sb.append(" ");
8433 sb.append((int)ai.uid);
8434 sb.append(isDebug ? " 1 " : " 0 ");
8435 sb.append(dataPath);
8436 sb.append("\n");
8437 str.write(sb.toString().getBytes());
8438 }
8439 str.flush();
8440 str.close();
8441 journal.commit();
8442 }
8443 catch (Exception e) {
8444 journal.rollback();
8445 }
8446
8447 FileUtils.setPermissions(mPackageListFilename.toString(),
8448 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8449 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8450 |FileUtils.S_IROTH,
8451 -1, -1);
8452
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008453 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008454
8455 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008456 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 -08008457 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008458 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 -08008459 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008460 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008461 if (mSettingsFilename.exists()) {
8462 if (!mSettingsFilename.delete()) {
8463 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8464 }
8465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 //Debug.stopMethodTracing();
8467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008468
8469 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008470 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008471 serializer.startTag(null, "updated-package");
8472 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008473 if (pkg.realName != null) {
8474 serializer.attribute(null, "realName", pkg.realName);
8475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 serializer.attribute(null, "codePath", pkg.codePathString);
8477 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008478 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008479 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8480 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8481 }
8482 if (pkg.sharedUser == null) {
8483 serializer.attribute(null, "userId",
8484 Integer.toString(pkg.userId));
8485 } else {
8486 serializer.attribute(null, "sharedUserId",
8487 Integer.toString(pkg.userId));
8488 }
8489 serializer.startTag(null, "perms");
8490 if (pkg.sharedUser == null) {
8491 // If this is a shared user, the permissions will
8492 // be written there. We still need to write an
8493 // empty permissions list so permissionsFixed will
8494 // be set.
8495 for (final String name : pkg.grantedPermissions) {
8496 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008497 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008498 // We only need to write signature or system permissions but this wont
8499 // match the semantics of grantedPermissions. So write all permissions.
8500 serializer.startTag(null, "item");
8501 serializer.attribute(null, "name", name);
8502 serializer.endTag(null, "item");
8503 }
8504 }
8505 }
8506 serializer.endTag(null, "perms");
8507 serializer.endTag(null, "updated-package");
8508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008509
8510 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008511 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008512 serializer.startTag(null, "package");
8513 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008514 if (pkg.realName != null) {
8515 serializer.attribute(null, "realName", pkg.realName);
8516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 serializer.attribute(null, "codePath", pkg.codePathString);
8518 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8519 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8520 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008521 serializer.attribute(null, "flags",
8522 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008524 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 if (pkg.sharedUser == null) {
8526 serializer.attribute(null, "userId",
8527 Integer.toString(pkg.userId));
8528 } else {
8529 serializer.attribute(null, "sharedUserId",
8530 Integer.toString(pkg.userId));
8531 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008532 if (pkg.uidError) {
8533 serializer.attribute(null, "uidError", "true");
8534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008535 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8536 serializer.attribute(null, "enabled",
8537 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8538 ? "true" : "false");
8539 }
8540 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8541 serializer.attribute(null, "installStatus", "false");
8542 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008543 if (pkg.installerPackageName != null) {
8544 serializer.attribute(null, "installer", pkg.installerPackageName);
8545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008546 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8547 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8548 serializer.startTag(null, "perms");
8549 if (pkg.sharedUser == null) {
8550 // If this is a shared user, the permissions will
8551 // be written there. We still need to write an
8552 // empty permissions list so permissionsFixed will
8553 // be set.
8554 for (final String name : pkg.grantedPermissions) {
8555 serializer.startTag(null, "item");
8556 serializer.attribute(null, "name", name);
8557 serializer.endTag(null, "item");
8558 }
8559 }
8560 serializer.endTag(null, "perms");
8561 }
8562 if (pkg.disabledComponents.size() > 0) {
8563 serializer.startTag(null, "disabled-components");
8564 for (final String name : pkg.disabledComponents) {
8565 serializer.startTag(null, "item");
8566 serializer.attribute(null, "name", name);
8567 serializer.endTag(null, "item");
8568 }
8569 serializer.endTag(null, "disabled-components");
8570 }
8571 if (pkg.enabledComponents.size() > 0) {
8572 serializer.startTag(null, "enabled-components");
8573 for (final String name : pkg.enabledComponents) {
8574 serializer.startTag(null, "item");
8575 serializer.attribute(null, "name", name);
8576 serializer.endTag(null, "item");
8577 }
8578 serializer.endTag(null, "enabled-components");
8579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008581 serializer.endTag(null, "package");
8582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008584 void writePermission(XmlSerializer serializer, BasePermission bp)
8585 throws XmlPullParserException, java.io.IOException {
8586 if (bp.type != BasePermission.TYPE_BUILTIN
8587 && bp.sourcePackage != null) {
8588 serializer.startTag(null, "item");
8589 serializer.attribute(null, "name", bp.name);
8590 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008591 if (bp.protectionLevel !=
8592 PermissionInfo.PROTECTION_NORMAL) {
8593 serializer.attribute(null, "protection",
8594 Integer.toString(bp.protectionLevel));
8595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 if (DEBUG_SETTINGS) Log.v(TAG,
8597 "Writing perm: name=" + bp.name + " type=" + bp.type);
8598 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8599 PermissionInfo pi = bp.perm != null ? bp.perm.info
8600 : bp.pendingInfo;
8601 if (pi != null) {
8602 serializer.attribute(null, "type", "dynamic");
8603 if (pi.icon != 0) {
8604 serializer.attribute(null, "icon",
8605 Integer.toString(pi.icon));
8606 }
8607 if (pi.nonLocalizedLabel != null) {
8608 serializer.attribute(null, "label",
8609 pi.nonLocalizedLabel.toString());
8610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 }
8612 }
8613 serializer.endTag(null, "item");
8614 }
8615 }
8616
8617 String getReadMessagesLP() {
8618 return mReadMessages.toString();
8619 }
8620
Oscar Montemayora8529f62009-11-18 10:14:20 -08008621 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8623 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008624 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 while(its.hasNext()) {
8626 String key = its.next();
8627 PackageSetting ps = mPackages.get(key);
8628 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008629 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008630 }
8631 }
8632 return ret;
8633 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008635 boolean readLP() {
8636 FileInputStream str = null;
8637 if (mBackupSettingsFilename.exists()) {
8638 try {
8639 str = new FileInputStream(mBackupSettingsFilename);
8640 mReadMessages.append("Reading from backup settings file\n");
8641 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008642 if (mSettingsFilename.exists()) {
8643 // If both the backup and settings file exist, we
8644 // ignore the settings since it might have been
8645 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008646 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008647 mSettingsFilename.delete();
8648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008649 } catch (java.io.IOException e) {
8650 // We'll try for the normal settings file.
8651 }
8652 }
8653
8654 mPastSignatures.clear();
8655
8656 try {
8657 if (str == null) {
8658 if (!mSettingsFilename.exists()) {
8659 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008660 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 return false;
8662 }
8663 str = new FileInputStream(mSettingsFilename);
8664 }
8665 XmlPullParser parser = Xml.newPullParser();
8666 parser.setInput(str, null);
8667
8668 int type;
8669 while ((type=parser.next()) != XmlPullParser.START_TAG
8670 && type != XmlPullParser.END_DOCUMENT) {
8671 ;
8672 }
8673
8674 if (type != XmlPullParser.START_TAG) {
8675 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008676 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008677 return false;
8678 }
8679
8680 int outerDepth = parser.getDepth();
8681 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8682 && (type != XmlPullParser.END_TAG
8683 || parser.getDepth() > outerDepth)) {
8684 if (type == XmlPullParser.END_TAG
8685 || type == XmlPullParser.TEXT) {
8686 continue;
8687 }
8688
8689 String tagName = parser.getName();
8690 if (tagName.equals("package")) {
8691 readPackageLP(parser);
8692 } else if (tagName.equals("permissions")) {
8693 readPermissionsLP(mPermissions, parser);
8694 } else if (tagName.equals("permission-trees")) {
8695 readPermissionsLP(mPermissionTrees, parser);
8696 } else if (tagName.equals("shared-user")) {
8697 readSharedUserLP(parser);
8698 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008699 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008700 } else if (tagName.equals("preferred-activities")) {
8701 readPreferredActivitiesLP(parser);
8702 } else if(tagName.equals("updated-package")) {
8703 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008704 } else if (tagName.equals("cleaning-package")) {
8705 String name = parser.getAttributeValue(null, "name");
8706 if (name != null) {
8707 mPackagesToBeCleaned.add(name);
8708 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008709 } else if (tagName.equals("renamed-package")) {
8710 String nname = parser.getAttributeValue(null, "new");
8711 String oname = parser.getAttributeValue(null, "old");
8712 if (nname != null && oname != null) {
8713 mRenamedPackages.put(nname, oname);
8714 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008715 } else if (tagName.equals("last-platform-version")) {
8716 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8717 try {
8718 String internal = parser.getAttributeValue(null, "internal");
8719 if (internal != null) {
8720 mInternalSdkPlatform = Integer.parseInt(internal);
8721 }
8722 String external = parser.getAttributeValue(null, "external");
8723 if (external != null) {
8724 mInternalSdkPlatform = Integer.parseInt(external);
8725 }
8726 } catch (NumberFormatException e) {
8727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008729 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008730 + parser.getName());
8731 XmlUtils.skipCurrentTag(parser);
8732 }
8733 }
8734
8735 str.close();
8736
8737 } catch(XmlPullParserException e) {
8738 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008739 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008740
8741 } catch(java.io.IOException e) {
8742 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008743 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008744
8745 }
8746
8747 int N = mPendingPackages.size();
8748 for (int i=0; i<N; i++) {
8749 final PendingPackage pp = mPendingPackages.get(i);
8750 Object idObj = getUserIdLP(pp.sharedId);
8751 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008752 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008754 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008755 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008756 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008757 + pp.name);
8758 continue;
8759 }
8760 p.copyFrom(pp);
8761 } else if (idObj != null) {
8762 String msg = "Bad package setting: package " + pp.name
8763 + " has shared uid " + pp.sharedId
8764 + " that is not a shared uid\n";
8765 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008766 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008767 } else {
8768 String msg = "Bad package setting: package " + pp.name
8769 + " has shared uid " + pp.sharedId
8770 + " that is not defined\n";
8771 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008772 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773 }
8774 }
8775 mPendingPackages.clear();
8776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008777 mReadMessages.append("Read completed successfully: "
8778 + mPackages.size() + " packages, "
8779 + mSharedUsers.size() + " shared uids\n");
8780
8781 return true;
8782 }
8783
8784 private int readInt(XmlPullParser parser, String ns, String name,
8785 int defValue) {
8786 String v = parser.getAttributeValue(ns, name);
8787 try {
8788 if (v == null) {
8789 return defValue;
8790 }
8791 return Integer.parseInt(v);
8792 } catch (NumberFormatException e) {
8793 reportSettingsProblem(Log.WARN,
8794 "Error in package manager settings: attribute " +
8795 name + " has bad integer value " + v + " at "
8796 + parser.getPositionDescription());
8797 }
8798 return defValue;
8799 }
8800
8801 private void readPermissionsLP(HashMap<String, BasePermission> out,
8802 XmlPullParser parser)
8803 throws IOException, XmlPullParserException {
8804 int outerDepth = parser.getDepth();
8805 int type;
8806 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8807 && (type != XmlPullParser.END_TAG
8808 || parser.getDepth() > outerDepth)) {
8809 if (type == XmlPullParser.END_TAG
8810 || type == XmlPullParser.TEXT) {
8811 continue;
8812 }
8813
8814 String tagName = parser.getName();
8815 if (tagName.equals("item")) {
8816 String name = parser.getAttributeValue(null, "name");
8817 String sourcePackage = parser.getAttributeValue(null, "package");
8818 String ptype = parser.getAttributeValue(null, "type");
8819 if (name != null && sourcePackage != null) {
8820 boolean dynamic = "dynamic".equals(ptype);
8821 BasePermission bp = new BasePermission(name, sourcePackage,
8822 dynamic
8823 ? BasePermission.TYPE_DYNAMIC
8824 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008825 bp.protectionLevel = readInt(parser, null, "protection",
8826 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008827 if (dynamic) {
8828 PermissionInfo pi = new PermissionInfo();
8829 pi.packageName = sourcePackage.intern();
8830 pi.name = name.intern();
8831 pi.icon = readInt(parser, null, "icon", 0);
8832 pi.nonLocalizedLabel = parser.getAttributeValue(
8833 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008834 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008835 bp.pendingInfo = pi;
8836 }
8837 out.put(bp.name, bp);
8838 } else {
8839 reportSettingsProblem(Log.WARN,
8840 "Error in package manager settings: permissions has"
8841 + " no name at " + parser.getPositionDescription());
8842 }
8843 } else {
8844 reportSettingsProblem(Log.WARN,
8845 "Unknown element reading permissions: "
8846 + parser.getName() + " at "
8847 + parser.getPositionDescription());
8848 }
8849 XmlUtils.skipCurrentTag(parser);
8850 }
8851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008854 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008855 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008856 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008857 String codePathStr = parser.getAttributeValue(null, "codePath");
8858 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008859 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008860 resourcePathStr = codePathStr;
8861 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008862 String version = parser.getAttributeValue(null, "version");
8863 int versionCode = 0;
8864 if (version != null) {
8865 try {
8866 versionCode = Integer.parseInt(version);
8867 } catch (NumberFormatException e) {
8868 }
8869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008871 int pkgFlags = 0;
8872 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008873 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008874 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008875 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008876 String timeStampStr = parser.getAttributeValue(null, "ts");
8877 if (timeStampStr != null) {
8878 try {
8879 long timeStamp = Long.parseLong(timeStampStr);
8880 ps.setTimeStamp(timeStamp, timeStampStr);
8881 } catch (NumberFormatException e) {
8882 }
8883 }
8884 String idStr = parser.getAttributeValue(null, "userId");
8885 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8886 if(ps.userId <= 0) {
8887 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8888 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8889 }
8890 int outerDepth = parser.getDepth();
8891 int type;
8892 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8893 && (type != XmlPullParser.END_TAG
8894 || parser.getDepth() > outerDepth)) {
8895 if (type == XmlPullParser.END_TAG
8896 || type == XmlPullParser.TEXT) {
8897 continue;
8898 }
8899
8900 String tagName = parser.getName();
8901 if (tagName.equals("perms")) {
8902 readGrantedPermissionsLP(parser,
8903 ps.grantedPermissions);
8904 } else {
8905 reportSettingsProblem(Log.WARN,
8906 "Unknown element under <updated-package>: "
8907 + parser.getName());
8908 XmlUtils.skipCurrentTag(parser);
8909 }
8910 }
8911 mDisabledSysPackages.put(name, ps);
8912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008914 private void readPackageLP(XmlPullParser parser)
8915 throws XmlPullParserException, IOException {
8916 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008917 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008918 String idStr = null;
8919 String sharedIdStr = null;
8920 String codePathStr = null;
8921 String resourcePathStr = null;
8922 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008923 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008924 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008925 int pkgFlags = 0;
8926 String timeStampStr;
8927 long timeStamp = 0;
8928 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008929 String version = null;
8930 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008931 try {
8932 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008933 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008935 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8937 codePathStr = parser.getAttributeValue(null, "codePath");
8938 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008939 version = parser.getAttributeValue(null, "version");
8940 if (version != null) {
8941 try {
8942 versionCode = Integer.parseInt(version);
8943 } catch (NumberFormatException e) {
8944 }
8945 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008946 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008947
8948 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008950 try {
8951 pkgFlags = Integer.parseInt(systemStr);
8952 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008953 }
8954 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008955 // For backward compatibility
8956 systemStr = parser.getAttributeValue(null, "system");
8957 if (systemStr != null) {
8958 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8959 } else {
8960 // Old settings that don't specify system... just treat
8961 // them as system, good enough.
8962 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 }
8965 timeStampStr = parser.getAttributeValue(null, "ts");
8966 if (timeStampStr != null) {
8967 try {
8968 timeStamp = Long.parseLong(timeStampStr);
8969 } catch (NumberFormatException e) {
8970 }
8971 }
8972 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8973 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8974 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8975 if (resourcePathStr == null) {
8976 resourcePathStr = codePathStr;
8977 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008978 if (realName != null) {
8979 realName = realName.intern();
8980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008981 if (name == null) {
8982 reportSettingsProblem(Log.WARN,
8983 "Error in package manager settings: <package> has no name at "
8984 + parser.getPositionDescription());
8985 } else if (codePathStr == null) {
8986 reportSettingsProblem(Log.WARN,
8987 "Error in package manager settings: <package> has no codePath at "
8988 + parser.getPositionDescription());
8989 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008990 packageSetting = addPackageLP(name.intern(), realName,
8991 new File(codePathStr), new File(resourcePathStr),
8992 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008993 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8994 + ": userId=" + userId + " pkg=" + packageSetting);
8995 if (packageSetting == null) {
8996 reportSettingsProblem(Log.ERROR,
8997 "Failure adding uid " + userId
8998 + " while parsing settings at "
8999 + parser.getPositionDescription());
9000 } else {
9001 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9002 }
9003 } else if (sharedIdStr != null) {
9004 userId = sharedIdStr != null
9005 ? Integer.parseInt(sharedIdStr) : 0;
9006 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009007 packageSetting = new PendingPackage(name.intern(), realName,
9008 new File(codePathStr), new File(resourcePathStr),
9009 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9011 mPendingPackages.add((PendingPackage) packageSetting);
9012 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9013 + ": sharedUserId=" + userId + " pkg="
9014 + packageSetting);
9015 } else {
9016 reportSettingsProblem(Log.WARN,
9017 "Error in package manager settings: package "
9018 + name + " has bad sharedId " + sharedIdStr
9019 + " at " + parser.getPositionDescription());
9020 }
9021 } else {
9022 reportSettingsProblem(Log.WARN,
9023 "Error in package manager settings: package "
9024 + name + " has bad userId " + idStr + " at "
9025 + parser.getPositionDescription());
9026 }
9027 } catch (NumberFormatException e) {
9028 reportSettingsProblem(Log.WARN,
9029 "Error in package manager settings: package "
9030 + name + " has bad userId " + idStr + " at "
9031 + parser.getPositionDescription());
9032 }
9033 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009034 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009035 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 final String enabledStr = parser.getAttributeValue(null, "enabled");
9037 if (enabledStr != null) {
9038 if (enabledStr.equalsIgnoreCase("true")) {
9039 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9040 } else if (enabledStr.equalsIgnoreCase("false")) {
9041 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9042 } else if (enabledStr.equalsIgnoreCase("default")) {
9043 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9044 } else {
9045 reportSettingsProblem(Log.WARN,
9046 "Error in package manager settings: package "
9047 + name + " has bad enabled value: " + idStr
9048 + " at " + parser.getPositionDescription());
9049 }
9050 } else {
9051 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9052 }
9053 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9054 if (installStatusStr != null) {
9055 if (installStatusStr.equalsIgnoreCase("false")) {
9056 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9057 } else {
9058 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9059 }
9060 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009062 int outerDepth = parser.getDepth();
9063 int type;
9064 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9065 && (type != XmlPullParser.END_TAG
9066 || parser.getDepth() > outerDepth)) {
9067 if (type == XmlPullParser.END_TAG
9068 || type == XmlPullParser.TEXT) {
9069 continue;
9070 }
9071
9072 String tagName = parser.getName();
9073 if (tagName.equals("disabled-components")) {
9074 readDisabledComponentsLP(packageSetting, parser);
9075 } else if (tagName.equals("enabled-components")) {
9076 readEnabledComponentsLP(packageSetting, parser);
9077 } else if (tagName.equals("sigs")) {
9078 packageSetting.signatures.readXml(parser, mPastSignatures);
9079 } else if (tagName.equals("perms")) {
9080 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009081 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009082 packageSetting.permissionsFixed = true;
9083 } else {
9084 reportSettingsProblem(Log.WARN,
9085 "Unknown element under <package>: "
9086 + parser.getName());
9087 XmlUtils.skipCurrentTag(parser);
9088 }
9089 }
9090 } else {
9091 XmlUtils.skipCurrentTag(parser);
9092 }
9093 }
9094
9095 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9096 XmlPullParser parser)
9097 throws IOException, XmlPullParserException {
9098 int outerDepth = parser.getDepth();
9099 int type;
9100 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9101 && (type != XmlPullParser.END_TAG
9102 || parser.getDepth() > outerDepth)) {
9103 if (type == XmlPullParser.END_TAG
9104 || type == XmlPullParser.TEXT) {
9105 continue;
9106 }
9107
9108 String tagName = parser.getName();
9109 if (tagName.equals("item")) {
9110 String name = parser.getAttributeValue(null, "name");
9111 if (name != null) {
9112 packageSetting.disabledComponents.add(name.intern());
9113 } else {
9114 reportSettingsProblem(Log.WARN,
9115 "Error in package manager settings: <disabled-components> has"
9116 + " no name at " + parser.getPositionDescription());
9117 }
9118 } else {
9119 reportSettingsProblem(Log.WARN,
9120 "Unknown element under <disabled-components>: "
9121 + parser.getName());
9122 }
9123 XmlUtils.skipCurrentTag(parser);
9124 }
9125 }
9126
9127 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9128 XmlPullParser parser)
9129 throws IOException, XmlPullParserException {
9130 int outerDepth = parser.getDepth();
9131 int type;
9132 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9133 && (type != XmlPullParser.END_TAG
9134 || parser.getDepth() > outerDepth)) {
9135 if (type == XmlPullParser.END_TAG
9136 || type == XmlPullParser.TEXT) {
9137 continue;
9138 }
9139
9140 String tagName = parser.getName();
9141 if (tagName.equals("item")) {
9142 String name = parser.getAttributeValue(null, "name");
9143 if (name != null) {
9144 packageSetting.enabledComponents.add(name.intern());
9145 } else {
9146 reportSettingsProblem(Log.WARN,
9147 "Error in package manager settings: <enabled-components> has"
9148 + " no name at " + parser.getPositionDescription());
9149 }
9150 } else {
9151 reportSettingsProblem(Log.WARN,
9152 "Unknown element under <enabled-components>: "
9153 + parser.getName());
9154 }
9155 XmlUtils.skipCurrentTag(parser);
9156 }
9157 }
9158
9159 private void readSharedUserLP(XmlPullParser parser)
9160 throws XmlPullParserException, IOException {
9161 String name = null;
9162 String idStr = null;
9163 int pkgFlags = 0;
9164 SharedUserSetting su = null;
9165 try {
9166 name = parser.getAttributeValue(null, "name");
9167 idStr = parser.getAttributeValue(null, "userId");
9168 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9169 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9170 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9171 }
9172 if (name == null) {
9173 reportSettingsProblem(Log.WARN,
9174 "Error in package manager settings: <shared-user> has no name at "
9175 + parser.getPositionDescription());
9176 } else if (userId == 0) {
9177 reportSettingsProblem(Log.WARN,
9178 "Error in package manager settings: shared-user "
9179 + name + " has bad userId " + idStr + " at "
9180 + parser.getPositionDescription());
9181 } else {
9182 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9183 reportSettingsProblem(Log.ERROR,
9184 "Occurred while parsing settings at "
9185 + parser.getPositionDescription());
9186 }
9187 }
9188 } catch (NumberFormatException e) {
9189 reportSettingsProblem(Log.WARN,
9190 "Error in package manager settings: package "
9191 + name + " has bad userId " + idStr + " at "
9192 + parser.getPositionDescription());
9193 };
9194
9195 if (su != null) {
9196 int outerDepth = parser.getDepth();
9197 int type;
9198 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9199 && (type != XmlPullParser.END_TAG
9200 || parser.getDepth() > outerDepth)) {
9201 if (type == XmlPullParser.END_TAG
9202 || type == XmlPullParser.TEXT) {
9203 continue;
9204 }
9205
9206 String tagName = parser.getName();
9207 if (tagName.equals("sigs")) {
9208 su.signatures.readXml(parser, mPastSignatures);
9209 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009210 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009211 } else {
9212 reportSettingsProblem(Log.WARN,
9213 "Unknown element under <shared-user>: "
9214 + parser.getName());
9215 XmlUtils.skipCurrentTag(parser);
9216 }
9217 }
9218
9219 } else {
9220 XmlUtils.skipCurrentTag(parser);
9221 }
9222 }
9223
9224 private void readGrantedPermissionsLP(XmlPullParser parser,
9225 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9226 int outerDepth = parser.getDepth();
9227 int type;
9228 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9229 && (type != XmlPullParser.END_TAG
9230 || parser.getDepth() > outerDepth)) {
9231 if (type == XmlPullParser.END_TAG
9232 || type == XmlPullParser.TEXT) {
9233 continue;
9234 }
9235
9236 String tagName = parser.getName();
9237 if (tagName.equals("item")) {
9238 String name = parser.getAttributeValue(null, "name");
9239 if (name != null) {
9240 outPerms.add(name.intern());
9241 } else {
9242 reportSettingsProblem(Log.WARN,
9243 "Error in package manager settings: <perms> has"
9244 + " no name at " + parser.getPositionDescription());
9245 }
9246 } else {
9247 reportSettingsProblem(Log.WARN,
9248 "Unknown element under <perms>: "
9249 + parser.getName());
9250 }
9251 XmlUtils.skipCurrentTag(parser);
9252 }
9253 }
9254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009255 private void readPreferredActivitiesLP(XmlPullParser parser)
9256 throws XmlPullParserException, IOException {
9257 int outerDepth = parser.getDepth();
9258 int type;
9259 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9260 && (type != XmlPullParser.END_TAG
9261 || parser.getDepth() > outerDepth)) {
9262 if (type == XmlPullParser.END_TAG
9263 || type == XmlPullParser.TEXT) {
9264 continue;
9265 }
9266
9267 String tagName = parser.getName();
9268 if (tagName.equals("item")) {
9269 PreferredActivity pa = new PreferredActivity(parser);
9270 if (pa.mParseError == null) {
9271 mPreferredActivities.addFilter(pa);
9272 } else {
9273 reportSettingsProblem(Log.WARN,
9274 "Error in package manager settings: <preferred-activity> "
9275 + pa.mParseError + " at "
9276 + parser.getPositionDescription());
9277 }
9278 } else {
9279 reportSettingsProblem(Log.WARN,
9280 "Unknown element under <preferred-activities>: "
9281 + parser.getName());
9282 XmlUtils.skipCurrentTag(parser);
9283 }
9284 }
9285 }
9286
9287 // Returns -1 if we could not find an available UserId to assign
9288 private int newUserIdLP(Object obj) {
9289 // Let's be stupidly inefficient for now...
9290 final int N = mUserIds.size();
9291 for (int i=0; i<N; i++) {
9292 if (mUserIds.get(i) == null) {
9293 mUserIds.set(i, obj);
9294 return FIRST_APPLICATION_UID + i;
9295 }
9296 }
9297
9298 // None left?
9299 if (N >= MAX_APPLICATION_UIDS) {
9300 return -1;
9301 }
9302
9303 mUserIds.add(obj);
9304 return FIRST_APPLICATION_UID + N;
9305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009307 public PackageSetting getDisabledSystemPkg(String name) {
9308 synchronized(mPackages) {
9309 PackageSetting ps = mDisabledSysPackages.get(name);
9310 return ps;
9311 }
9312 }
9313
9314 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9315 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9316 if (Config.LOGV) {
9317 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9318 + " componentName = " + componentInfo.name);
9319 Log.v(TAG, "enabledComponents: "
9320 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9321 Log.v(TAG, "disabledComponents: "
9322 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9323 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009324 if (packageSettings == null) {
9325 if (false) {
9326 Log.w(TAG, "WAITING FOR DEBUGGER");
9327 Debug.waitForDebugger();
9328 Log.i(TAG, "We will crash!");
9329 }
9330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9332 || ((componentInfo.enabled
9333 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9334 || (componentInfo.applicationInfo.enabled
9335 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9336 && !packageSettings.disabledComponents.contains(componentInfo.name))
9337 || packageSettings.enabledComponents.contains(componentInfo.name));
9338 }
9339 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009340
9341 // ------- apps on sdcard specific code -------
9342 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009343 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009344 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009345 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009346 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009347
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009348 private String getEncryptKey() {
9349 try {
9350 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9351 if (sdEncKey == null) {
9352 sdEncKey = SystemKeyStore.getInstance().
9353 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9354 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009355 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009356 return null;
9357 }
9358 }
9359 return sdEncKey;
9360 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009361 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009362 return null;
9363 }
9364 }
9365
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009366 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009367 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009368 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009369 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009370 if (list != null) {
9371 int idx = 0;
9372 int idList[] = new int[MAX_CONTAINERS];
9373 boolean neverFound = true;
9374 for (String name : list) {
9375 // Ignore null entries
9376 if (name == null) {
9377 continue;
9378 }
9379 int sidx = name.indexOf(prefix);
9380 if (sidx == -1) {
9381 // Not a temp file. just ignore
9382 continue;
9383 }
9384 String subStr = name.substring(sidx + prefix.length());
9385 idList[idx] = -1;
9386 if (subStr != null) {
9387 try {
9388 int cid = Integer.parseInt(subStr);
9389 idList[idx++] = cid;
9390 neverFound = false;
9391 } catch (NumberFormatException e) {
9392 }
9393 }
9394 }
9395 if (!neverFound) {
9396 // Sort idList
9397 Arrays.sort(idList);
9398 for (int j = 1; j <= idList.length; j++) {
9399 if (idList[j-1] != j) {
9400 tmpIdx = j;
9401 break;
9402 }
9403 }
9404 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009405 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009406 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009407 }
9408
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009409 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009410 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009411 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009412 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9413 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9414 throw new SecurityException("Media status can only be updated by the system");
9415 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009416 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009417 Log.i(TAG, "Updating external media status from " +
9418 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9419 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009420 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9421 mediaStatus+", mMediaMounted=" + mMediaMounted);
9422 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009423 if (reportStatus) {
9424 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9425 }
9426 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009427 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009428 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009429 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009430 // Queue up an async operation since the package installation may take a little while.
9431 mHandler.post(new Runnable() {
9432 public void run() {
9433 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009434 try {
9435 updateExternalMediaStatusInner(mediaStatus);
9436 } finally {
9437 if (reportStatus) {
9438 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9439 }
9440 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009441 }
9442 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009443 }
9444
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009445 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009446 // If we are up here that means there are packages to be
9447 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009448 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009449 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009450 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009451 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009452 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009453
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009454 int uidList[] = new int[list.length];
9455 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009456 HashSet<String> removeCids = new HashSet<String>();
9457 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009458 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009459 for (String cid : list) {
9460 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009461 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9462 boolean failed = true;
9463 try {
9464 String pkgName = args.getPackageName();
9465 if (pkgName == null) {
9466 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009467 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9469 PackageSetting ps = mSettings.mPackages.get(pkgName);
9470 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009471 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009472 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9473 " corresponds to pkg : " + pkgName +
9474 " at code path: " + ps.codePathString);
9475 // We do have a valid package installed on sdcard
9476 processCids.put(args, ps.codePathString);
9477 failed = false;
9478 int uid = ps.userId;
9479 if (uid != -1) {
9480 uidList[num++] = uid;
9481 }
9482 }
9483 } finally {
9484 if (failed) {
9485 // Stale container on sdcard. Just delete
9486 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9487 removeCids.add(cid);
9488 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009489 }
9490 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009491 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009492 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009493 int uidArr[] = null;
9494 if (num > 0) {
9495 // Sort uid list
9496 Arrays.sort(uidList, 0, num);
9497 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009498 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009499 uidArr[0] = uidList[0];
9500 int di = 0;
9501 for (int i = 1; i < num; i++) {
9502 if (uidList[i-1] != uidList[i]) {
9503 uidArr[di++] = uidList[i];
9504 }
9505 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009506 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009507 // Process packages with valid entries.
9508 if (mediaStatus) {
9509 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009510 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009511 startCleaningPackages();
9512 } else {
9513 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009514 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009515 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009516 }
9517
9518 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009519 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009520 int size = pkgList.size();
9521 if (size > 0) {
9522 // Send broadcasts here
9523 Bundle extras = new Bundle();
9524 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9525 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009526 if (uidArr != null) {
9527 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9528 }
9529 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9530 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009531 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009532 }
9533 }
9534
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009535 /*
9536 * Look at potentially valid container ids from processCids
9537 * If package information doesn't match the one on record
9538 * or package scanning fails, the cid is added to list of
9539 * removeCids and cleaned up. Since cleaning up containers
9540 * involves destroying them, we do not want any parse
9541 * references to such stale containers. So force gc's
9542 * to avoid unnecessary crashes.
9543 */
9544 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009545 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009546 ArrayList<String> pkgList = new ArrayList<String>();
9547 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009548 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009549 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009550 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009551 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9552 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009553 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009554 try {
9555 // Make sure there are no container errors first.
9556 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9557 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009558 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009559 " when installing from sdcard");
9560 continue;
9561 }
9562 // Check code path here.
9563 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009564 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009565 " does not match one in settings " + codePath);
9566 continue;
9567 }
9568 // Parse package
9569 int parseFlags = PackageParser.PARSE_CHATTY |
Jeff Brown07330792010-03-30 19:57:08 -07009570 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009571 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009572 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009573 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9574 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009575 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009576 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009577 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009578 retCode = PackageManager.INSTALL_SUCCEEDED;
9579 pkgList.add(pkg.packageName);
9580 // Post process args
9581 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9582 }
9583 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009584 Slog.i(TAG, "Failed to install pkg from " +
9585 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009586 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009587 }
9588
9589 } finally {
9590 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9591 // Don't destroy container here. Wait till gc clears things up.
9592 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009593 }
9594 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009595 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009596 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009597 // If the platform SDK has changed since the last time we booted,
9598 // we need to re-grant app permission to catch any new ones that
9599 // appear. This is really a hack, and means that apps can in some
9600 // cases get permissions that the user didn't initially explicitly
9601 // allow... it would be nice to have some better way to handle
9602 // this situation.
9603 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9604 != mSdkVersion;
9605 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9606 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9607 + "; regranting permissions for external storage");
9608 mSettings.mExternalSdkPlatform = mSdkVersion;
9609
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009610 // Make sure group IDs have been assigned, and any permission
9611 // changes in other apps are accounted for
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009612 updatePermissionsLP(null, null, true, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009613 // Persist settings
9614 mSettings.writeLP();
9615 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009616 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009617 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009618 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009619 }
9620 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009621 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009622 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009623 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009624 if (removeCids != null) {
9625 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009626 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009627 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009628 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009629 }
9630
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009631 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009632 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009633 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009634 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009635 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009636 Set<SdInstallArgs> keys = processCids.keySet();
9637 for (SdInstallArgs args : keys) {
9638 String cid = args.cid;
9639 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009641 // Delete package internally
9642 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9643 synchronized (mInstallLock) {
9644 boolean res = deletePackageLI(pkgName, false,
9645 PackageManager.DONT_DELETE_DATA, outInfo);
9646 if (res) {
9647 pkgList.add(pkgName);
9648 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009649 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009650 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009651 }
9652 }
9653 }
9654 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009655 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009656 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9657 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9658 boolean ordered, boolean sticky) throws RemoteException {
9659 // Force gc now that everyone is done cleaning up, to release
9660 // references on assets.
9661 Runtime.getRuntime().gc();
9662 }
9663 });
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009664 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009665 // Just unmount all valid containers.
9666 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009667 synchronized (mInstallLock) {
9668 args.doPostDeleteLI(false);
9669 }
9670 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009671 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009672
9673 public void movePackage(final String packageName,
9674 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009675 mContext.enforceCallingOrSelfPermission(
9676 android.Manifest.permission.MOVE_PACKAGE, null);
9677 int returnCode = PackageManager.MOVE_SUCCEEDED;
9678 int currFlags = 0;
9679 int newFlags = 0;
9680 synchronized (mPackages) {
9681 PackageParser.Package pkg = mPackages.get(packageName);
9682 if (pkg == null) {
9683 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009684 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009685 // Disable moving fwd locked apps and system packages
9686 if (pkg.applicationInfo != null &&
9687 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9688 Slog.w(TAG, "Cannot move system application");
9689 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9690 } else if (pkg.applicationInfo != null &&
9691 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9692 Slog.w(TAG, "Cannot move forward locked app.");
9693 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009694 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009695 // Find install location first
9696 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9697 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9698 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009699 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009700 } else {
9701 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9702 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9703 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9704 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9705 if (newFlags == currFlags) {
9706 Slog.w(TAG, "No move required. Trying to move to same location");
9707 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9708 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009709 }
9710 }
9711 }
9712 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9713 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9714 } else {
9715 Message msg = mHandler.obtainMessage(INIT_COPY);
9716 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9717 pkg.applicationInfo.publicSourceDir);
9718 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9719 packageName);
9720 msg.obj = mp;
9721 mHandler.sendMessage(msg);
9722 }
9723 }
9724 }
9725
9726 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9727 // Queue up an async operation since the package deletion may take a little while.
9728 mHandler.post(new Runnable() {
9729 public void run() {
9730 mHandler.removeCallbacks(this);
9731 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009732 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9733 int uidArr[] = null;
9734 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009735 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009736 PackageParser.Package pkg = mPackages.get(mp.packageName);
9737 if (pkg == null ) {
9738 Slog.w(TAG, " Package " + mp.packageName +
9739 " doesn't exist. Aborting move");
9740 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9741 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9742 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9743 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9744 " Aborting move and returning error");
9745 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9746 } else {
9747 uidArr = new int[] { pkg.applicationInfo.uid };
9748 pkgList = new ArrayList<String>();
9749 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009750 }
9751 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009752 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9753 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009754 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009755 // Update package code and resource paths
9756 synchronized (mInstallLock) {
9757 synchronized (mPackages) {
9758 PackageParser.Package pkg = mPackages.get(mp.packageName);
9759 // Recheck for package again.
9760 if (pkg == null ) {
9761 Slog.w(TAG, " Package " + mp.packageName +
9762 " doesn't exist. Aborting move");
9763 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9764 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9765 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9766 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9767 " Aborting move and returning error");
9768 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9769 } else {
9770 String oldCodePath = pkg.mPath;
9771 String newCodePath = mp.targetArgs.getCodePath();
9772 String newResPath = mp.targetArgs.getResourcePath();
9773 pkg.mPath = newCodePath;
9774 // Move dex files around
9775 if (moveDexFilesLI(pkg)
9776 != PackageManager.INSTALL_SUCCEEDED) {
9777 // Moving of dex files failed. Set
9778 // error code and abort move.
9779 pkg.mPath = pkg.mScanPath;
9780 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9781 } else {
9782 pkg.mScanPath = newCodePath;
9783 pkg.applicationInfo.sourceDir = newCodePath;
9784 pkg.applicationInfo.publicSourceDir = newResPath;
9785 PackageSetting ps = (PackageSetting) pkg.mExtras;
9786 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9787 ps.codePathString = ps.codePath.getPath();
9788 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9789 ps.resourcePathString = ps.resourcePath.getPath();
9790 // Set the application info flag correctly.
9791 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9792 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9793 } else {
9794 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9795 }
9796 ps.setFlags(pkg.applicationInfo.flags);
9797 mAppDirs.remove(oldCodePath);
9798 mAppDirs.put(newCodePath, pkg);
9799 // Persist settings
9800 mSettings.writeLP();
9801 }
9802 }
9803 }
9804 // Send resources available broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009805 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009806 }
9807 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009808 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009809 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009810 // Clean up failed installation
9811 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009812 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009813 }
9814 } else {
9815 // Force a gc to clear things up.
9816 Runtime.getRuntime().gc();
9817 // Delete older code
9818 synchronized (mInstallLock) {
9819 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009820 }
9821 }
9822 IPackageMoveObserver observer = mp.observer;
9823 if (observer != null) {
9824 try {
9825 observer.packageMoved(mp.packageName, returnCode);
9826 } catch (RemoteException e) {
9827 Log.i(TAG, "Observer no longer exists.");
9828 }
9829 }
9830 }
9831 });
9832 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009833
9834 public boolean setInstallLocation(int loc) {
9835 mContext.enforceCallingOrSelfPermission(
9836 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9837 if (getInstallLocation() == loc) {
9838 return true;
9839 }
9840 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9841 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9842 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9843 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9844 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9845 return true;
9846 }
9847 return false;
9848 }
9849
9850 public int getInstallLocation() {
9851 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9852 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009854}
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009855