blob: b9204c7ede6aa4a956401b99dc963d723293d386 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070023import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080024import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080033import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070035import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070036import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.Intent;
38import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070039import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080040import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070041import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.ActivityInfo;
43import android.content.pm.ApplicationInfo;
44import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070045import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.IPackageDataObserver;
47import android.content.pm.IPackageDeleteObserver;
48import android.content.pm.IPackageInstallObserver;
49import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080050import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.IPackageStatsObserver;
52import android.content.pm.InstrumentationInfo;
53import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080054import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.pm.PackageManager;
56import android.content.pm.PackageStats;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.pm.PackageParser;
61import android.content.pm.PermissionInfo;
62import android.content.pm.PermissionGroupInfo;
63import android.content.pm.ProviderInfo;
64import android.content.pm.ResolveInfo;
65import android.content.pm.ServiceInfo;
66import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.Uri;
68import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070069import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080071import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080073import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070074import android.os.Looper;
75import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Parcel;
77import android.os.RemoteException;
78import android.os.Environment;
79import android.os.FileObserver;
80import android.os.FileUtils;
81import android.os.Handler;
82import android.os.ParcelFileDescriptor;
83import android.os.Process;
84import android.os.ServiceManager;
85import android.os.SystemClock;
86import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070087import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080088import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.util.*;
90import android.view.Display;
91import android.view.WindowManager;
92
93import java.io.File;
94import java.io.FileDescriptor;
95import java.io.FileInputStream;
96import java.io.FileNotFoundException;
97import java.io.FileOutputStream;
98import java.io.FileReader;
99import java.io.FilenameFilter;
100import java.io.IOException;
101import java.io.InputStream;
102import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800103import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800104import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.ArrayList;
106import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700107import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.Collections;
109import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800110import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.util.Enumeration;
112import java.util.HashMap;
113import java.util.HashSet;
114import java.util.Iterator;
115import java.util.List;
116import java.util.Map;
117import java.util.Set;
118import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800119import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import java.util.zip.ZipFile;
121import java.util.zip.ZipOutputStream;
122
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700123/**
124 * Keep track of all those .apks everywhere.
125 *
126 * This is very central to the platform's security; please run the unit
127 * tests whenever making modifications here:
128 *
129mmm frameworks/base/tests/AndroidTests
130adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
131adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
132 *
133 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134class PackageManagerService extends IPackageManager.Stub {
135 private static final String TAG = "PackageManager";
136 private static final boolean DEBUG_SETTINGS = false;
137 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800138 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800139 private static final boolean DEBUG_INSTALL = false;
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -0700140 private static final boolean DEBUG_NATIVE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
142 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
143 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400144 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private static final int FIRST_APPLICATION_UID =
146 Process.FIRST_APPLICATION_UID;
147 private static final int MAX_APPLICATION_UIDS = 1000;
148
149 private static final boolean SHOW_INFO = false;
150
151 private static final boolean GET_CERTIFICATES = true;
152
153 private static final int REMOVE_EVENTS =
154 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
155 private static final int ADD_EVENTS =
156 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
157
158 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800159 // Suffix used during package installation when copying/moving
160 // package apks to install directory.
161 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800163 /**
164 * Indicates the state of installation. Used by PackageManager to
165 * figure out incomplete installations. Say a package is being installed
166 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
167 * the package installation is successful or unsuccesful lin which case
168 * the PackageManager will no longer maintain state information associated
169 * with the package. If some exception(like device freeze or battery being
170 * pulled out) occurs during installation of a package, the PackageManager
171 * needs this information to clean up the previously failed installation.
172 */
173 private static final int PKG_INSTALL_INCOMPLETE = 0;
174 private static final int PKG_INSTALL_COMPLETE = 1;
175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final int SCAN_MONITOR = 1<<0;
177 static final int SCAN_NO_DEX = 1<<1;
178 static final int SCAN_FORCE_DEX = 1<<2;
179 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800180 static final int SCAN_NEW_INSTALL = 1<<4;
181 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700183 static final int REMOVE_CHATTY = 1<<16;
184
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800185 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
186 "com.android.defcontainer",
187 "com.android.defcontainer.DefaultContainerService");
188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
190 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700191 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
Dianne Hackborn851a5412009-05-08 12:06:44 -0700193 final int mSdkVersion = Build.VERSION.SDK_INT;
194 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
195 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 final Context mContext;
198 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700199 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 final DisplayMetrics mMetrics;
201 final int mDefParseFlags;
202 final String[] mSeparateProcesses;
203
204 // This is where all application persistent data goes.
205 final File mAppDataDir;
206
207 // This is the object monitoring the framework dir.
208 final FileObserver mFrameworkInstallObserver;
209
210 // This is the object monitoring the system app dir.
211 final FileObserver mSystemInstallObserver;
212
213 // This is the object monitoring mAppInstallDir.
214 final FileObserver mAppInstallObserver;
215
216 // This is the object monitoring mDrmAppPrivateInstallDir.
217 final FileObserver mDrmAppInstallObserver;
218
219 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
220 // LOCK HELD. Can be called with mInstallLock held.
221 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 final File mFrameworkDir;
224 final File mSystemAppDir;
225 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700226 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
228 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
229 // apps.
230 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 // Lock for state used when installing and doing other long running
235 // operations. Methods that must be called with this lock held have
236 // the prefix "LI".
237 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 // These are the directories in the 3rd party applications installed dir
240 // that we have currently loaded packages from. Keys are the application's
241 // installed zip file (absolute codePath), and values are Package.
242 final HashMap<String, PackageParser.Package> mAppDirs =
243 new HashMap<String, PackageParser.Package>();
244
245 // Information for the parser to write more useful error messages.
246 File mScanningPath;
247 int mLastScanError;
248
249 final int[] mOutPermissions = new int[3];
250
251 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 // Keys are String (package name), values are Package. This also serves
254 // as the lock for the global state. Methods that must be called with
255 // this lock held have the prefix "LP".
256 final HashMap<String, PackageParser.Package> mPackages =
257 new HashMap<String, PackageParser.Package>();
258
259 final Settings mSettings;
260 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261
262 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
263 int[] mGlobalGids;
264
265 // These are the built-in uid -> permission mappings that were read from the
266 // etc/permissions.xml file.
267 final SparseArray<HashSet<String>> mSystemPermissions =
268 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 // These are the built-in shared libraries that were read from the
271 // etc/permissions.xml file.
272 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800273
Dianne Hackborn49237342009-08-27 20:08:01 -0700274 // Temporary for building the final shared libraries for an .apk.
275 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800276
Dianne Hackborn49237342009-08-27 20:08:01 -0700277 // These are the features this devices supports that were read from the
278 // etc/permissions.xml file.
279 final HashMap<String, FeatureInfo> mAvailableFeatures =
280 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 // All available activities, for your resolving pleasure.
283 final ActivityIntentResolver mActivities =
284 new ActivityIntentResolver();
285
286 // All available receivers, for your resolving pleasure.
287 final ActivityIntentResolver mReceivers =
288 new ActivityIntentResolver();
289
290 // All available services, for your resolving pleasure.
291 final ServiceIntentResolver mServices = new ServiceIntentResolver();
292
293 // Keys are String (provider class name), values are Provider.
294 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
295 new HashMap<ComponentName, PackageParser.Provider>();
296
297 // Mapping from provider base names (first directory in content URI codePath)
298 // to the provider information.
299 final HashMap<String, PackageParser.Provider> mProviders =
300 new HashMap<String, PackageParser.Provider>();
301
302 // Mapping from instrumentation class names to info about them.
303 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
304 new HashMap<ComponentName, PackageParser.Instrumentation>();
305
306 // Mapping from permission names to info about them.
307 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
308 new HashMap<String, PackageParser.PermissionGroup>();
309
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800310 // Packages whose data we have transfered into another package, thus
311 // should no longer exist.
312 final HashSet<String> mTransferedPackages = new HashSet<String>();
313
Dianne Hackborn854060af2009-07-09 18:14:31 -0700314 // Broadcast actions that are only available to the system.
315 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 boolean mSystemReady;
318 boolean mSafeMode;
319 boolean mHasSystemUidErrors;
320
321 ApplicationInfo mAndroidApplication;
322 final ActivityInfo mResolveActivity = new ActivityInfo();
323 final ResolveInfo mResolveInfo = new ResolveInfo();
324 ComponentName mResolveComponentName;
325 PackageParser.Package mPlatformPackage;
326
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700327 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800328 final HashMap<String, ArrayList<String>> mPendingBroadcasts
329 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800330 // Service Connection to remote media container service to copy
331 // package uri's from external media onto secure containers
332 // or internal storage.
333 private IMediaContainerService mContainerService = null;
334
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700335 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800336 static final int MCS_BOUND = 3;
337 static final int END_COPY = 4;
338 static final int INIT_COPY = 5;
339 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800340 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800341 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800342 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800343 static final int MCS_RECONNECT = 10;
344 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700345 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700346 static final int WRITE_SETTINGS = 13;
347
348 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800349
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700350 // Delay time in millisecs
351 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800352 final private DefaultContainerConnection mDefContainerConn =
353 new DefaultContainerConnection();
354 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800355 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800356 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800357 IMediaContainerService imcs =
358 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800359 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800360 }
361
362 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800363 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800364 }
365 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700366
Christopher Tate1bb69062010-02-19 17:02:12 -0800367 // Recordkeeping of restore-after-install operations that are currently in flight
368 // between the Package Manager and the Backup Manager
369 class PostInstallData {
370 public InstallArgs args;
371 public PackageInstalledInfo res;
372
373 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
374 args = _a;
375 res = _r;
376 }
377 };
378 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
379 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
380
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700381 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800382 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800383 final ArrayList<HandlerParams> mPendingInstalls =
384 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800385
386 private boolean connectToService() {
387 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
388 " DefaultContainerService");
389 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700390 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800391 if (mContext.bindService(service, mDefContainerConn,
392 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700393 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800394 mBound = true;
395 return true;
396 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700397 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800398 return false;
399 }
400
401 private void disconnectService() {
402 mContainerService = null;
403 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700404 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800405 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800407 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800408
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700409 PackageHandler(Looper looper) {
410 super(looper);
411 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700412
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700413 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700414 try {
415 doHandleMessage(msg);
416 } finally {
417 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
418 }
419 }
420
421 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700422 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800423 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800424 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800425 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800426 int idx = mPendingInstalls.size();
427 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
428 // If a bind was already initiated we dont really
429 // need to do anything. The pending install
430 // will be processed later on.
431 if (!mBound) {
432 // If this is the only one pending we might
433 // have to bind to the service again.
434 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800435 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800436 params.serviceError();
437 return;
438 } else {
439 // Once we bind to the service, the first
440 // pending request will be processed.
441 mPendingInstalls.add(idx, params);
442 }
443 } else {
444 mPendingInstalls.add(idx, params);
445 // Already bound to the service. Just make
446 // sure we trigger off processing the first request.
447 if (idx == 0) {
448 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800449 }
450 }
451 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800452 }
453 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800454 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800455 if (msg.obj != null) {
456 mContainerService = (IMediaContainerService) msg.obj;
457 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800458 if (mContainerService == null) {
459 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800460 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800461 for (HandlerParams params : mPendingInstalls) {
462 mPendingInstalls.remove(0);
463 // Indicate service bind error
464 params.serviceError();
465 }
466 mPendingInstalls.clear();
467 } else if (mPendingInstalls.size() > 0) {
468 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800469 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 params.startCopy();
471 }
472 } else {
473 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800474 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800475 }
476 break;
477 }
478 case MCS_RECONNECT : {
479 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
480 if (mPendingInstalls.size() > 0) {
481 if (mBound) {
482 disconnectService();
483 }
484 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800485 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800486 for (HandlerParams params : mPendingInstalls) {
487 mPendingInstalls.remove(0);
488 // Indicate service bind error
489 params.serviceError();
490 }
491 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800492 }
493 }
494 break;
495 }
496 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800497 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
498 // Delete pending install
499 if (mPendingInstalls.size() > 0) {
500 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800501 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800502 if (mPendingInstalls.size() == 0) {
503 if (mBound) {
504 disconnectService();
505 }
506 } else {
507 // There are more pending requests in queue.
508 // Just post MCS_BOUND message to trigger processing
509 // of next pending install.
510 mHandler.sendEmptyMessage(MCS_BOUND);
511 }
512 break;
513 }
514 case MCS_GIVE_UP: {
515 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
516 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800517 break;
518 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700519 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800520 String packages[];
521 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700522 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700523 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700524 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700525 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800526 if (mPendingBroadcasts == null) {
527 return;
528 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700529 size = mPendingBroadcasts.size();
530 if (size <= 0) {
531 // Nothing to be done. Just return
532 return;
533 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800534 packages = new String[size];
535 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700536 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800537 Iterator<HashMap.Entry<String, ArrayList<String>>>
538 it = mPendingBroadcasts.entrySet().iterator();
539 int i = 0;
540 while (it.hasNext() && i < size) {
541 HashMap.Entry<String, ArrayList<String>> ent = it.next();
542 packages[i] = ent.getKey();
543 components[i] = ent.getValue();
544 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700545 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800546 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700547 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800548 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700549 mPendingBroadcasts.clear();
550 }
551 // Send broadcasts
552 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800553 sendPackageChangedBroadcast(packages[i], true,
554 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700555 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700556 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700557 break;
558 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800559 case START_CLEANING_PACKAGE: {
560 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700561 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800562 synchronized (mPackages) {
563 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
564 mSettings.mPackagesToBeCleaned.add(packageName);
565 }
566 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700567 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800568 startCleaningPackages();
569 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800570 case POST_INSTALL: {
571 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
572 PostInstallData data = mRunningInstalls.get(msg.arg1);
573 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700574 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800575
576 if (data != null) {
577 InstallArgs args = data.args;
578 PackageInstalledInfo res = data.res;
579
580 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700581 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800582 Bundle extras = new Bundle(1);
583 extras.putInt(Intent.EXTRA_UID, res.uid);
584 final boolean update = res.removedInfo.removedPackage != null;
585 if (update) {
586 extras.putBoolean(Intent.EXTRA_REPLACING, true);
587 }
588 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
589 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700590 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800591 if (update) {
592 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
593 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700594 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800595 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700596 if (res.removedInfo.args != null) {
597 // Remove the replaced package's older resources safely now
598 deleteOld = true;
599 }
600 }
601 // Force a gc to clear up things
602 Runtime.getRuntime().gc();
603 // We delete after a gc for applications on sdcard.
604 if (deleteOld) {
605 synchronized (mInstallLock) {
606 res.removedInfo.args.doPostDeleteLI(true);
607 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800608 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800609 if (args.observer != null) {
610 try {
611 args.observer.packageInstalled(res.name, res.returnCode);
612 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800613 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800614 }
615 }
616 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800617 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800618 }
619 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700620 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700621 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
622 boolean reportStatus = msg.arg1 == 1;
623 boolean doGc = msg.arg2 == 1;
624 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
625 if (doGc) {
626 // Force a gc to clear up stale containers.
627 Runtime.getRuntime().gc();
628 }
629 if (msg.obj != null) {
630 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
631 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
632 // Unload containers
633 unloadAllContainers(args);
634 }
635 if (reportStatus) {
636 try {
637 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
638 PackageHelper.getMountService().finishMediaUpdate();
639 } catch (RemoteException e) {
640 Log.e(TAG, "MountService not running?");
641 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700642 }
643 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700644 case WRITE_SETTINGS: {
645 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
646 synchronized (mPackages) {
647 removeMessages(WRITE_SETTINGS);
648 mSettings.writeLP();
649 }
650 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
651 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700652 }
653 }
654 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800655
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700656 void scheduleWriteSettingsLocked() {
657 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
658 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
659 }
660 }
661
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800662 static boolean installOnSd(int flags) {
663 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700664 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800665 return false;
666 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700667 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
668 return true;
669 }
670 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800671 }
672
673 static boolean isFwdLocked(int flags) {
674 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
675 return true;
676 }
677 return false;
678 }
679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 public static final IPackageManager main(Context context, boolean factoryTest) {
681 PackageManagerService m = new PackageManagerService(context, factoryTest);
682 ServiceManager.addService("package", m);
683 return m;
684 }
685
686 static String[] splitString(String str, char sep) {
687 int count = 1;
688 int i = 0;
689 while ((i=str.indexOf(sep, i)) >= 0) {
690 count++;
691 i++;
692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 String[] res = new String[count];
695 i=0;
696 count = 0;
697 int lastI=0;
698 while ((i=str.indexOf(sep, i)) >= 0) {
699 res[count] = str.substring(lastI, i);
700 count++;
701 i++;
702 lastI = i;
703 }
704 res[count] = str.substring(lastI, str.length());
705 return res;
706 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800709 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800713 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 mContext = context;
717 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700718 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 mMetrics = new DisplayMetrics();
720 mSettings = new Settings();
721 mSettings.addSharedUserLP("android.uid.system",
722 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
723 mSettings.addSharedUserLP("android.uid.phone",
724 MULTIPLE_APPLICATION_UIDS
725 ? RADIO_UID : FIRST_APPLICATION_UID,
726 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400727 mSettings.addSharedUserLP("android.uid.log",
728 MULTIPLE_APPLICATION_UIDS
729 ? LOG_UID : FIRST_APPLICATION_UID,
730 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731
732 String separateProcesses = SystemProperties.get("debug.separate_processes");
733 if (separateProcesses != null && separateProcesses.length() > 0) {
734 if ("*".equals(separateProcesses)) {
735 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
736 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800737 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 } else {
739 mDefParseFlags = 0;
740 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800741 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 + separateProcesses);
743 }
744 } else {
745 mDefParseFlags = 0;
746 mSeparateProcesses = null;
747 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 Installer installer = new Installer();
750 // Little hacky thing to check if installd is here, to determine
751 // whether we are running on the simulator and thus need to take
752 // care of building the /data file structure ourself.
753 // (apparently the sim now has a working installer)
754 if (installer.ping() && Process.supportsProcesses()) {
755 mInstaller = installer;
756 } else {
757 mInstaller = null;
758 }
759
760 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
761 Display d = wm.getDefaultDisplay();
762 d.getMetrics(mMetrics);
763
764 synchronized (mInstallLock) {
765 synchronized (mPackages) {
766 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700767 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 File dataDir = Environment.getDataDirectory();
770 mAppDataDir = new File(dataDir, "data");
771 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
772
773 if (mInstaller == null) {
774 // Make sure these dirs exist, when we are running in
775 // the simulator.
776 // Make a wide-open directory for random misc stuff.
777 File miscDir = new File(dataDir, "misc");
778 miscDir.mkdirs();
779 mAppDataDir.mkdirs();
780 mDrmAppPrivateInstallDir.mkdirs();
781 }
782
783 readPermissions();
784
785 mRestoredSettings = mSettings.readLP();
786 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800787
788 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800790
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800791 // Set flag to monitor and not change apk file paths when
792 // scanning install directories.
793 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700794 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800795 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800796 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700797 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700802 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700805 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 /**
808 * Out of paranoia, ensure that everything in the boot class
809 * path has been dexed.
810 */
811 String bootClassPath = System.getProperty("java.boot.class.path");
812 if (bootClassPath != null) {
813 String[] paths = splitString(bootClassPath, ':');
814 for (int i=0; i<paths.length; i++) {
815 try {
816 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
817 libFiles.add(paths[i]);
818 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700819 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 }
821 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800822 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800824 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 }
826 }
827 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800828 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 /**
832 * Also ensure all external libraries have had dexopt run on them.
833 */
834 if (mSharedLibraries.size() > 0) {
835 Iterator<String> libs = mSharedLibraries.values().iterator();
836 while (libs.hasNext()) {
837 String lib = libs.next();
838 try {
839 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
840 libFiles.add(lib);
841 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700842 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 }
844 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800845 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800847 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
849 }
850 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 // Gross hack for now: we know this file doesn't contain any
853 // code, so don't dexopt it to avoid the resulting log spew.
854 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 /**
857 * And there are a number of commands implemented in Java, which
858 * we currently need to do the dexopt on so that they can be
859 * run from a non-root shell.
860 */
861 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700862 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 for (int i=0; i<frameworkFiles.length; i++) {
864 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
865 String path = libPath.getPath();
866 // Skip the file if we alrady did it.
867 if (libFiles.contains(path)) {
868 continue;
869 }
870 // Skip the file if it is not a type we want to dexopt.
871 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
872 continue;
873 }
874 try {
875 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
876 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700877 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 }
879 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800880 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800882 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 }
884 }
885 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800886
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700887 if (didDexOpt) {
888 // If we had to do a dexopt of one of the previous
889 // things, then something on the system has changed.
890 // Consider this significant, and wipe away all other
891 // existing dexopt files to ensure we don't leave any
892 // dangling around.
893 String[] files = mDalvikCacheDir.list();
894 if (files != null) {
895 for (int i=0; i<files.length; i++) {
896 String fn = files[i];
897 if (fn.startsWith("data@app@")
898 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800899 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700900 (new File(mDalvikCacheDir, fn)).delete();
901 }
902 }
903 }
904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800906
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800907 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 mFrameworkInstallObserver = new AppDirObserver(
909 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
910 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700911 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
912 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800913 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800914
915 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
917 mSystemInstallObserver = new AppDirObserver(
918 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
919 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700920 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
921 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800922
923 if (mInstaller != null) {
924 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
925 mInstaller.moveFiles();
926 }
927
928 // Prune any system packages that no longer exist.
929 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
930 while (psit.hasNext()) {
931 PackageSetting ps = psit.next();
932 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800933 && !mPackages.containsKey(ps.name)
934 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800935 psit.remove();
936 String msg = "System package " + ps.name
937 + " no longer exists; wiping its data";
938 reportSettingsProblem(Log.WARN, msg);
939 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700940 mInstaller.remove(ps.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800941 }
942 }
943 }
944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 mAppInstallDir = new File(dataDir, "app");
946 if (mInstaller == null) {
947 // Make sure these dirs exist, when we are running in
948 // the simulator.
949 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
950 }
951 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800952 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 //clean up list
954 for(int i = 0; i < deletePkgsList.size(); i++) {
955 //clean up here
956 cleanupInstallFailedPackage(deletePkgsList.get(i));
957 }
958 //delete tmp files
959 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800960
961 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 SystemClock.uptimeMillis());
963 mAppInstallObserver = new AppDirObserver(
964 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
965 mAppInstallObserver.startWatching();
966 scanDirLI(mAppInstallDir, 0, scanMode);
967
968 mDrmAppInstallObserver = new AppDirObserver(
969 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
970 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800971 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800973 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800975 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 + ((SystemClock.uptimeMillis()-startTime)/1000f)
977 + " seconds");
978
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700979 // If the platform SDK has changed since the last time we booted,
980 // we need to re-grant app permission to catch any new ones that
981 // appear. This is really a hack, and means that apps can in some
982 // cases get permissions that the user didn't initially explicitly
983 // allow... it would be nice to have some better way to handle
984 // this situation.
985 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
986 != mSdkVersion;
987 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
988 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
989 + "; regranting permissions for internal storage");
990 mSettings.mInternalSdkPlatform = mSdkVersion;
991
Dianne Hackborn92cfa102010-04-28 11:00:44 -0700992 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993
994 mSettings.writeLP();
995
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800996 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 // Now after opening every single application zip, make sure they
1000 // are all flushed. Not really needed, but keeps things nice and
1001 // tidy.
1002 Runtime.getRuntime().gc();
1003 } // synchronized (mPackages)
1004 } // synchronized (mInstallLock)
1005 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 @Override
1008 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1009 throws RemoteException {
1010 try {
1011 return super.onTransact(code, data, reply, flags);
1012 } catch (RuntimeException e) {
1013 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001014 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 }
1016 throw e;
1017 }
1018 }
1019
Dianne Hackborne6620b22010-01-22 14:46:21 -08001020 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001021 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07001023 int retCode = mInstaller.remove(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001025 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001026 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
1028 } else {
1029 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001030 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 File dataDir = new File(pkg.applicationInfo.dataDir);
1032 dataDir.delete();
1033 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001034 if (ps.codePath != null) {
1035 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001036 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001037 }
1038 }
1039 if (ps.resourcePath != null) {
1040 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001041 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001042 }
1043 }
1044 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046
1047 void readPermissions() {
1048 // Read permissions from .../etc/permission directory.
1049 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1050 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 return;
1053 }
1054 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001055 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 return;
1057 }
1058
1059 // Iterate over the files in the directory and scan .xml files
1060 for (File f : libraryDir.listFiles()) {
1061 // We'll read platform.xml last
1062 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1063 continue;
1064 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001067 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 continue;
1069 }
1070 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001071 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 continue;
1073 }
1074
1075 readPermissionsFromXml(f);
1076 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1079 final File permFile = new File(Environment.getRootDirectory(),
1080 "etc/permissions/platform.xml");
1081 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001082
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001083 StringBuilder sb = new StringBuilder(128);
1084 sb.append("Libs:");
1085 Iterator<String> it = mSharedLibraries.keySet().iterator();
1086 while (it.hasNext()) {
1087 sb.append(' ');
1088 String name = it.next();
1089 sb.append(name);
1090 sb.append(':');
1091 sb.append(mSharedLibraries.get(name));
1092 }
1093 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001094
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001095 sb.setLength(0);
1096 sb.append("Features:");
1097 it = mAvailableFeatures.keySet().iterator();
1098 while (it.hasNext()) {
1099 sb.append(' ');
1100 sb.append(it.next());
1101 }
1102 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001104
1105 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 FileReader permReader = null;
1107 try {
1108 permReader = new FileReader(permFile);
1109 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001110 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 return;
1112 }
1113
1114 try {
1115 XmlPullParser parser = Xml.newPullParser();
1116 parser.setInput(permReader);
1117
1118 XmlUtils.beginDocument(parser, "permissions");
1119
1120 while (true) {
1121 XmlUtils.nextElement(parser);
1122 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1123 break;
1124 }
1125
1126 String name = parser.getName();
1127 if ("group".equals(name)) {
1128 String gidStr = parser.getAttributeValue(null, "gid");
1129 if (gidStr != null) {
1130 int gid = Integer.parseInt(gidStr);
1131 mGlobalGids = appendInt(mGlobalGids, gid);
1132 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001133 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 + parser.getPositionDescription());
1135 }
1136
1137 XmlUtils.skipCurrentTag(parser);
1138 continue;
1139 } else if ("permission".equals(name)) {
1140 String perm = parser.getAttributeValue(null, "name");
1141 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001142 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 + parser.getPositionDescription());
1144 XmlUtils.skipCurrentTag(parser);
1145 continue;
1146 }
1147 perm = perm.intern();
1148 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 } else if ("assign-permission".equals(name)) {
1151 String perm = parser.getAttributeValue(null, "name");
1152 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001153 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 + parser.getPositionDescription());
1155 XmlUtils.skipCurrentTag(parser);
1156 continue;
1157 }
1158 String uidStr = parser.getAttributeValue(null, "uid");
1159 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001160 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 + parser.getPositionDescription());
1162 XmlUtils.skipCurrentTag(parser);
1163 continue;
1164 }
1165 int uid = Process.getUidForName(uidStr);
1166 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001167 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 + uidStr + "\" at "
1169 + parser.getPositionDescription());
1170 XmlUtils.skipCurrentTag(parser);
1171 continue;
1172 }
1173 perm = perm.intern();
1174 HashSet<String> perms = mSystemPermissions.get(uid);
1175 if (perms == null) {
1176 perms = new HashSet<String>();
1177 mSystemPermissions.put(uid, perms);
1178 }
1179 perms.add(perm);
1180 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 } else if ("library".equals(name)) {
1183 String lname = parser.getAttributeValue(null, "name");
1184 String lfile = parser.getAttributeValue(null, "file");
1185 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001186 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 + parser.getPositionDescription());
1188 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001189 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 + parser.getPositionDescription());
1191 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001192 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001193 mSharedLibraries.put(lname, lfile);
1194 }
1195 XmlUtils.skipCurrentTag(parser);
1196 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001197
Dianne Hackborn49237342009-08-27 20:08:01 -07001198 } else if ("feature".equals(name)) {
1199 String fname = parser.getAttributeValue(null, "name");
1200 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001201 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001202 + parser.getPositionDescription());
1203 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001204 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001205 FeatureInfo fi = new FeatureInfo();
1206 fi.name = fname;
1207 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
1209 XmlUtils.skipCurrentTag(parser);
1210 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 } else {
1213 XmlUtils.skipCurrentTag(parser);
1214 continue;
1215 }
1216
1217 }
1218 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001219 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001221 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 }
1223 }
1224
1225 void readPermission(XmlPullParser parser, String name)
1226 throws IOException, XmlPullParserException {
1227
1228 name = name.intern();
1229
1230 BasePermission bp = mSettings.mPermissions.get(name);
1231 if (bp == null) {
1232 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1233 mSettings.mPermissions.put(name, bp);
1234 }
1235 int outerDepth = parser.getDepth();
1236 int type;
1237 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1238 && (type != XmlPullParser.END_TAG
1239 || parser.getDepth() > outerDepth)) {
1240 if (type == XmlPullParser.END_TAG
1241 || type == XmlPullParser.TEXT) {
1242 continue;
1243 }
1244
1245 String tagName = parser.getName();
1246 if ("group".equals(tagName)) {
1247 String gidStr = parser.getAttributeValue(null, "gid");
1248 if (gidStr != null) {
1249 int gid = Process.getGidForName(gidStr);
1250 bp.gids = appendInt(bp.gids, gid);
1251 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001252 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 + parser.getPositionDescription());
1254 }
1255 }
1256 XmlUtils.skipCurrentTag(parser);
1257 }
1258 }
1259
1260 static int[] appendInt(int[] cur, int val) {
1261 if (cur == null) {
1262 return new int[] { val };
1263 }
1264 final int N = cur.length;
1265 for (int i=0; i<N; i++) {
1266 if (cur[i] == val) {
1267 return cur;
1268 }
1269 }
1270 int[] ret = new int[N+1];
1271 System.arraycopy(cur, 0, ret, 0, N);
1272 ret[N] = val;
1273 return ret;
1274 }
1275
1276 static int[] appendInts(int[] cur, int[] add) {
1277 if (add == null) return cur;
1278 if (cur == null) return add;
1279 final int N = add.length;
1280 for (int i=0; i<N; i++) {
1281 cur = appendInt(cur, add[i]);
1282 }
1283 return cur;
1284 }
1285
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001286 static int[] removeInt(int[] cur, int val) {
1287 if (cur == null) {
1288 return null;
1289 }
1290 final int N = cur.length;
1291 for (int i=0; i<N; i++) {
1292 if (cur[i] == val) {
1293 int[] ret = new int[N-1];
1294 if (i > 0) {
1295 System.arraycopy(cur, 0, ret, 0, i);
1296 }
1297 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001298 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001299 }
1300 return ret;
1301 }
1302 }
1303 return cur;
1304 }
1305
1306 static int[] removeInts(int[] cur, int[] rem) {
1307 if (rem == null) return cur;
1308 if (cur == null) return cur;
1309 final int N = rem.length;
1310 for (int i=0; i<N; i++) {
1311 cur = removeInt(cur, rem[i]);
1312 }
1313 return cur;
1314 }
1315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001317 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1318 // The package has been uninstalled but has retained data and resources.
1319 return PackageParser.generatePackageInfo(p, null, flags);
1320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 final PackageSetting ps = (PackageSetting)p.mExtras;
1322 if (ps == null) {
1323 return null;
1324 }
1325 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1326 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1327 }
1328
1329 public PackageInfo getPackageInfo(String packageName, int flags) {
1330 synchronized (mPackages) {
1331 PackageParser.Package p = mPackages.get(packageName);
1332 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001333 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 + ": " + p);
1335 if (p != null) {
1336 return generatePackageInfo(p, flags);
1337 }
1338 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1339 return generatePackageInfoFromSettingsLP(packageName, flags);
1340 }
1341 }
1342 return null;
1343 }
1344
Dianne Hackborn47096932010-02-11 15:57:09 -08001345 public String[] currentToCanonicalPackageNames(String[] names) {
1346 String[] out = new String[names.length];
1347 synchronized (mPackages) {
1348 for (int i=names.length-1; i>=0; i--) {
1349 PackageSetting ps = mSettings.mPackages.get(names[i]);
1350 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1351 }
1352 }
1353 return out;
1354 }
1355
1356 public String[] canonicalToCurrentPackageNames(String[] names) {
1357 String[] out = new String[names.length];
1358 synchronized (mPackages) {
1359 for (int i=names.length-1; i>=0; i--) {
1360 String cur = mSettings.mRenamedPackages.get(names[i]);
1361 out[i] = cur != null ? cur : names[i];
1362 }
1363 }
1364 return out;
1365 }
1366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 public int getPackageUid(String packageName) {
1368 synchronized (mPackages) {
1369 PackageParser.Package p = mPackages.get(packageName);
1370 if(p != null) {
1371 return p.applicationInfo.uid;
1372 }
1373 PackageSetting ps = mSettings.mPackages.get(packageName);
1374 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1375 return -1;
1376 }
1377 p = ps.pkg;
1378 return p != null ? p.applicationInfo.uid : -1;
1379 }
1380 }
1381
1382 public int[] getPackageGids(String packageName) {
1383 synchronized (mPackages) {
1384 PackageParser.Package p = mPackages.get(packageName);
1385 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001386 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 + ": " + p);
1388 if (p != null) {
1389 final PackageSetting ps = (PackageSetting)p.mExtras;
1390 final SharedUserSetting suid = ps.sharedUser;
1391 return suid != null ? suid.gids : ps.gids;
1392 }
1393 }
1394 // stupid thing to indicate an error.
1395 return new int[0];
1396 }
1397
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001398 static final PermissionInfo generatePermissionInfo(
1399 BasePermission bp, int flags) {
1400 if (bp.perm != null) {
1401 return PackageParser.generatePermissionInfo(bp.perm, flags);
1402 }
1403 PermissionInfo pi = new PermissionInfo();
1404 pi.name = bp.name;
1405 pi.packageName = bp.sourcePackage;
1406 pi.nonLocalizedLabel = bp.name;
1407 pi.protectionLevel = bp.protectionLevel;
1408 return pi;
1409 }
1410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 public PermissionInfo getPermissionInfo(String name, int flags) {
1412 synchronized (mPackages) {
1413 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001414 if (p != null) {
1415 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417 return null;
1418 }
1419 }
1420
1421 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1422 synchronized (mPackages) {
1423 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1424 for (BasePermission p : mSettings.mPermissions.values()) {
1425 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001426 if (p.perm == null || p.perm.info.group == null) {
1427 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001430 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1432 }
1433 }
1434 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 if (out.size() > 0) {
1437 return out;
1438 }
1439 return mPermissionGroups.containsKey(group) ? out : null;
1440 }
1441 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1444 synchronized (mPackages) {
1445 return PackageParser.generatePermissionGroupInfo(
1446 mPermissionGroups.get(name), flags);
1447 }
1448 }
1449
1450 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1451 synchronized (mPackages) {
1452 final int N = mPermissionGroups.size();
1453 ArrayList<PermissionGroupInfo> out
1454 = new ArrayList<PermissionGroupInfo>(N);
1455 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1456 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1457 }
1458 return out;
1459 }
1460 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1463 PackageSetting ps = mSettings.mPackages.get(packageName);
1464 if(ps != null) {
1465 if(ps.pkg == null) {
1466 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1467 if(pInfo != null) {
1468 return pInfo.applicationInfo;
1469 }
1470 return null;
1471 }
1472 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1473 }
1474 return null;
1475 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1478 PackageSetting ps = mSettings.mPackages.get(packageName);
1479 if(ps != null) {
1480 if(ps.pkg == null) {
1481 ps.pkg = new PackageParser.Package(packageName);
1482 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001483 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1484 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1485 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1486 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
1488 return generatePackageInfo(ps.pkg, flags);
1489 }
1490 return null;
1491 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1494 synchronized (mPackages) {
1495 PackageParser.Package p = mPackages.get(packageName);
1496 if (Config.LOGV) Log.v(
1497 TAG, "getApplicationInfo " + packageName
1498 + ": " + p);
1499 if (p != null) {
1500 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001501 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
1503 if ("android".equals(packageName)||"system".equals(packageName)) {
1504 return mAndroidApplication;
1505 }
1506 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1507 return generateApplicationInfoFromSettingsLP(packageName, flags);
1508 }
1509 }
1510 return null;
1511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001512
1513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1515 mContext.enforceCallingOrSelfPermission(
1516 android.Manifest.permission.CLEAR_APP_CACHE, null);
1517 // Queue up an async operation since clearing cache may take a little while.
1518 mHandler.post(new Runnable() {
1519 public void run() {
1520 mHandler.removeCallbacks(this);
1521 int retCode = -1;
1522 if (mInstaller != null) {
1523 retCode = mInstaller.freeCache(freeStorageSize);
1524 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001525 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 }
1527 } //end if mInstaller
1528 if (observer != null) {
1529 try {
1530 observer.onRemoveCompleted(null, (retCode >= 0));
1531 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001532 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
1534 }
1535 }
1536 });
1537 }
1538
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001539 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001540 mContext.enforceCallingOrSelfPermission(
1541 android.Manifest.permission.CLEAR_APP_CACHE, null);
1542 // Queue up an async operation since clearing cache may take a little while.
1543 mHandler.post(new Runnable() {
1544 public void run() {
1545 mHandler.removeCallbacks(this);
1546 int retCode = -1;
1547 if (mInstaller != null) {
1548 retCode = mInstaller.freeCache(freeStorageSize);
1549 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001550 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001551 }
1552 }
1553 if(pi != null) {
1554 try {
1555 // Callback via pending intent
1556 int code = (retCode >= 0) ? 1 : 0;
1557 pi.sendIntent(null, code, null,
1558 null, null);
1559 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001560 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001561 }
1562 }
1563 }
1564 });
1565 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1568 synchronized (mPackages) {
1569 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001570
1571 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001573 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 }
1575 if (mResolveComponentName.equals(component)) {
1576 return mResolveActivity;
1577 }
1578 }
1579 return null;
1580 }
1581
1582 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1583 synchronized (mPackages) {
1584 PackageParser.Activity a = mReceivers.mActivities.get(component);
1585 if (Config.LOGV) Log.v(
1586 TAG, "getReceiverInfo " + component + ": " + a);
1587 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1588 return PackageParser.generateActivityInfo(a, flags);
1589 }
1590 }
1591 return null;
1592 }
1593
1594 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1595 synchronized (mPackages) {
1596 PackageParser.Service s = mServices.mServices.get(component);
1597 if (Config.LOGV) Log.v(
1598 TAG, "getServiceInfo " + component + ": " + s);
1599 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1600 return PackageParser.generateServiceInfo(s, flags);
1601 }
1602 }
1603 return null;
1604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 public String[] getSystemSharedLibraryNames() {
1607 Set<String> libSet;
1608 synchronized (mPackages) {
1609 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001610 int size = libSet.size();
1611 if (size > 0) {
1612 String[] libs = new String[size];
1613 libSet.toArray(libs);
1614 return libs;
1615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001617 return null;
1618 }
1619
1620 public FeatureInfo[] getSystemAvailableFeatures() {
1621 Collection<FeatureInfo> featSet;
1622 synchronized (mPackages) {
1623 featSet = mAvailableFeatures.values();
1624 int size = featSet.size();
1625 if (size > 0) {
1626 FeatureInfo[] features = new FeatureInfo[size+1];
1627 featSet.toArray(features);
1628 FeatureInfo fi = new FeatureInfo();
1629 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1630 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1631 features[size] = fi;
1632 return features;
1633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
1635 return null;
1636 }
1637
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001638 public boolean hasSystemFeature(String name) {
1639 synchronized (mPackages) {
1640 return mAvailableFeatures.containsKey(name);
1641 }
1642 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 public int checkPermission(String permName, String pkgName) {
1645 synchronized (mPackages) {
1646 PackageParser.Package p = mPackages.get(pkgName);
1647 if (p != null && p.mExtras != null) {
1648 PackageSetting ps = (PackageSetting)p.mExtras;
1649 if (ps.sharedUser != null) {
1650 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1651 return PackageManager.PERMISSION_GRANTED;
1652 }
1653 } else if (ps.grantedPermissions.contains(permName)) {
1654 return PackageManager.PERMISSION_GRANTED;
1655 }
1656 }
1657 }
1658 return PackageManager.PERMISSION_DENIED;
1659 }
1660
1661 public int checkUidPermission(String permName, int uid) {
1662 synchronized (mPackages) {
1663 Object obj = mSettings.getUserIdLP(uid);
1664 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001665 GrantedPermissions gp = (GrantedPermissions)obj;
1666 if (gp.grantedPermissions.contains(permName)) {
1667 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
1669 } else {
1670 HashSet<String> perms = mSystemPermissions.get(uid);
1671 if (perms != null && perms.contains(permName)) {
1672 return PackageManager.PERMISSION_GRANTED;
1673 }
1674 }
1675 }
1676 return PackageManager.PERMISSION_DENIED;
1677 }
1678
1679 private BasePermission findPermissionTreeLP(String permName) {
1680 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1681 if (permName.startsWith(bp.name) &&
1682 permName.length() > bp.name.length() &&
1683 permName.charAt(bp.name.length()) == '.') {
1684 return bp;
1685 }
1686 }
1687 return null;
1688 }
1689
1690 private BasePermission checkPermissionTreeLP(String permName) {
1691 if (permName != null) {
1692 BasePermission bp = findPermissionTreeLP(permName);
1693 if (bp != null) {
1694 if (bp.uid == Binder.getCallingUid()) {
1695 return bp;
1696 }
1697 throw new SecurityException("Calling uid "
1698 + Binder.getCallingUid()
1699 + " is not allowed to add to permission tree "
1700 + bp.name + " owned by uid " + bp.uid);
1701 }
1702 }
1703 throw new SecurityException("No permission tree found for " + permName);
1704 }
1705
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001706 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1707 if (s1 == null) {
1708 return s2 == null;
1709 }
1710 if (s2 == null) {
1711 return false;
1712 }
1713 if (s1.getClass() != s2.getClass()) {
1714 return false;
1715 }
1716 return s1.equals(s2);
1717 }
1718
1719 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1720 if (pi1.icon != pi2.icon) return false;
1721 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1722 if (!compareStrings(pi1.name, pi2.name)) return false;
1723 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1724 // We'll take care of setting this one.
1725 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1726 // These are not currently stored in settings.
1727 //if (!compareStrings(pi1.group, pi2.group)) return false;
1728 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1729 //if (pi1.labelRes != pi2.labelRes) return false;
1730 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1731 return true;
1732 }
1733
1734 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1735 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1736 throw new SecurityException("Label must be specified in permission");
1737 }
1738 BasePermission tree = checkPermissionTreeLP(info.name);
1739 BasePermission bp = mSettings.mPermissions.get(info.name);
1740 boolean added = bp == null;
1741 boolean changed = true;
1742 if (added) {
1743 bp = new BasePermission(info.name, tree.sourcePackage,
1744 BasePermission.TYPE_DYNAMIC);
1745 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1746 throw new SecurityException(
1747 "Not allowed to modify non-dynamic permission "
1748 + info.name);
1749 } else {
1750 if (bp.protectionLevel == info.protectionLevel
1751 && bp.perm.owner.equals(tree.perm.owner)
1752 && bp.uid == tree.uid
1753 && comparePermissionInfos(bp.perm.info, info)) {
1754 changed = false;
1755 }
1756 }
1757 bp.protectionLevel = info.protectionLevel;
1758 bp.perm = new PackageParser.Permission(tree.perm.owner,
1759 new PermissionInfo(info));
1760 bp.perm.info.packageName = tree.perm.info.packageName;
1761 bp.uid = tree.uid;
1762 if (added) {
1763 mSettings.mPermissions.put(info.name, bp);
1764 }
1765 if (changed) {
1766 if (!async) {
1767 mSettings.writeLP();
1768 } else {
1769 scheduleWriteSettingsLocked();
1770 }
1771 }
1772 return added;
1773 }
1774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 public boolean addPermission(PermissionInfo info) {
1776 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001777 return addPermissionLocked(info, false);
1778 }
1779 }
1780
1781 public boolean addPermissionAsync(PermissionInfo info) {
1782 synchronized (mPackages) {
1783 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 }
1785 }
1786
1787 public void removePermission(String name) {
1788 synchronized (mPackages) {
1789 checkPermissionTreeLP(name);
1790 BasePermission bp = mSettings.mPermissions.get(name);
1791 if (bp != null) {
1792 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1793 throw new SecurityException(
1794 "Not allowed to modify non-dynamic permission "
1795 + name);
1796 }
1797 mSettings.mPermissions.remove(name);
1798 mSettings.writeLP();
1799 }
1800 }
1801 }
1802
Dianne Hackborn854060af2009-07-09 18:14:31 -07001803 public boolean isProtectedBroadcast(String actionName) {
1804 synchronized (mPackages) {
1805 return mProtectedBroadcasts.contains(actionName);
1806 }
1807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 public int checkSignatures(String pkg1, String pkg2) {
1810 synchronized (mPackages) {
1811 PackageParser.Package p1 = mPackages.get(pkg1);
1812 PackageParser.Package p2 = mPackages.get(pkg2);
1813 if (p1 == null || p1.mExtras == null
1814 || p2 == null || p2.mExtras == null) {
1815 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1816 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001817 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 }
1819 }
1820
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001821 public int checkUidSignatures(int uid1, int uid2) {
1822 synchronized (mPackages) {
1823 Signature[] s1;
1824 Signature[] s2;
1825 Object obj = mSettings.getUserIdLP(uid1);
1826 if (obj != null) {
1827 if (obj instanceof SharedUserSetting) {
1828 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1829 } else if (obj instanceof PackageSetting) {
1830 s1 = ((PackageSetting)obj).signatures.mSignatures;
1831 } else {
1832 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1833 }
1834 } else {
1835 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1836 }
1837 obj = mSettings.getUserIdLP(uid2);
1838 if (obj != null) {
1839 if (obj instanceof SharedUserSetting) {
1840 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1841 } else if (obj instanceof PackageSetting) {
1842 s2 = ((PackageSetting)obj).signatures.mSignatures;
1843 } else {
1844 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1845 }
1846 } else {
1847 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1848 }
1849 return checkSignaturesLP(s1, s2);
1850 }
1851 }
1852
1853 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1854 if (s1 == null) {
1855 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1857 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1858 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001859 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1861 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001862 HashSet<Signature> set1 = new HashSet<Signature>();
1863 for (Signature sig : s1) {
1864 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001866 HashSet<Signature> set2 = new HashSet<Signature>();
1867 for (Signature sig : s2) {
1868 set2.add(sig);
1869 }
1870 // Make sure s2 contains all signatures in s1.
1871 if (set1.equals(set2)) {
1872 return PackageManager.SIGNATURE_MATCH;
1873 }
1874 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 }
1876
1877 public String[] getPackagesForUid(int uid) {
1878 synchronized (mPackages) {
1879 Object obj = mSettings.getUserIdLP(uid);
1880 if (obj instanceof SharedUserSetting) {
1881 SharedUserSetting sus = (SharedUserSetting)obj;
1882 final int N = sus.packages.size();
1883 String[] res = new String[N];
1884 Iterator<PackageSetting> it = sus.packages.iterator();
1885 int i=0;
1886 while (it.hasNext()) {
1887 res[i++] = it.next().name;
1888 }
1889 return res;
1890 } else if (obj instanceof PackageSetting) {
1891 PackageSetting ps = (PackageSetting)obj;
1892 return new String[] { ps.name };
1893 }
1894 }
1895 return null;
1896 }
1897
1898 public String getNameForUid(int uid) {
1899 synchronized (mPackages) {
1900 Object obj = mSettings.getUserIdLP(uid);
1901 if (obj instanceof SharedUserSetting) {
1902 SharedUserSetting sus = (SharedUserSetting)obj;
1903 return sus.name + ":" + sus.userId;
1904 } else if (obj instanceof PackageSetting) {
1905 PackageSetting ps = (PackageSetting)obj;
1906 return ps.name;
1907 }
1908 }
1909 return null;
1910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 public int getUidForSharedUser(String sharedUserName) {
1913 if(sharedUserName == null) {
1914 return -1;
1915 }
1916 synchronized (mPackages) {
1917 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1918 if(suid == null) {
1919 return -1;
1920 }
1921 return suid.userId;
1922 }
1923 }
1924
1925 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1926 int flags) {
1927 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001928 return chooseBestActivity(intent, resolvedType, flags, query);
1929 }
1930
Mihai Predaeae850c2009-05-13 10:13:48 +02001931 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1932 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 if (query != null) {
1934 final int N = query.size();
1935 if (N == 1) {
1936 return query.get(0);
1937 } else if (N > 1) {
1938 // If there is more than one activity with the same priority,
1939 // then let the user decide between them.
1940 ResolveInfo r0 = query.get(0);
1941 ResolveInfo r1 = query.get(1);
1942 if (false) {
1943 System.out.println(r0.activityInfo.name +
1944 "=" + r0.priority + " vs " +
1945 r1.activityInfo.name +
1946 "=" + r1.priority);
1947 }
1948 // If the first activity has a higher priority, or a different
1949 // default, then it is always desireable to pick it.
1950 if (r0.priority != r1.priority
1951 || r0.preferredOrder != r1.preferredOrder
1952 || r0.isDefault != r1.isDefault) {
1953 return query.get(0);
1954 }
1955 // If we have saved a preference for a preferred activity for
1956 // this Intent, use that.
1957 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1958 flags, query, r0.priority);
1959 if (ri != null) {
1960 return ri;
1961 }
1962 return mResolveInfo;
1963 }
1964 }
1965 return null;
1966 }
1967
1968 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1969 int flags, List<ResolveInfo> query, int priority) {
1970 synchronized (mPackages) {
1971 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1972 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001973 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1975 if (prefs != null && prefs.size() > 0) {
1976 // First figure out how good the original match set is.
1977 // We will only allow preferred activities that came
1978 // from the same match quality.
1979 int match = 0;
1980 final int N = query.size();
1981 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1982 for (int j=0; j<N; j++) {
1983 ResolveInfo ri = query.get(j);
1984 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1985 + ": 0x" + Integer.toHexString(match));
1986 if (ri.match > match) match = ri.match;
1987 }
1988 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1989 + Integer.toHexString(match));
1990 match &= IntentFilter.MATCH_CATEGORY_MASK;
1991 final int M = prefs.size();
1992 for (int i=0; i<M; i++) {
1993 PreferredActivity pa = prefs.get(i);
1994 if (pa.mMatch != match) {
1995 continue;
1996 }
1997 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1998 if (DEBUG_PREFERRED) {
1999 Log.v(TAG, "Got preferred activity:");
2000 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
2001 }
2002 if (ai != null) {
2003 for (int j=0; j<N; j++) {
2004 ResolveInfo ri = query.get(j);
2005 if (!ri.activityInfo.applicationInfo.packageName
2006 .equals(ai.applicationInfo.packageName)) {
2007 continue;
2008 }
2009 if (!ri.activityInfo.name.equals(ai.name)) {
2010 continue;
2011 }
2012
2013 // Okay we found a previously set preferred app.
2014 // If the result set is different from when this
2015 // was created, we need to clear it and re-ask the
2016 // user their preference.
2017 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002018 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 + intent + " type " + resolvedType);
2020 mSettings.mPreferredActivities.removeFilter(pa);
2021 return null;
2022 }
2023
2024 // Yay!
2025 return ri;
2026 }
2027 }
2028 }
2029 }
2030 }
2031 return null;
2032 }
2033
2034 public List<ResolveInfo> queryIntentActivities(Intent intent,
2035 String resolvedType, int flags) {
2036 ComponentName comp = intent.getComponent();
2037 if (comp != null) {
2038 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2039 ActivityInfo ai = getActivityInfo(comp, flags);
2040 if (ai != null) {
2041 ResolveInfo ri = new ResolveInfo();
2042 ri.activityInfo = ai;
2043 list.add(ri);
2044 }
2045 return list;
2046 }
2047
2048 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002049 String pkgName = intent.getPackage();
2050 if (pkgName == null) {
2051 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2052 resolvedType, flags);
2053 }
2054 PackageParser.Package pkg = mPackages.get(pkgName);
2055 if (pkg != null) {
2056 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2057 resolvedType, flags, pkg.activities);
2058 }
2059 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061 }
2062
2063 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2064 Intent[] specifics, String[] specificTypes, Intent intent,
2065 String resolvedType, int flags) {
2066 final String resultsAction = intent.getAction();
2067
2068 List<ResolveInfo> results = queryIntentActivities(
2069 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2070 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2071
2072 int specificsPos = 0;
2073 int N;
2074
2075 // todo: note that the algorithm used here is O(N^2). This
2076 // isn't a problem in our current environment, but if we start running
2077 // into situations where we have more than 5 or 10 matches then this
2078 // should probably be changed to something smarter...
2079
2080 // First we go through and resolve each of the specific items
2081 // that were supplied, taking care of removing any corresponding
2082 // duplicate items in the generic resolve list.
2083 if (specifics != null) {
2084 for (int i=0; i<specifics.length; i++) {
2085 final Intent sintent = specifics[i];
2086 if (sintent == null) {
2087 continue;
2088 }
2089
2090 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2091 String action = sintent.getAction();
2092 if (resultsAction != null && resultsAction.equals(action)) {
2093 // If this action was explicitly requested, then don't
2094 // remove things that have it.
2095 action = null;
2096 }
2097 ComponentName comp = sintent.getComponent();
2098 ResolveInfo ri = null;
2099 ActivityInfo ai = null;
2100 if (comp == null) {
2101 ri = resolveIntent(
2102 sintent,
2103 specificTypes != null ? specificTypes[i] : null,
2104 flags);
2105 if (ri == null) {
2106 continue;
2107 }
2108 if (ri == mResolveInfo) {
2109 // ACK! Must do something better with this.
2110 }
2111 ai = ri.activityInfo;
2112 comp = new ComponentName(ai.applicationInfo.packageName,
2113 ai.name);
2114 } else {
2115 ai = getActivityInfo(comp, flags);
2116 if (ai == null) {
2117 continue;
2118 }
2119 }
2120
2121 // Look for any generic query activities that are duplicates
2122 // of this specific one, and remove them from the results.
2123 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2124 N = results.size();
2125 int j;
2126 for (j=specificsPos; j<N; j++) {
2127 ResolveInfo sri = results.get(j);
2128 if ((sri.activityInfo.name.equals(comp.getClassName())
2129 && sri.activityInfo.applicationInfo.packageName.equals(
2130 comp.getPackageName()))
2131 || (action != null && sri.filter.matchAction(action))) {
2132 results.remove(j);
2133 if (Config.LOGV) Log.v(
2134 TAG, "Removing duplicate item from " + j
2135 + " due to specific " + specificsPos);
2136 if (ri == null) {
2137 ri = sri;
2138 }
2139 j--;
2140 N--;
2141 }
2142 }
2143
2144 // Add this specific item to its proper place.
2145 if (ri == null) {
2146 ri = new ResolveInfo();
2147 ri.activityInfo = ai;
2148 }
2149 results.add(specificsPos, ri);
2150 ri.specificIndex = i;
2151 specificsPos++;
2152 }
2153 }
2154
2155 // Now we go through the remaining generic results and remove any
2156 // duplicate actions that are found here.
2157 N = results.size();
2158 for (int i=specificsPos; i<N-1; i++) {
2159 final ResolveInfo rii = results.get(i);
2160 if (rii.filter == null) {
2161 continue;
2162 }
2163
2164 // Iterate over all of the actions of this result's intent
2165 // filter... typically this should be just one.
2166 final Iterator<String> it = rii.filter.actionsIterator();
2167 if (it == null) {
2168 continue;
2169 }
2170 while (it.hasNext()) {
2171 final String action = it.next();
2172 if (resultsAction != null && resultsAction.equals(action)) {
2173 // If this action was explicitly requested, then don't
2174 // remove things that have it.
2175 continue;
2176 }
2177 for (int j=i+1; j<N; j++) {
2178 final ResolveInfo rij = results.get(j);
2179 if (rij.filter != null && rij.filter.hasAction(action)) {
2180 results.remove(j);
2181 if (Config.LOGV) Log.v(
2182 TAG, "Removing duplicate item from " + j
2183 + " due to action " + action + " at " + i);
2184 j--;
2185 N--;
2186 }
2187 }
2188 }
2189
2190 // If the caller didn't request filter information, drop it now
2191 // so we don't have to marshall/unmarshall it.
2192 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2193 rii.filter = null;
2194 }
2195 }
2196
2197 // Filter out the caller activity if so requested.
2198 if (caller != null) {
2199 N = results.size();
2200 for (int i=0; i<N; i++) {
2201 ActivityInfo ainfo = results.get(i).activityInfo;
2202 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2203 && caller.getClassName().equals(ainfo.name)) {
2204 results.remove(i);
2205 break;
2206 }
2207 }
2208 }
2209
2210 // If the caller didn't request filter information,
2211 // drop them now so we don't have to
2212 // marshall/unmarshall it.
2213 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2214 N = results.size();
2215 for (int i=0; i<N; i++) {
2216 results.get(i).filter = null;
2217 }
2218 }
2219
2220 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2221 return results;
2222 }
2223
2224 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2225 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002226 ComponentName comp = intent.getComponent();
2227 if (comp != null) {
2228 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2229 ActivityInfo ai = getReceiverInfo(comp, flags);
2230 if (ai != null) {
2231 ResolveInfo ri = new ResolveInfo();
2232 ri.activityInfo = ai;
2233 list.add(ri);
2234 }
2235 return list;
2236 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002239 String pkgName = intent.getPackage();
2240 if (pkgName == null) {
2241 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2242 resolvedType, flags);
2243 }
2244 PackageParser.Package pkg = mPackages.get(pkgName);
2245 if (pkg != null) {
2246 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2247 resolvedType, flags, pkg.receivers);
2248 }
2249 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
2251 }
2252
2253 public ResolveInfo resolveService(Intent intent, String resolvedType,
2254 int flags) {
2255 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2256 flags);
2257 if (query != null) {
2258 if (query.size() >= 1) {
2259 // If there is more than one service with the same priority,
2260 // just arbitrarily pick the first one.
2261 return query.get(0);
2262 }
2263 }
2264 return null;
2265 }
2266
2267 public List<ResolveInfo> queryIntentServices(Intent intent,
2268 String resolvedType, int flags) {
2269 ComponentName comp = intent.getComponent();
2270 if (comp != null) {
2271 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2272 ServiceInfo si = getServiceInfo(comp, flags);
2273 if (si != null) {
2274 ResolveInfo ri = new ResolveInfo();
2275 ri.serviceInfo = si;
2276 list.add(ri);
2277 }
2278 return list;
2279 }
2280
2281 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002282 String pkgName = intent.getPackage();
2283 if (pkgName == null) {
2284 return (List<ResolveInfo>)mServices.queryIntent(intent,
2285 resolvedType, flags);
2286 }
2287 PackageParser.Package pkg = mPackages.get(pkgName);
2288 if (pkg != null) {
2289 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2290 resolvedType, flags, pkg.services);
2291 }
2292 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 }
2294 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 public List<PackageInfo> getInstalledPackages(int flags) {
2297 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2298
2299 synchronized (mPackages) {
2300 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2301 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2302 while (i.hasNext()) {
2303 final PackageSetting ps = i.next();
2304 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2305 if(psPkg != null) {
2306 finalList.add(psPkg);
2307 }
2308 }
2309 }
2310 else {
2311 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2312 while (i.hasNext()) {
2313 final PackageParser.Package p = i.next();
2314 if (p.applicationInfo != null) {
2315 PackageInfo pi = generatePackageInfo(p, flags);
2316 if(pi != null) {
2317 finalList.add(pi);
2318 }
2319 }
2320 }
2321 }
2322 }
2323 return finalList;
2324 }
2325
2326 public List<ApplicationInfo> getInstalledApplications(int flags) {
2327 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2328 synchronized(mPackages) {
2329 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2330 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2331 while (i.hasNext()) {
2332 final PackageSetting ps = i.next();
2333 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2334 if(ai != null) {
2335 finalList.add(ai);
2336 }
2337 }
2338 }
2339 else {
2340 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2341 while (i.hasNext()) {
2342 final PackageParser.Package p = i.next();
2343 if (p.applicationInfo != null) {
2344 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2345 if(ai != null) {
2346 finalList.add(ai);
2347 }
2348 }
2349 }
2350 }
2351 }
2352 return finalList;
2353 }
2354
2355 public List<ApplicationInfo> getPersistentApplications(int flags) {
2356 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2357
2358 synchronized (mPackages) {
2359 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2360 while (i.hasNext()) {
2361 PackageParser.Package p = i.next();
2362 if (p.applicationInfo != null
2363 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2364 && (!mSafeMode || (p.applicationInfo.flags
2365 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2366 finalList.add(p.applicationInfo);
2367 }
2368 }
2369 }
2370
2371 return finalList;
2372 }
2373
2374 public ProviderInfo resolveContentProvider(String name, int flags) {
2375 synchronized (mPackages) {
2376 final PackageParser.Provider provider = mProviders.get(name);
2377 return provider != null
2378 && mSettings.isEnabledLP(provider.info, flags)
2379 && (!mSafeMode || (provider.info.applicationInfo.flags
2380 &ApplicationInfo.FLAG_SYSTEM) != 0)
2381 ? PackageParser.generateProviderInfo(provider, flags)
2382 : null;
2383 }
2384 }
2385
Fred Quintana718d8a22009-04-29 17:53:20 -07002386 /**
2387 * @deprecated
2388 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 public void querySyncProviders(List outNames, List outInfo) {
2390 synchronized (mPackages) {
2391 Iterator<Map.Entry<String, PackageParser.Provider>> i
2392 = mProviders.entrySet().iterator();
2393
2394 while (i.hasNext()) {
2395 Map.Entry<String, PackageParser.Provider> entry = i.next();
2396 PackageParser.Provider p = entry.getValue();
2397
2398 if (p.syncable
2399 && (!mSafeMode || (p.info.applicationInfo.flags
2400 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2401 outNames.add(entry.getKey());
2402 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2403 }
2404 }
2405 }
2406 }
2407
2408 public List<ProviderInfo> queryContentProviders(String processName,
2409 int uid, int flags) {
2410 ArrayList<ProviderInfo> finalList = null;
2411
2412 synchronized (mPackages) {
2413 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2414 while (i.hasNext()) {
2415 PackageParser.Provider p = i.next();
2416 if (p.info.authority != null
2417 && (processName == null ||
2418 (p.info.processName.equals(processName)
2419 && p.info.applicationInfo.uid == uid))
2420 && mSettings.isEnabledLP(p.info, flags)
2421 && (!mSafeMode || (p.info.applicationInfo.flags
2422 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2423 if (finalList == null) {
2424 finalList = new ArrayList<ProviderInfo>(3);
2425 }
2426 finalList.add(PackageParser.generateProviderInfo(p,
2427 flags));
2428 }
2429 }
2430 }
2431
2432 if (finalList != null) {
2433 Collections.sort(finalList, mProviderInitOrderSorter);
2434 }
2435
2436 return finalList;
2437 }
2438
2439 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2440 int flags) {
2441 synchronized (mPackages) {
2442 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2443 return PackageParser.generateInstrumentationInfo(i, flags);
2444 }
2445 }
2446
2447 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2448 int flags) {
2449 ArrayList<InstrumentationInfo> finalList =
2450 new ArrayList<InstrumentationInfo>();
2451
2452 synchronized (mPackages) {
2453 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2454 while (i.hasNext()) {
2455 PackageParser.Instrumentation p = i.next();
2456 if (targetPackage == null
2457 || targetPackage.equals(p.info.targetPackage)) {
2458 finalList.add(PackageParser.generateInstrumentationInfo(p,
2459 flags));
2460 }
2461 }
2462 }
2463
2464 return finalList;
2465 }
2466
2467 private void scanDirLI(File dir, int flags, int scanMode) {
2468 Log.d(TAG, "Scanning app dir " + dir);
2469
2470 String[] files = dir.list();
2471
2472 int i;
2473 for (i=0; i<files.length; i++) {
2474 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002475 if (!isPackageFilename(files[i])) {
2476 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002477 continue;
2478 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002479 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002481 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002482 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2483 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002484 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002485 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002486 file.delete();
2487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 }
2489 }
2490
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002491 private static File getSettingsProblemFile() {
2492 File dataDir = Environment.getDataDirectory();
2493 File systemDir = new File(dataDir, "system");
2494 File fname = new File(systemDir, "uiderrors.txt");
2495 return fname;
2496 }
2497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 private static void reportSettingsProblem(int priority, String msg) {
2499 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002500 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 FileOutputStream out = new FileOutputStream(fname, true);
2502 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002503 SimpleDateFormat formatter = new SimpleDateFormat();
2504 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2505 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 pw.close();
2507 FileUtils.setPermissions(
2508 fname.toString(),
2509 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2510 -1, -1);
2511 } catch (java.io.IOException e) {
2512 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002513 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 }
2515
2516 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2517 PackageParser.Package pkg, File srcFile, int parseFlags) {
2518 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002519 if (ps != null
2520 && ps.codePath.equals(srcFile)
2521 && ps.getTimeStamp() == srcFile.lastModified()) {
2522 if (ps.signatures.mSignatures != null
2523 && ps.signatures.mSignatures.length != 0) {
2524 // Optimization: reuse the existing cached certificates
2525 // if the package appears to be unchanged.
2526 pkg.mSignatures = ps.signatures.mSignatures;
2527 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 }
Jeff Browne7600722010-04-07 18:28:23 -07002529
2530 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002531 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002532 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2533 }
2534
2535 if (!pp.collectCertificates(pkg, parseFlags)) {
2536 mLastScanError = pp.getParseError();
2537 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 }
2539 }
2540 return true;
2541 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 /*
2544 * Scan a package and return the newly parsed package.
2545 * Returns null in case of errors and the error code is stored in mLastScanError
2546 */
2547 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002548 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002550 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002552 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002555 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 if (pkg == null) {
2557 mLastScanError = pp.getParseError();
2558 return null;
2559 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002560 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 PackageSetting updatedPkg;
2562 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002563 // Look to see if we already know about this package.
2564 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002565 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002566 // This package has been renamed to its original name. Let's
2567 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002568 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002569 }
2570 // If there was no original package, see one for the real package name.
2571 if (ps == null) {
2572 ps = mSettings.peekPackageLP(pkg.packageName);
2573 }
2574 // Check to see if this package could be hiding/updating a system
2575 // package. Must look for it either under the original or real
2576 // package name depending on our state.
2577 updatedPkg = mSettings.mDisabledSysPackages.get(
2578 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002580 // First check if this is a system package that may involve an update
2581 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2582 if (!ps.codePath.equals(scanFile)) {
2583 // The path has changed from what was last scanned... check the
2584 // version of the new path against what we have stored to determine
2585 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002586 if (pkg.mVersionCode < ps.versionCode) {
2587 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002588 // Ignore entry. Skip it.
2589 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2590 + "ignored: updated version " + ps.versionCode
2591 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002592 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2593 return null;
2594 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002595 // The current app on the system partion is better than
2596 // what we have updated to on the data partition; switch
2597 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002598 // At this point, its safely assumed that package installation for
2599 // apps in system partition will go through. If not there won't be a working
2600 // version of the app
2601 synchronized (mPackages) {
2602 // Just remove the loaded entries from package lists.
2603 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002604 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002605 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002606 + "reverting from " + ps.codePathString
2607 + ": new version " + pkg.mVersionCode
2608 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002609 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2610 args.cleanUpResourcesLI();
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07002611 removeNativeBinariesLI(pkg);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002612 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 }
2615 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002616 if (updatedPkg != null) {
2617 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2618 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2619 }
2620 // Verify certificates against what was last scanned
2621 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002622 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002623 return null;
2624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 // The apk is forward locked (not public) if its code and resources
2626 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002627 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002629 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002630 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002631
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002632 String codePath = null;
2633 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002634 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2635 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002636 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002637 } else {
2638 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002639 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002640 }
2641 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002642 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002643 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002644 codePath = pkg.mScanPath;
2645 // Set application objects path explicitly.
2646 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002648 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 }
2650
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002651 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2652 String destCodePath, String destResPath) {
2653 pkg.mPath = pkg.mScanPath = destCodePath;
2654 pkg.applicationInfo.sourceDir = destCodePath;
2655 pkg.applicationInfo.publicSourceDir = destResPath;
2656 }
2657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 private static String fixProcessName(String defProcessName,
2659 String processName, int uid) {
2660 if (processName == null) {
2661 return defProcessName;
2662 }
2663 return processName;
2664 }
2665
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002666 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002667 PackageParser.Package pkg) {
2668 if (pkgSetting.signatures.mSignatures != null) {
2669 // Already existing package. Make sure signatures match
2670 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2671 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002672 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002673 + " signatures do not match the previously installed version; ignoring!");
2674 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 return false;
2676 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002677 }
2678 // Check for shared user signatures
2679 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2680 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2681 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2682 Slog.e(TAG, "Package " + pkg.packageName
2683 + " has no signatures that match those in shared user "
2684 + pkgSetting.sharedUser.name + "; ignoring!");
2685 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2686 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 }
2689 return true;
2690 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002691
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002692 public boolean performDexOpt(String packageName) {
2693 if (!mNoDexOpt) {
2694 return false;
2695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002696
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002697 PackageParser.Package p;
2698 synchronized (mPackages) {
2699 p = mPackages.get(packageName);
2700 if (p == null || p.mDidDexOpt) {
2701 return false;
2702 }
2703 }
2704 synchronized (mInstallLock) {
2705 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2706 }
2707 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002708
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002709 static final int DEX_OPT_SKIPPED = 0;
2710 static final int DEX_OPT_PERFORMED = 1;
2711 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002712
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002713 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2714 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002715 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002716 String path = pkg.mScanPath;
2717 int ret = 0;
2718 try {
2719 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002720 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002721 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002722 pkg.mDidDexOpt = true;
2723 performed = true;
2724 }
2725 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002726 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002727 ret = -1;
2728 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002729 Slog.w(TAG, "IOException reading apk: " + path, e);
2730 ret = -1;
2731 } catch (dalvik.system.StaleDexCacheError e) {
2732 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2733 ret = -1;
2734 } catch (Exception e) {
2735 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002736 ret = -1;
2737 }
2738 if (ret < 0) {
2739 //error from installer
2740 return DEX_OPT_FAILED;
2741 }
2742 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002743
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002744 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2745 }
2746
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002747 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2748 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002749 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002750 + " to " + newPkg.packageName
2751 + ": old package not in system partition");
2752 return false;
2753 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002754 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002755 + " to " + newPkg.packageName
2756 + ": old package still exists");
2757 return false;
2758 }
2759 return true;
2760 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002761
2762 private File getDataPathForPackage(PackageParser.Package pkg) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002763 return new File(mAppDataDir, pkg.packageName);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002764 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002765
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002766 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2767 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002768 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002769 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2770 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002771 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002772 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002773 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2774 return null;
2775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 mScanningPath = scanFile;
2777 if (pkg == null) {
2778 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2779 return null;
2780 }
2781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2783 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2784 }
2785
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002786 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 synchronized (mPackages) {
2788 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002789 Slog.w(TAG, "*************************************************");
2790 Slog.w(TAG, "Core android package being redefined. Skipping.");
2791 Slog.w(TAG, " file=" + mScanningPath);
2792 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2794 return null;
2795 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 // Set up information for our fall-back user intent resolution
2798 // activity.
2799 mPlatformPackage = pkg;
2800 pkg.mVersionCode = mSdkVersion;
2801 mAndroidApplication = pkg.applicationInfo;
2802 mResolveActivity.applicationInfo = mAndroidApplication;
2803 mResolveActivity.name = ResolverActivity.class.getName();
2804 mResolveActivity.packageName = mAndroidApplication.packageName;
2805 mResolveActivity.processName = mAndroidApplication.processName;
2806 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2807 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2808 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2809 mResolveActivity.exported = true;
2810 mResolveActivity.enabled = true;
2811 mResolveInfo.activityInfo = mResolveActivity;
2812 mResolveInfo.priority = 0;
2813 mResolveInfo.preferredOrder = 0;
2814 mResolveInfo.match = 0;
2815 mResolveComponentName = new ComponentName(
2816 mAndroidApplication.packageName, mResolveActivity.name);
2817 }
2818 }
2819
2820 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002821 TAG, "Scanning package " + pkg.packageName);
2822 if (mPackages.containsKey(pkg.packageName)
2823 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002824 Slog.w(TAG, "*************************************************");
2825 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002827 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2829 return null;
2830 }
2831
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002832 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002833 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2834 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 SharedUserSetting suid = null;
2837 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002838
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002839 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2840 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002841 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002842 pkg.mRealPackage = null;
2843 pkg.mAdoptPermissions = null;
2844 }
2845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 synchronized (mPackages) {
2847 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002848 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2849 if (mTmpSharedLibraries == null ||
2850 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2851 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2852 }
2853 int num = 0;
2854 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2855 for (int i=0; i<N; i++) {
2856 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002858 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002860 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2862 return null;
2863 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002864 mTmpSharedLibraries[num] = file;
2865 num++;
2866 }
2867 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2868 for (int i=0; i<N; i++) {
2869 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2870 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002871 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002872 + " desires unavailable shared library "
2873 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2874 } else {
2875 mTmpSharedLibraries[num] = file;
2876 num++;
2877 }
2878 }
2879 if (num > 0) {
2880 pkg.usesLibraryFiles = new String[num];
2881 System.arraycopy(mTmpSharedLibraries, 0,
2882 pkg.usesLibraryFiles, 0, num);
2883 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002884
Dianne Hackborn49237342009-08-27 20:08:01 -07002885 if (pkg.reqFeatures != null) {
2886 N = pkg.reqFeatures.size();
2887 for (int i=0; i<N; i++) {
2888 FeatureInfo fi = pkg.reqFeatures.get(i);
2889 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2890 // Don't care.
2891 continue;
2892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002893
Dianne Hackborn49237342009-08-27 20:08:01 -07002894 if (fi.name != null) {
2895 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002896 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002897 + " requires unavailable feature "
2898 + fi.name + "; failing!");
2899 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2900 return null;
2901 }
2902 }
2903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 }
2905 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 if (pkg.mSharedUserId != null) {
2908 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2909 pkg.applicationInfo.flags, true);
2910 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002911 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 + " for shared user failed");
2913 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2914 return null;
2915 }
2916 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2917 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2918 + suid.userId + "): packages=" + suid.packages);
2919 }
2920 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002921
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002922 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002923 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002924 Log.w(TAG, "WAITING FOR DEBUGGER");
2925 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002926 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2927 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002928 }
2929 }
2930
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002931 // Check if we are renaming from an original package name.
2932 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002933 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002934 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002935 // This package may need to be renamed to a previously
2936 // installed name. Let's check on that...
2937 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002938 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002939 // This package had originally been installed as the
2940 // original name, and we have already taken care of
2941 // transitioning to the new one. Just update the new
2942 // one to continue using the old name.
2943 realName = pkg.mRealPackage;
2944 if (!pkg.packageName.equals(renamed)) {
2945 // Callers into this function may have already taken
2946 // care of renaming the package; only do it here if
2947 // it is not already done.
2948 pkg.setPackageName(renamed);
2949 }
2950
Dianne Hackbornc1552392010-03-03 16:19:01 -08002951 } else {
2952 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2953 if ((origPackage=mSettings.peekPackageLP(
2954 pkg.mOriginalPackages.get(i))) != null) {
2955 // We do have the package already installed under its
2956 // original name... should we use it?
2957 if (!verifyPackageUpdate(origPackage, pkg)) {
2958 // New package is not compatible with original.
2959 origPackage = null;
2960 continue;
2961 } else if (origPackage.sharedUser != null) {
2962 // Make sure uid is compatible between packages.
2963 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002964 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002965 + " to " + pkg.packageName + ": old uid "
2966 + origPackage.sharedUser.name
2967 + " differs from " + pkg.mSharedUserId);
2968 origPackage = null;
2969 continue;
2970 }
2971 } else {
2972 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2973 + pkg.packageName + " to old name " + origPackage.name);
2974 }
2975 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002976 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002977 }
2978 }
2979 }
2980
2981 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002982 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002983 + " was transferred to another, but its .apk remains");
2984 }
2985
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002986 // Just create the setting, don't add it yet. For already existing packages
2987 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002988 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 destResourceFile, pkg.applicationInfo.flags, true, false);
2990 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002991 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2993 return null;
2994 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002995
2996 if (pkgSetting.origPackage != null) {
2997 // If we are first transitioning from an original package,
2998 // fix up the new package's name now. We need to do this after
2999 // looking up the package under its new name, so getPackageLP
3000 // can take care of fiddling things correctly.
3001 pkg.setPackageName(origPackage.name);
3002
3003 // File a report about this.
3004 String msg = "New package " + pkgSetting.realName
3005 + " renamed to replace old package " + pkgSetting.name;
3006 reportSettingsProblem(Log.WARN, msg);
3007
3008 // Make a note of it.
3009 mTransferedPackages.add(origPackage.name);
3010
3011 // No longer need to retain this.
3012 pkgSetting.origPackage = null;
3013 }
3014
3015 if (realName != null) {
3016 // Make a note of it.
3017 mTransferedPackages.add(pkg.packageName);
3018 }
3019
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003020 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3022 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 pkg.applicationInfo.uid = pkgSetting.userId;
3025 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003026
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003027 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003028 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 return null;
3030 }
3031 // The signature has changed, but this package is in the system
3032 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003033 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 // However... if this package is part of a shared user, but it
3035 // doesn't match the signature of the shared user, let's fail.
3036 // What this means is that you can't change the signatures
3037 // associated with an overall shared user, which doesn't seem all
3038 // that unreasonable.
3039 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003040 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3041 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3042 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3044 return null;
3045 }
3046 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003047 // File a report about this.
3048 String msg = "System package " + pkg.packageName
3049 + " signature changed; retaining data.";
3050 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003052
The Android Open Source Project10592532009-03-18 17:39:46 -07003053 // Verify that this new package doesn't have any content providers
3054 // that conflict with existing packages. Only do this if the
3055 // package isn't already installed, since we don't want to break
3056 // things that are installed.
3057 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3058 int N = pkg.providers.size();
3059 int i;
3060 for (i=0; i<N; i++) {
3061 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003062 if (p.info.authority != null) {
3063 String names[] = p.info.authority.split(";");
3064 for (int j = 0; j < names.length; j++) {
3065 if (mProviders.containsKey(names[j])) {
3066 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003067 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003068 " (in package " + pkg.applicationInfo.packageName +
3069 ") is already used by "
3070 + ((other != null && other.getComponentName() != null)
3071 ? other.getComponentName().getPackageName() : "?"));
3072 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3073 return null;
3074 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003075 }
3076 }
3077 }
3078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 }
3080
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003081 final String pkgName = pkg.packageName;
3082
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003083 if (pkg.mAdoptPermissions != null) {
3084 // This package wants to adopt ownership of permissions from
3085 // another package.
3086 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3087 String origName = pkg.mAdoptPermissions.get(i);
3088 PackageSetting orig = mSettings.peekPackageLP(origName);
3089 if (orig != null) {
3090 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003091 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003092 + origName + " to " + pkg.packageName);
3093 mSettings.transferPermissions(origName, pkg.packageName);
3094 }
3095 }
3096 }
3097 }
3098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 long scanFileTime = scanFile.lastModified();
3100 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3101 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3102 pkg.applicationInfo.processName = fixProcessName(
3103 pkg.applicationInfo.packageName,
3104 pkg.applicationInfo.processName,
3105 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106
3107 File dataPath;
3108 if (mPlatformPackage == pkg) {
3109 // The system package is special.
3110 dataPath = new File (Environment.getDataDirectory(), "system");
3111 pkg.applicationInfo.dataDir = dataPath.getPath();
3112 } else {
3113 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003114 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003115
3116 boolean uidError = false;
3117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 if (dataPath.exists()) {
3119 mOutPermissions[1] = 0;
3120 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3121 if (mOutPermissions[1] == pkg.applicationInfo.uid
3122 || !Process.supportsProcesses()) {
3123 pkg.applicationInfo.dataDir = dataPath.getPath();
3124 } else {
3125 boolean recovered = false;
3126 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3127 // If this is a system app, we can at least delete its
3128 // current data so the application will still work.
3129 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003130 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003131 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 // Old data gone!
3133 String msg = "System package " + pkg.packageName
3134 + " has changed from uid: "
3135 + mOutPermissions[1] + " to "
3136 + pkg.applicationInfo.uid + "; old data erased";
3137 reportSettingsProblem(Log.WARN, msg);
3138 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 // And now re-install the app.
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003141 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 pkg.applicationInfo.uid);
3143 if (ret == -1) {
3144 // Ack should not happen!
3145 msg = "System package " + pkg.packageName
3146 + " could not have data directory re-created after delete.";
3147 reportSettingsProblem(Log.WARN, msg);
3148 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3149 return null;
3150 }
3151 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 if (!recovered) {
3154 mHasSystemUidErrors = true;
3155 }
3156 }
3157 if (!recovered) {
3158 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3159 + pkg.applicationInfo.uid + "/fs_"
3160 + mOutPermissions[1];
3161 String msg = "Package " + pkg.packageName
3162 + " has mismatched uid: "
3163 + mOutPermissions[1] + " on disk, "
3164 + pkg.applicationInfo.uid + " in settings";
3165 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003166 mSettings.mReadMessages.append(msg);
3167 mSettings.mReadMessages.append('\n');
3168 uidError = true;
3169 if (!pkgSetting.uidError) {
3170 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 }
3173 }
3174 }
3175 pkg.applicationInfo.dataDir = dataPath.getPath();
3176 } else {
3177 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3178 Log.v(TAG, "Want this data dir: " + dataPath);
3179 //invoke installer to do the actual installation
3180 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003181 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 pkg.applicationInfo.uid);
3183 if(ret < 0) {
3184 // Error from installer
3185 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3186 return null;
3187 }
3188 } else {
3189 dataPath.mkdirs();
3190 if (dataPath.exists()) {
3191 FileUtils.setPermissions(
3192 dataPath.toString(),
3193 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3194 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3195 }
3196 }
3197 if (dataPath.exists()) {
3198 pkg.applicationInfo.dataDir = dataPath.getPath();
3199 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003200 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 pkg.applicationInfo.dataDir = null;
3202 }
3203 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003204
3205 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 }
3207
3208 // Perform shared library installation and dex validation and
3209 // optimization, if this is not a system app.
3210 if (mInstaller != null) {
3211 String path = scanFile.getPath();
3212 if (scanFileNewer) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003213 // Note: We don't want to unpack the native binaries for
3214 // system applications, unless they have been updated
3215 // (the binaries are already under /system/lib).
3216 //
3217 // In other words, we're going to unpack the binaries
3218 // only for non-system apps and system app upgrades.
3219 //
3220 int flags = pkg.applicationInfo.flags;
3221 if ((flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
3222 (flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3223 Log.i(TAG, path + " changed; unpacking");
3224 int err = cachePackageSharedLibsLI(pkg, scanFile);
3225 if (err != PackageManager.INSTALL_SUCCEEDED) {
3226 mLastScanError = err;
3227 return null;
3228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 }
3230 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003231 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003232
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003233 if ((scanMode&SCAN_NO_DEX) == 0) {
3234 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3236 return null;
3237 }
3238 }
3239 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 if (mFactoryTest && pkg.requestedPermissions.contains(
3242 android.Manifest.permission.FACTORY_TEST)) {
3243 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3244 }
3245
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003246 // Request the ActivityManager to kill the process(only for existing packages)
3247 // so that we do not end up in a confused state while the user is still using the older
3248 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003249 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003250 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003251 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003252 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003255 // We don't expect installation to fail beyond this point,
3256 if ((scanMode&SCAN_MONITOR) != 0) {
3257 mAppDirs.put(pkg.mPath, pkg);
3258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003260 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003262 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003263 // Make sure we don't accidentally delete its data.
3264 mSettings.mPackagesToBeCleaned.remove(pkgName);
3265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 int N = pkg.providers.size();
3267 StringBuilder r = null;
3268 int i;
3269 for (i=0; i<N; i++) {
3270 PackageParser.Provider p = pkg.providers.get(i);
3271 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3272 p.info.processName, pkg.applicationInfo.uid);
3273 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3274 p.info.name), p);
3275 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003276 if (p.info.authority != null) {
3277 String names[] = p.info.authority.split(";");
3278 p.info.authority = null;
3279 for (int j = 0; j < names.length; j++) {
3280 if (j == 1 && p.syncable) {
3281 // We only want the first authority for a provider to possibly be
3282 // syncable, so if we already added this provider using a different
3283 // authority clear the syncable flag. We copy the provider before
3284 // changing it because the mProviders object contains a reference
3285 // to a provider that we don't want to change.
3286 // Only do this for the second authority since the resulting provider
3287 // object can be the same for all future authorities for this provider.
3288 p = new PackageParser.Provider(p);
3289 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003291 if (!mProviders.containsKey(names[j])) {
3292 mProviders.put(names[j], p);
3293 if (p.info.authority == null) {
3294 p.info.authority = names[j];
3295 } else {
3296 p.info.authority = p.info.authority + ";" + names[j];
3297 }
3298 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3299 Log.d(TAG, "Registered content provider: " + names[j] +
3300 ", className = " + p.info.name +
3301 ", isSyncable = " + p.info.isSyncable);
3302 } else {
3303 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003304 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003305 " (in package " + pkg.applicationInfo.packageName +
3306 "): name already used by "
3307 + ((other != null && other.getComponentName() != null)
3308 ? other.getComponentName().getPackageName() : "?"));
3309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 }
3311 }
3312 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3313 if (r == null) {
3314 r = new StringBuilder(256);
3315 } else {
3316 r.append(' ');
3317 }
3318 r.append(p.info.name);
3319 }
3320 }
3321 if (r != null) {
3322 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3323 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 N = pkg.services.size();
3326 r = null;
3327 for (i=0; i<N; i++) {
3328 PackageParser.Service s = pkg.services.get(i);
3329 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3330 s.info.processName, pkg.applicationInfo.uid);
3331 mServices.addService(s);
3332 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3333 if (r == null) {
3334 r = new StringBuilder(256);
3335 } else {
3336 r.append(' ');
3337 }
3338 r.append(s.info.name);
3339 }
3340 }
3341 if (r != null) {
3342 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3343 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 N = pkg.receivers.size();
3346 r = null;
3347 for (i=0; i<N; i++) {
3348 PackageParser.Activity a = pkg.receivers.get(i);
3349 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3350 a.info.processName, pkg.applicationInfo.uid);
3351 mReceivers.addActivity(a, "receiver");
3352 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3353 if (r == null) {
3354 r = new StringBuilder(256);
3355 } else {
3356 r.append(' ');
3357 }
3358 r.append(a.info.name);
3359 }
3360 }
3361 if (r != null) {
3362 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3363 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 N = pkg.activities.size();
3366 r = null;
3367 for (i=0; i<N; i++) {
3368 PackageParser.Activity a = pkg.activities.get(i);
3369 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3370 a.info.processName, pkg.applicationInfo.uid);
3371 mActivities.addActivity(a, "activity");
3372 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3373 if (r == null) {
3374 r = new StringBuilder(256);
3375 } else {
3376 r.append(' ');
3377 }
3378 r.append(a.info.name);
3379 }
3380 }
3381 if (r != null) {
3382 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3383 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 N = pkg.permissionGroups.size();
3386 r = null;
3387 for (i=0; i<N; i++) {
3388 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3389 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3390 if (cur == null) {
3391 mPermissionGroups.put(pg.info.name, pg);
3392 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3393 if (r == null) {
3394 r = new StringBuilder(256);
3395 } else {
3396 r.append(' ');
3397 }
3398 r.append(pg.info.name);
3399 }
3400 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003401 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 + pg.info.packageName + " ignored: original from "
3403 + cur.info.packageName);
3404 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3405 if (r == null) {
3406 r = new StringBuilder(256);
3407 } else {
3408 r.append(' ');
3409 }
3410 r.append("DUP:");
3411 r.append(pg.info.name);
3412 }
3413 }
3414 }
3415 if (r != null) {
3416 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3417 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 N = pkg.permissions.size();
3420 r = null;
3421 for (i=0; i<N; i++) {
3422 PackageParser.Permission p = pkg.permissions.get(i);
3423 HashMap<String, BasePermission> permissionMap =
3424 p.tree ? mSettings.mPermissionTrees
3425 : mSettings.mPermissions;
3426 p.group = mPermissionGroups.get(p.info.group);
3427 if (p.info.group == null || p.group != null) {
3428 BasePermission bp = permissionMap.get(p.info.name);
3429 if (bp == null) {
3430 bp = new BasePermission(p.info.name, p.info.packageName,
3431 BasePermission.TYPE_NORMAL);
3432 permissionMap.put(p.info.name, bp);
3433 }
3434 if (bp.perm == null) {
3435 if (bp.sourcePackage == null
3436 || bp.sourcePackage.equals(p.info.packageName)) {
3437 BasePermission tree = findPermissionTreeLP(p.info.name);
3438 if (tree == null
3439 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003440 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 bp.perm = p;
3442 bp.uid = pkg.applicationInfo.uid;
3443 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3444 if (r == null) {
3445 r = new StringBuilder(256);
3446 } else {
3447 r.append(' ');
3448 }
3449 r.append(p.info.name);
3450 }
3451 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003452 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 + p.info.packageName + " ignored: base tree "
3454 + tree.name + " is from package "
3455 + tree.sourcePackage);
3456 }
3457 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003458 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 + p.info.packageName + " ignored: original from "
3460 + bp.sourcePackage);
3461 }
3462 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3463 if (r == null) {
3464 r = new StringBuilder(256);
3465 } else {
3466 r.append(' ');
3467 }
3468 r.append("DUP:");
3469 r.append(p.info.name);
3470 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003471 if (bp.perm == p) {
3472 bp.protectionLevel = p.info.protectionLevel;
3473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003475 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 + p.info.packageName + " ignored: no group "
3477 + p.group);
3478 }
3479 }
3480 if (r != null) {
3481 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 N = pkg.instrumentation.size();
3485 r = null;
3486 for (i=0; i<N; i++) {
3487 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3488 a.info.packageName = pkg.applicationInfo.packageName;
3489 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3490 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3491 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003492 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3494 if (r == null) {
3495 r = new StringBuilder(256);
3496 } else {
3497 r.append(' ');
3498 }
3499 r.append(a.info.name);
3500 }
3501 }
3502 if (r != null) {
3503 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3504 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003505
Dianne Hackborn854060af2009-07-09 18:14:31 -07003506 if (pkg.protectedBroadcasts != null) {
3507 N = pkg.protectedBroadcasts.size();
3508 for (i=0; i<N; i++) {
3509 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3510 }
3511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 pkgSetting.setTimeStamp(scanFileTime);
3514 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 return pkg;
3517 }
3518
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003519 private void killApplication(String pkgName, int uid) {
3520 // Request the ActivityManager to kill the process(only for existing packages)
3521 // so that we do not end up in a confused state while the user is still using the older
3522 // version of the application while the new one gets installed.
3523 IActivityManager am = ActivityManagerNative.getDefault();
3524 if (am != null) {
3525 try {
3526 am.killApplicationWithUid(pkgName, uid);
3527 } catch (RemoteException e) {
3528 }
3529 }
3530 }
3531
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003532 // The following constants are returned by cachePackageSharedLibsForAbiLI
3533 // to indicate if native shared libraries were found in the package.
3534 // Values are:
3535 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3536 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3537 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3538 // in package (and not installed)
3539 //
3540 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3541 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3542 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003544 // Return the path of the directory that will contain the native binaries
3545 // of a given installed package. This is relative to the data path.
3546 //
3547 private static File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3548 return new File(pkg.applicationInfo.dataDir + "/lib");
3549 }
3550
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003551 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3552 // and automatically copy them to /data/data/<appname>/lib if present.
3553 //
3554 // NOTE: this method may throw an IOException if the library cannot
3555 // be copied to its final destination, e.g. if there isn't enough
3556 // room left on the data partition, or a ZipException if the package
3557 // file is malformed.
3558 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003559 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003560 File scanFile, String cpuAbi) throws IOException, ZipException {
3561 File sharedLibraryDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003562 final String apkLib = "lib/";
3563 final int apkLibLen = apkLib.length();
3564 final int cpuAbiLen = cpuAbi.length();
3565 final String libPrefix = "lib";
3566 final int libPrefixLen = libPrefix.length();
3567 final String libSuffix = ".so";
3568 final int libSuffixLen = libSuffix.length();
3569 boolean hasNativeLibraries = false;
3570 boolean installedNativeLibraries = false;
3571
3572 // the minimum length of a valid native shared library of the form
3573 // lib/<something>/lib<name>.so.
3574 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3575
3576 ZipFile zipFile = new ZipFile(scanFile);
3577 Enumeration<ZipEntry> entries =
3578 (Enumeration<ZipEntry>) zipFile.entries();
3579
3580 while (entries.hasMoreElements()) {
3581 ZipEntry entry = entries.nextElement();
3582 // skip directories
3583 if (entry.isDirectory()) {
3584 continue;
3585 }
3586 String entryName = entry.getName();
3587
3588 // check that the entry looks like lib/<something>/lib<name>.so
3589 // here, but don't check the ABI just yet.
3590 //
3591 // - must be sufficiently long
3592 // - must end with libSuffix, i.e. ".so"
3593 // - must start with apkLib, i.e. "lib/"
3594 if (entryName.length() < minEntryLen ||
3595 !entryName.endsWith(libSuffix) ||
3596 !entryName.startsWith(apkLib) ) {
3597 continue;
3598 }
3599
3600 // file name must start with libPrefix, i.e. "lib"
3601 int lastSlash = entryName.lastIndexOf('/');
3602
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003603 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003604 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3605 continue;
3606 }
3607
3608 hasNativeLibraries = true;
3609
3610 // check the cpuAbi now, between lib/ and /lib<name>.so
3611 //
3612 if (lastSlash != apkLibLen + cpuAbiLen ||
3613 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3614 continue;
3615
3616 // extract the library file name, ensure it doesn't contain
3617 // weird characters. we're guaranteed here that it doesn't contain
3618 // a directory separator though.
3619 String libFileName = entryName.substring(lastSlash+1);
3620 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3621 continue;
3622 }
3623
3624 installedNativeLibraries = true;
3625
3626 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3627 File.separator + libFileName;
3628 File sharedLibraryFile = new File(sharedLibraryFilePath);
3629 if (! sharedLibraryFile.exists() ||
3630 sharedLibraryFile.length() != entry.getSize() ||
3631 sharedLibraryFile.lastModified() != entry.getTime()) {
3632 if (Config.LOGD) {
3633 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003635 if (mInstaller == null) {
3636 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003637 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003638 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003639 sharedLibraryFile);
3640 }
3641 }
3642 if (!hasNativeLibraries)
3643 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3644
3645 if (!installedNativeLibraries)
3646 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3647
3648 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3649 }
3650
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003651 // Find the gdbserver executable program in a package at
3652 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3653 //
3654 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3655 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3656 //
3657 private int cachePackageGdbServerLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003658 File scanFile, String cpuAbi) throws IOException, ZipException {
3659 File installGdbServerDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003660 final String GDBSERVER = "gdbserver";
3661 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3662
3663 ZipFile zipFile = new ZipFile(scanFile);
3664 Enumeration<ZipEntry> entries =
3665 (Enumeration<ZipEntry>) zipFile.entries();
3666
3667 while (entries.hasMoreElements()) {
3668 ZipEntry entry = entries.nextElement();
3669 // skip directories
3670 if (entry.isDirectory()) {
3671 continue;
3672 }
3673 String entryName = entry.getName();
3674
3675 if (!entryName.equals(apkGdbServerPath)) {
3676 continue;
3677 }
3678
3679 String installGdbServerPath = installGdbServerDir.getPath() +
3680 "/" + GDBSERVER;
3681 File installGdbServerFile = new File(installGdbServerPath);
3682 if (! installGdbServerFile.exists() ||
3683 installGdbServerFile.length() != entry.getSize() ||
3684 installGdbServerFile.lastModified() != entry.getTime()) {
3685 if (Config.LOGD) {
3686 Log.d(TAG, "Caching gdbserver " + entry.getName());
3687 }
3688 if (mInstaller == null) {
3689 installGdbServerDir.mkdir();
3690 }
3691 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3692 installGdbServerFile);
3693 }
3694 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3695 }
3696 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3697 }
3698
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003699 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3700 // and copy them to /data/data/<appname>/lib.
3701 //
3702 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3703 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3704 // one if ro.product.cpu.abi2 is defined.
3705 //
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003706 private int cachePackageSharedLibsLI(PackageParser.Package pkg, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003707 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003708 try {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003709 int result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003710
3711 // some architectures are capable of supporting several CPU ABIs
3712 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3713 // this is indicated by the definition of the ro.product.cpu.abi2
3714 // system property.
3715 //
3716 // only scan the package twice in case of ABI mismatch
3717 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003718 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003719 if (cpuAbi2 != null) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003720 result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003722
3723 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003724 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003725 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003727
3728 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3729 cpuAbi = cpuAbi2;
3730 }
3731 }
3732
3733 // for debuggable packages, also extract gdbserver from lib/<abi>
3734 // into /data/data/<appname>/lib too.
3735 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3736 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003737 int result2 = cachePackageGdbServerLI(pkg, scanFile, cpuAbi);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003738 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3739 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003742 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003743 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003744 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003746 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003747 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003749 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 }
3751
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003752 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003754 File binaryDir,
3755 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 InputStream inputStream = zipFile.getInputStream(entry);
3757 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003758 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003760 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 // now need to be left as world readable and owned by the system.
3762 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3763 ! tempFile.setLastModified(entry.getTime()) ||
3764 FileUtils.setPermissions(tempFilePath,
3765 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003766 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003768 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 // Failed to properly write file.
3770 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003771 throw new IOException("Couldn't create cached binary "
3772 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 }
3774 } finally {
3775 inputStream.close();
3776 }
3777 }
3778
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003779 // Remove the native binaries of a given package. This simply
3780 // gets rid of the files in the 'lib' sub-directory.
3781 private void removeNativeBinariesLI(PackageParser.Package pkg) {
3782 File binaryDir = getNativeBinaryDirForPackage(pkg);
3783
3784 if (DEBUG_NATIVE) {
3785 Slog.w(TAG,"Deleting native binaries from: " + binaryDir.getPath());
3786 }
3787
3788 // Just remove any file in the directory. Since the directory
3789 // is owned by the 'system' UID, the application is not supposed
3790 // to have written anything there.
3791 //
3792 if (binaryDir.exists()) {
3793 File[] binaries = binaryDir.listFiles();
3794 if (binaries != null) {
3795 for (int nn=0; nn < binaries.length; nn++) {
3796 if (DEBUG_NATIVE) {
3797 Slog.d(TAG," Deleting " + binaries[nn].getName());
3798 }
3799 if (!binaries[nn].delete()) {
3800 Slog.w(TAG,"Could not delete native binary: " +
3801 binaries[nn].getPath());
3802 }
3803 }
3804 }
3805 // Do not delete 'lib' directory itself, or this will prevent
3806 // installation of future updates.
3807 }
3808 }
3809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3811 if (chatty && Config.LOGD) Log.d(
3812 TAG, "Removing package " + pkg.applicationInfo.packageName );
3813
3814 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 mPackages.remove(pkg.applicationInfo.packageName);
3818 if (pkg.mPath != null) {
3819 mAppDirs.remove(pkg.mPath);
3820 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 PackageSetting ps = (PackageSetting)pkg.mExtras;
3823 if (ps != null && ps.sharedUser != null) {
3824 // XXX don't do this until the data is removed.
3825 if (false) {
3826 ps.sharedUser.packages.remove(ps);
3827 if (ps.sharedUser.packages.size() == 0) {
3828 // Remove.
3829 }
3830 }
3831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 int N = pkg.providers.size();
3834 StringBuilder r = null;
3835 int i;
3836 for (i=0; i<N; i++) {
3837 PackageParser.Provider p = pkg.providers.get(i);
3838 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3839 p.info.name));
3840 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 /* The is another ContentProvider with this authority when
3843 * this app was installed so this authority is null,
3844 * Ignore it as we don't have to unregister the provider.
3845 */
3846 continue;
3847 }
3848 String names[] = p.info.authority.split(";");
3849 for (int j = 0; j < names.length; j++) {
3850 if (mProviders.get(names[j]) == p) {
3851 mProviders.remove(names[j]);
3852 if (chatty && Config.LOGD) Log.d(
3853 TAG, "Unregistered content provider: " + names[j] +
3854 ", className = " + p.info.name +
3855 ", isSyncable = " + p.info.isSyncable);
3856 }
3857 }
3858 if (chatty) {
3859 if (r == null) {
3860 r = new StringBuilder(256);
3861 } else {
3862 r.append(' ');
3863 }
3864 r.append(p.info.name);
3865 }
3866 }
3867 if (r != null) {
3868 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 N = pkg.services.size();
3872 r = null;
3873 for (i=0; i<N; i++) {
3874 PackageParser.Service s = pkg.services.get(i);
3875 mServices.removeService(s);
3876 if (chatty) {
3877 if (r == null) {
3878 r = new StringBuilder(256);
3879 } else {
3880 r.append(' ');
3881 }
3882 r.append(s.info.name);
3883 }
3884 }
3885 if (r != null) {
3886 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3887 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 N = pkg.receivers.size();
3890 r = null;
3891 for (i=0; i<N; i++) {
3892 PackageParser.Activity a = pkg.receivers.get(i);
3893 mReceivers.removeActivity(a, "receiver");
3894 if (chatty) {
3895 if (r == null) {
3896 r = new StringBuilder(256);
3897 } else {
3898 r.append(' ');
3899 }
3900 r.append(a.info.name);
3901 }
3902 }
3903 if (r != null) {
3904 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3905 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 N = pkg.activities.size();
3908 r = null;
3909 for (i=0; i<N; i++) {
3910 PackageParser.Activity a = pkg.activities.get(i);
3911 mActivities.removeActivity(a, "activity");
3912 if (chatty) {
3913 if (r == null) {
3914 r = new StringBuilder(256);
3915 } else {
3916 r.append(' ');
3917 }
3918 r.append(a.info.name);
3919 }
3920 }
3921 if (r != null) {
3922 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 N = pkg.permissions.size();
3926 r = null;
3927 for (i=0; i<N; i++) {
3928 PackageParser.Permission p = pkg.permissions.get(i);
3929 boolean tree = false;
3930 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3931 if (bp == null) {
3932 tree = true;
3933 bp = mSettings.mPermissionTrees.get(p.info.name);
3934 }
3935 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003936 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 if (chatty) {
3938 if (r == null) {
3939 r = new StringBuilder(256);
3940 } else {
3941 r.append(' ');
3942 }
3943 r.append(p.info.name);
3944 }
3945 }
3946 }
3947 if (r != null) {
3948 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3949 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 N = pkg.instrumentation.size();
3952 r = null;
3953 for (i=0; i<N; i++) {
3954 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003955 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 if (chatty) {
3957 if (r == null) {
3958 r = new StringBuilder(256);
3959 } else {
3960 r.append(' ');
3961 }
3962 r.append(a.info.name);
3963 }
3964 }
3965 if (r != null) {
3966 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3967 }
3968 }
3969 }
3970
3971 private static final boolean isPackageFilename(String name) {
3972 return name != null && name.endsWith(".apk");
3973 }
3974
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003975 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3976 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3977 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3978 return true;
3979 }
3980 }
3981 return false;
3982 }
3983
3984 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003985 PackageParser.Package pkgInfo, boolean grantPermissions,
3986 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 // Make sure there are no dangling permission trees.
3988 Iterator<BasePermission> it = mSettings.mPermissionTrees
3989 .values().iterator();
3990 while (it.hasNext()) {
3991 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003992 if (bp.packageSetting == null) {
3993 // We may not yet have parsed the package, so just see if
3994 // we still know about its settings.
3995 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3996 }
3997 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003998 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 + " from package " + bp.sourcePackage);
4000 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004001 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4002 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4003 Slog.i(TAG, "Removing old permission tree: " + bp.name
4004 + " from package " + bp.sourcePackage);
4005 grantPermissions = true;
4006 it.remove();
4007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 }
4009 }
4010
4011 // Make sure all dynamic permissions have been assigned to a package,
4012 // and make sure there are no dangling permissions.
4013 it = mSettings.mPermissions.values().iterator();
4014 while (it.hasNext()) {
4015 BasePermission bp = it.next();
4016 if (bp.type == BasePermission.TYPE_DYNAMIC) {
4017 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4018 + bp.name + " pkg=" + bp.sourcePackage
4019 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004020 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 BasePermission tree = findPermissionTreeLP(bp.name);
4022 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004023 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 bp.perm = new PackageParser.Permission(tree.perm.owner,
4025 new PermissionInfo(bp.pendingInfo));
4026 bp.perm.info.packageName = tree.perm.info.packageName;
4027 bp.perm.info.name = bp.name;
4028 bp.uid = tree.uid;
4029 }
4030 }
4031 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004032 if (bp.packageSetting == null) {
4033 // We may not yet have parsed the package, so just see if
4034 // we still know about its settings.
4035 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4036 }
4037 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004038 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 + " from package " + bp.sourcePackage);
4040 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004041 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4042 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4043 Slog.i(TAG, "Removing old permission: " + bp.name
4044 + " from package " + bp.sourcePackage);
4045 grantPermissions = true;
4046 it.remove();
4047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 }
4049 }
4050
4051 // Now update the permissions for all packages, in particular
4052 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004053 if (grantPermissions) {
4054 for (PackageParser.Package pkg : mPackages.values()) {
4055 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004056 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004057 }
4058 }
4059 }
4060
4061 if (pkgInfo != null) {
4062 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 }
4064 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
4067 final PackageSetting ps = (PackageSetting)pkg.mExtras;
4068 if (ps == null) {
4069 return;
4070 }
4071 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004072 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 if (replace) {
4075 ps.permissionsFixed = false;
4076 if (gp == ps) {
4077 gp.grantedPermissions.clear();
4078 gp.gids = mGlobalGids;
4079 }
4080 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 if (gp.gids == null) {
4083 gp.gids = mGlobalGids;
4084 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 final int N = pkg.requestedPermissions.size();
4087 for (int i=0; i<N; i++) {
4088 String name = pkg.requestedPermissions.get(i);
4089 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 if (false) {
4091 if (gp != ps) {
4092 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004093 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094 }
4095 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004096 if (bp != null && bp.packageSetting != null) {
4097 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004099 boolean allowedSig = false;
4100 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4101 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004103 } else if (bp.packageSetting == null) {
4104 // This permission is invalid; skip it.
4105 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004106 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4107 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4108 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004110 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004112 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4114 // For updated system applications, the signatureOrSystem permission
4115 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004116 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4118 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4119 if(sysPs.grantedPermissions.contains(perm)) {
4120 allowed = true;
4121 } else {
4122 allowed = false;
4123 }
4124 } else {
4125 allowed = true;
4126 }
4127 }
4128 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004129 if (allowed) {
4130 allowedSig = true;
4131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 } else {
4133 allowed = false;
4134 }
4135 if (false) {
4136 if (gp != ps) {
4137 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4138 }
4139 }
4140 if (allowed) {
4141 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4142 && ps.permissionsFixed) {
4143 // If this is an existing, non-system package, then
4144 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004145 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004147 // Except... if this is a permission that was added
4148 // to the platform (note: need to only do this when
4149 // updating the platform).
4150 final int NP = PackageParser.NEW_PERMISSIONS.length;
4151 for (int ip=0; ip<NP; ip++) {
4152 final PackageParser.NewPermissionInfo npi
4153 = PackageParser.NEW_PERMISSIONS[ip];
4154 if (npi.name.equals(perm)
4155 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4156 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004157 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004158 + pkg.packageName);
4159 break;
4160 }
4161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 }
4163 }
4164 if (allowed) {
4165 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004166 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 gp.grantedPermissions.add(perm);
4168 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004169 } else if (!ps.haveGids) {
4170 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 }
4172 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004173 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 + " to package " + pkg.packageName
4175 + " because it was previously installed without");
4176 }
4177 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004178 if (gp.grantedPermissions.remove(perm)) {
4179 changedPermission = true;
4180 gp.gids = removeInts(gp.gids, bp.gids);
4181 Slog.i(TAG, "Un-granting permission " + perm
4182 + " from package " + pkg.packageName
4183 + " (protectionLevel=" + bp.protectionLevel
4184 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4185 + ")");
4186 } else {
4187 Slog.w(TAG, "Not granting permission " + perm
4188 + " to package " + pkg.packageName
4189 + " (protectionLevel=" + bp.protectionLevel
4190 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4191 + ")");
4192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 }
4194 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004195 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 + " in package " + pkg.packageName);
4197 }
4198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004199
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004200 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004201 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4202 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203 // This is the first that we have heard about this package, so the
4204 // permissions we have now selected are fixed until explicitly
4205 // changed.
4206 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004208 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 private final class ActivityIntentResolver
4212 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004213 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004215 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 }
4217
Mihai Preda074edef2009-05-18 17:13:31 +02004218 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004219 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004220 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4222 }
4223
Mihai Predaeae850c2009-05-13 10:13:48 +02004224 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4225 ArrayList<PackageParser.Activity> packageActivities) {
4226 if (packageActivities == null) {
4227 return null;
4228 }
4229 mFlags = flags;
4230 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4231 int N = packageActivities.size();
4232 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4233 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004234
4235 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004236 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004237 intentFilters = packageActivities.get(i).intents;
4238 if (intentFilters != null && intentFilters.size() > 0) {
4239 listCut.add(intentFilters);
4240 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004241 }
4242 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4243 }
4244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004246 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 if (SHOW_INFO || Config.LOGV) Log.v(
4248 TAG, " " + type + " " +
4249 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4250 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4251 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004252 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004253 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4254 if (SHOW_INFO || Config.LOGV) {
4255 Log.v(TAG, " IntentFilter:");
4256 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4257 }
4258 if (!intent.debugCheck()) {
4259 Log.w(TAG, "==> For Activity " + a.info.name);
4260 }
4261 addFilter(intent);
4262 }
4263 }
4264
4265 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004266 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 if (SHOW_INFO || Config.LOGV) Log.v(
4268 TAG, " " + type + " " +
4269 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4270 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4271 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004272 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4274 if (SHOW_INFO || Config.LOGV) {
4275 Log.v(TAG, " IntentFilter:");
4276 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4277 }
4278 removeFilter(intent);
4279 }
4280 }
4281
4282 @Override
4283 protected boolean allowFilterResult(
4284 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4285 ActivityInfo filterAi = filter.activity.info;
4286 for (int i=dest.size()-1; i>=0; i--) {
4287 ActivityInfo destAi = dest.get(i).activityInfo;
4288 if (destAi.name == filterAi.name
4289 && destAi.packageName == filterAi.packageName) {
4290 return false;
4291 }
4292 }
4293 return true;
4294 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004297 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4298 return info.activity.owner.packageName;
4299 }
4300
4301 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4303 int match) {
4304 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4305 return null;
4306 }
4307 final PackageParser.Activity activity = info.activity;
4308 if (mSafeMode && (activity.info.applicationInfo.flags
4309 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4310 return null;
4311 }
4312 final ResolveInfo res = new ResolveInfo();
4313 res.activityInfo = PackageParser.generateActivityInfo(activity,
4314 mFlags);
4315 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4316 res.filter = info;
4317 }
4318 res.priority = info.getPriority();
4319 res.preferredOrder = activity.owner.mPreferredOrder;
4320 //System.out.println("Result: " + res.activityInfo.className +
4321 // " = " + res.priority);
4322 res.match = match;
4323 res.isDefault = info.hasDefault;
4324 res.labelRes = info.labelRes;
4325 res.nonLocalizedLabel = info.nonLocalizedLabel;
4326 res.icon = info.icon;
4327 return res;
4328 }
4329
4330 @Override
4331 protected void sortResults(List<ResolveInfo> results) {
4332 Collections.sort(results, mResolvePrioritySorter);
4333 }
4334
4335 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004336 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004338 out.print(prefix); out.print(
4339 Integer.toHexString(System.identityHashCode(filter.activity)));
4340 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004341 out.print(filter.activity.getComponentShortName());
4342 out.print(" filter ");
4343 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 }
4345
4346// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4347// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4348// final List<ResolveInfo> retList = Lists.newArrayList();
4349// while (i.hasNext()) {
4350// final ResolveInfo resolveInfo = i.next();
4351// if (isEnabledLP(resolveInfo.activityInfo)) {
4352// retList.add(resolveInfo);
4353// }
4354// }
4355// return retList;
4356// }
4357
4358 // Keys are String (activity class name), values are Activity.
4359 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4360 = new HashMap<ComponentName, PackageParser.Activity>();
4361 private int mFlags;
4362 }
4363
4364 private final class ServiceIntentResolver
4365 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004366 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004368 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 }
4370
Mihai Preda074edef2009-05-18 17:13:31 +02004371 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004373 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4375 }
4376
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004377 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4378 ArrayList<PackageParser.Service> packageServices) {
4379 if (packageServices == null) {
4380 return null;
4381 }
4382 mFlags = flags;
4383 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4384 int N = packageServices.size();
4385 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4386 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4387
4388 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4389 for (int i = 0; i < N; ++i) {
4390 intentFilters = packageServices.get(i).intents;
4391 if (intentFilters != null && intentFilters.size() > 0) {
4392 listCut.add(intentFilters);
4393 }
4394 }
4395 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4396 }
4397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004399 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 if (SHOW_INFO || Config.LOGV) Log.v(
4401 TAG, " " + (s.info.nonLocalizedLabel != null
4402 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4403 if (SHOW_INFO || Config.LOGV) Log.v(
4404 TAG, " Class=" + s.info.name);
4405 int NI = s.intents.size();
4406 int j;
4407 for (j=0; j<NI; j++) {
4408 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4409 if (SHOW_INFO || Config.LOGV) {
4410 Log.v(TAG, " IntentFilter:");
4411 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4412 }
4413 if (!intent.debugCheck()) {
4414 Log.w(TAG, "==> For Service " + s.info.name);
4415 }
4416 addFilter(intent);
4417 }
4418 }
4419
4420 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004421 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 if (SHOW_INFO || Config.LOGV) Log.v(
4423 TAG, " " + (s.info.nonLocalizedLabel != null
4424 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4425 if (SHOW_INFO || Config.LOGV) Log.v(
4426 TAG, " Class=" + s.info.name);
4427 int NI = s.intents.size();
4428 int j;
4429 for (j=0; j<NI; j++) {
4430 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4431 if (SHOW_INFO || Config.LOGV) {
4432 Log.v(TAG, " IntentFilter:");
4433 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4434 }
4435 removeFilter(intent);
4436 }
4437 }
4438
4439 @Override
4440 protected boolean allowFilterResult(
4441 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4442 ServiceInfo filterSi = filter.service.info;
4443 for (int i=dest.size()-1; i>=0; i--) {
4444 ServiceInfo destAi = dest.get(i).serviceInfo;
4445 if (destAi.name == filterSi.name
4446 && destAi.packageName == filterSi.packageName) {
4447 return false;
4448 }
4449 }
4450 return true;
4451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004454 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4455 return info.service.owner.packageName;
4456 }
4457
4458 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004459 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4460 int match) {
4461 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4462 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4463 return null;
4464 }
4465 final PackageParser.Service service = info.service;
4466 if (mSafeMode && (service.info.applicationInfo.flags
4467 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4468 return null;
4469 }
4470 final ResolveInfo res = new ResolveInfo();
4471 res.serviceInfo = PackageParser.generateServiceInfo(service,
4472 mFlags);
4473 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4474 res.filter = filter;
4475 }
4476 res.priority = info.getPriority();
4477 res.preferredOrder = service.owner.mPreferredOrder;
4478 //System.out.println("Result: " + res.activityInfo.className +
4479 // " = " + res.priority);
4480 res.match = match;
4481 res.isDefault = info.hasDefault;
4482 res.labelRes = info.labelRes;
4483 res.nonLocalizedLabel = info.nonLocalizedLabel;
4484 res.icon = info.icon;
4485 return res;
4486 }
4487
4488 @Override
4489 protected void sortResults(List<ResolveInfo> results) {
4490 Collections.sort(results, mResolvePrioritySorter);
4491 }
4492
4493 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004494 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004496 out.print(prefix); out.print(
4497 Integer.toHexString(System.identityHashCode(filter.service)));
4498 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004499 out.print(filter.service.getComponentShortName());
4500 out.print(" filter ");
4501 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 }
4503
4504// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4505// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4506// final List<ResolveInfo> retList = Lists.newArrayList();
4507// while (i.hasNext()) {
4508// final ResolveInfo resolveInfo = (ResolveInfo) i;
4509// if (isEnabledLP(resolveInfo.serviceInfo)) {
4510// retList.add(resolveInfo);
4511// }
4512// }
4513// return retList;
4514// }
4515
4516 // Keys are String (activity class name), values are Activity.
4517 private final HashMap<ComponentName, PackageParser.Service> mServices
4518 = new HashMap<ComponentName, PackageParser.Service>();
4519 private int mFlags;
4520 };
4521
4522 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4523 new Comparator<ResolveInfo>() {
4524 public int compare(ResolveInfo r1, ResolveInfo r2) {
4525 int v1 = r1.priority;
4526 int v2 = r2.priority;
4527 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4528 if (v1 != v2) {
4529 return (v1 > v2) ? -1 : 1;
4530 }
4531 v1 = r1.preferredOrder;
4532 v2 = r2.preferredOrder;
4533 if (v1 != v2) {
4534 return (v1 > v2) ? -1 : 1;
4535 }
4536 if (r1.isDefault != r2.isDefault) {
4537 return r1.isDefault ? -1 : 1;
4538 }
4539 v1 = r1.match;
4540 v2 = r2.match;
4541 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4542 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4543 }
4544 };
4545
4546 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4547 new Comparator<ProviderInfo>() {
4548 public int compare(ProviderInfo p1, ProviderInfo p2) {
4549 final int v1 = p1.initOrder;
4550 final int v2 = p2.initOrder;
4551 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4552 }
4553 };
4554
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004555 private static final void sendPackageBroadcast(String action, String pkg,
4556 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004557 IActivityManager am = ActivityManagerNative.getDefault();
4558 if (am != null) {
4559 try {
4560 final Intent intent = new Intent(action,
4561 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4562 if (extras != null) {
4563 intent.putExtras(extras);
4564 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004565 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004566 am.broadcastIntent(null, intent, null, finishedReceiver,
4567 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 } catch (RemoteException ex) {
4569 }
4570 }
4571 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004572
4573 public String nextPackageToClean(String lastPackage) {
4574 synchronized (mPackages) {
4575 if (!mMediaMounted) {
4576 // If the external storage is no longer mounted at this point,
4577 // the caller may not have been able to delete all of this
4578 // packages files and can not delete any more. Bail.
4579 return null;
4580 }
4581 if (lastPackage != null) {
4582 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4583 }
4584 return mSettings.mPackagesToBeCleaned.size() > 0
4585 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4586 }
4587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004589 void schedulePackageCleaning(String packageName) {
4590 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4591 }
4592
4593 void startCleaningPackages() {
4594 synchronized (mPackages) {
4595 if (!mMediaMounted) {
4596 return;
4597 }
4598 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4599 return;
4600 }
4601 }
4602 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4603 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4604 IActivityManager am = ActivityManagerNative.getDefault();
4605 if (am != null) {
4606 try {
4607 am.startService(null, intent, null);
4608 } catch (RemoteException e) {
4609 }
4610 }
4611 }
4612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 private final class AppDirObserver extends FileObserver {
4614 public AppDirObserver(String path, int mask, boolean isrom) {
4615 super(path, mask);
4616 mRootDir = path;
4617 mIsRom = isrom;
4618 }
4619
4620 public void onEvent(int event, String path) {
4621 String removedPackage = null;
4622 int removedUid = -1;
4623 String addedPackage = null;
4624 int addedUid = -1;
4625
4626 synchronized (mInstallLock) {
4627 String fullPathStr = null;
4628 File fullPath = null;
4629 if (path != null) {
4630 fullPath = new File(mRootDir, path);
4631 fullPathStr = fullPath.getPath();
4632 }
4633
4634 if (Config.LOGV) Log.v(
4635 TAG, "File " + fullPathStr + " changed: "
4636 + Integer.toHexString(event));
4637
4638 if (!isPackageFilename(path)) {
4639 if (Config.LOGV) Log.v(
4640 TAG, "Ignoring change of non-package file: " + fullPathStr);
4641 return;
4642 }
4643
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004644 // Ignore packages that are being installed or
4645 // have just been installed.
4646 if (ignoreCodePath(fullPathStr)) {
4647 return;
4648 }
4649 PackageParser.Package p = null;
4650 synchronized (mPackages) {
4651 p = mAppDirs.get(fullPathStr);
4652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004653 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004654 if (p != null) {
4655 removePackageLI(p, true);
4656 removedPackage = p.applicationInfo.packageName;
4657 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004658 }
4659 }
4660
4661 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004662 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004663 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004664 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4665 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004666 PackageParser.PARSE_CHATTY |
4667 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004668 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004669 if (p != null) {
4670 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004671 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004672 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 }
4674 addedPackage = p.applicationInfo.packageName;
4675 addedUid = p.applicationInfo.uid;
4676 }
4677 }
4678 }
4679
4680 synchronized (mPackages) {
4681 mSettings.writeLP();
4682 }
4683 }
4684
4685 if (removedPackage != null) {
4686 Bundle extras = new Bundle(1);
4687 extras.putInt(Intent.EXTRA_UID, removedUid);
4688 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004689 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4690 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691 }
4692 if (addedPackage != null) {
4693 Bundle extras = new Bundle(1);
4694 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004695 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4696 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004697 }
4698 }
4699
4700 private final String mRootDir;
4701 private final boolean mIsRom;
4702 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004704 /* Called when a downloaded package installation has been confirmed by the user */
4705 public void installPackage(
4706 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004707 installPackage(packageURI, observer, flags, null);
4708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004709
Jacek Surazski65e13172009-04-28 15:26:38 +02004710 /* Called when a downloaded package installation has been confirmed by the user */
4711 public void installPackage(
4712 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4713 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004714 mContext.enforceCallingOrSelfPermission(
4715 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004716
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004717 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004718 msg.obj = new InstallParams(packageURI, observer, flags,
4719 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004720 mHandler.sendMessage(msg);
4721 }
4722
Christopher Tate1bb69062010-02-19 17:02:12 -08004723 public void finishPackageInstall(int token) {
4724 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4725 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4726 mHandler.sendMessage(msg);
4727 }
4728
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004729 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004730 // Queue up an async operation since the package installation may take a little while.
4731 mHandler.post(new Runnable() {
4732 public void run() {
4733 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004734 // Result object to be returned
4735 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004736 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004737 res.uid = -1;
4738 res.pkg = null;
4739 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004740 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004741 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004742 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004743 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004744 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004745 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004746 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004747
4748 // A restore should be performed at this point if (a) the install
4749 // succeeded, (b) the operation is not an update, and (c) the new
4750 // package has a backupAgent defined.
4751 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004752 boolean doRestore = (!update
4753 && res.pkg != null
4754 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004755
4756 // Set up the post-install work request bookkeeping. This will be used
4757 // and cleaned up by the post-install event handling regardless of whether
4758 // there's a restore pass performed. Token values are >= 1.
4759 int token;
4760 if (mNextInstallToken < 0) mNextInstallToken = 1;
4761 token = mNextInstallToken++;
4762
4763 PostInstallData data = new PostInstallData(args, res);
4764 mRunningInstalls.put(token, data);
4765 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4766
4767 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4768 // Pass responsibility to the Backup Manager. It will perform a
4769 // restore if appropriate, then pass responsibility back to the
4770 // Package Manager to run the post-install observer callbacks
4771 // and broadcasts.
4772 IBackupManager bm = IBackupManager.Stub.asInterface(
4773 ServiceManager.getService(Context.BACKUP_SERVICE));
4774 if (bm != null) {
4775 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4776 + " to BM for possible restore");
4777 try {
4778 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4779 } catch (RemoteException e) {
4780 // can't happen; the backup manager is local
4781 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004782 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004783 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004784 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004785 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004786 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004787 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004790
4791 if (!doRestore) {
4792 // No restore possible, or the Backup Manager was mysteriously not
4793 // available -- just fire the post-install work request directly.
4794 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4795 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4796 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004798 }
4799 });
4800 }
4801
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004802 abstract class HandlerParams {
4803 final static int MAX_RETRIES = 4;
4804 int retry = 0;
4805 final void startCopy() {
4806 try {
4807 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4808 retry++;
4809 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004810 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004811 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4812 handleServiceError();
4813 return;
4814 } else {
4815 handleStartCopy();
4816 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4817 mHandler.sendEmptyMessage(MCS_UNBIND);
4818 }
4819 } catch (RemoteException e) {
4820 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4821 mHandler.sendEmptyMessage(MCS_RECONNECT);
4822 }
4823 handleReturnCode();
4824 }
4825
4826 final void serviceError() {
4827 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4828 handleServiceError();
4829 handleReturnCode();
4830 }
4831 abstract void handleStartCopy() throws RemoteException;
4832 abstract void handleServiceError();
4833 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004834 }
4835
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004836 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004837 final IPackageInstallObserver observer;
4838 int flags;
4839 final Uri packageURI;
4840 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004841 private InstallArgs mArgs;
4842 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004843 InstallParams(Uri packageURI,
4844 IPackageInstallObserver observer, int flags,
4845 String installerPackageName) {
4846 this.packageURI = packageURI;
4847 this.flags = flags;
4848 this.observer = observer;
4849 this.installerPackageName = installerPackageName;
4850 }
4851
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004852 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4853 String packageName = pkgLite.packageName;
4854 int installLocation = pkgLite.installLocation;
4855 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4856 synchronized (mPackages) {
4857 PackageParser.Package pkg = mPackages.get(packageName);
4858 if (pkg != null) {
4859 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4860 // Check for updated system application.
4861 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4862 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004863 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004864 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4865 }
4866 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4867 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004868 if (onSd) {
4869 // Install flag overrides everything.
4870 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4871 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004872 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004873 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4874 // Application explicitly specified internal.
4875 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4876 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4877 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004878 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004879 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004880 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4881 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4882 }
4883 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004884 }
4885 }
4886 } else {
4887 // Invalid install. Return error code
4888 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4889 }
4890 }
4891 }
4892 // All the special cases have been taken care of.
4893 // Return result based on recommended install location.
4894 if (onSd) {
4895 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4896 }
4897 return pkgLite.recommendedInstallLocation;
4898 }
4899
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004900 /*
4901 * Invoke remote method to get package information and install
4902 * location values. Override install location based on default
4903 * policy if needed and then create install arguments based
4904 * on the install location.
4905 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004906 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004907 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004908 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4909 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004910 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4911 if (onInt && onSd) {
4912 // Check if both bits are set.
4913 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4914 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4915 } else if (fwdLocked && onSd) {
4916 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004917 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004918 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004919 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004920 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004921 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004922 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004923 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4924 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4925 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4926 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4927 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004928 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4929 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4930 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004931 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4932 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004933 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004934 // Override with defaults if needed.
4935 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004936 if (!onSd && !onInt) {
4937 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004938 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4939 // Set the flag to install on external media.
4940 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004941 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004942 } else {
4943 // Make sure the flag for installing on external
4944 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004945 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004946 flags &= ~PackageManager.INSTALL_EXTERNAL;
4947 }
4948 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004949 }
4950 }
4951 // Create the file args now.
4952 mArgs = createInstallArgs(this);
4953 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4954 // Create copy only if we are not in an erroneous state.
4955 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004956 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004957 }
4958 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004959 }
4960
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004961 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004962 void handleReturnCode() {
4963 processPendingInstall(mArgs, mRet);
4964 }
4965
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004966 @Override
4967 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004968 mArgs = createInstallArgs(this);
4969 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004970 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004971 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004972
4973 /*
4974 * Utility class used in movePackage api.
4975 * srcArgs and targetArgs are not set for invalid flags and make
4976 * sure to do null checks when invoking methods on them.
4977 * We probably want to return ErrorPrams for both failed installs
4978 * and moves.
4979 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004980 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004981 final IPackageMoveObserver observer;
4982 final int flags;
4983 final String packageName;
4984 final InstallArgs srcArgs;
4985 final InstallArgs targetArgs;
4986 int mRet;
4987 MoveParams(InstallArgs srcArgs,
4988 IPackageMoveObserver observer,
4989 int flags, String packageName) {
4990 this.srcArgs = srcArgs;
4991 this.observer = observer;
4992 this.flags = flags;
4993 this.packageName = packageName;
4994 if (srcArgs != null) {
4995 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4996 targetArgs = createInstallArgs(packageUri, flags, packageName);
4997 } else {
4998 targetArgs = null;
4999 }
5000 }
5001
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005002 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005003 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5004 // Check for storage space on target medium
5005 if (!targetArgs.checkFreeStorage(mContainerService)) {
5006 Log.w(TAG, "Insufficient storage to install");
5007 return;
5008 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005009 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005010 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005011 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005012 if (DEBUG_SD_INSTALL) {
5013 StringBuilder builder = new StringBuilder();
5014 if (srcArgs != null) {
5015 builder.append("src: ");
5016 builder.append(srcArgs.getCodePath());
5017 }
5018 if (targetArgs != null) {
5019 builder.append(" target : ");
5020 builder.append(targetArgs.getCodePath());
5021 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005022 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005023 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005024 }
5025
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005026 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005027 void handleReturnCode() {
5028 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005029 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
5030 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
5031 currentStatus = PackageManager.MOVE_SUCCEEDED;
5032 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
5033 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
5034 }
5035 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005036 }
5037
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005038 @Override
5039 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005040 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005041 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005042 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005043
5044 private InstallArgs createInstallArgs(InstallParams params) {
5045 if (installOnSd(params.flags)) {
5046 return new SdInstallArgs(params);
5047 } else {
5048 return new FileInstallArgs(params);
5049 }
5050 }
5051
5052 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
5053 if (installOnSd(flags)) {
5054 return new SdInstallArgs(fullCodePath, fullResourcePath);
5055 } else {
5056 return new FileInstallArgs(fullCodePath, fullResourcePath);
5057 }
5058 }
5059
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005060 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
5061 if (installOnSd(flags)) {
5062 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5063 return new SdInstallArgs(packageURI, cid);
5064 } else {
5065 return new FileInstallArgs(packageURI, pkgName);
5066 }
5067 }
5068
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005069 static abstract class InstallArgs {
5070 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005071 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005072 final int flags;
5073 final Uri packageURI;
5074 final String installerPackageName;
5075
5076 InstallArgs(Uri packageURI,
5077 IPackageInstallObserver observer, int flags,
5078 String installerPackageName) {
5079 this.packageURI = packageURI;
5080 this.flags = flags;
5081 this.observer = observer;
5082 this.installerPackageName = installerPackageName;
5083 }
5084
5085 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005086 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005087 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005088 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005089 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005090 abstract String getCodePath();
5091 abstract String getResourcePath();
5092 // Need installer lock especially for dex file removal.
5093 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005094 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005095 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005096 }
5097
5098 class FileInstallArgs extends InstallArgs {
5099 File installDir;
5100 String codeFileName;
5101 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005102 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005103
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005104 FileInstallArgs(InstallParams params) {
5105 super(params.packageURI, params.observer,
5106 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005107 }
5108
5109 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5110 super(null, null, 0, null);
5111 File codeFile = new File(fullCodePath);
5112 installDir = codeFile.getParentFile();
5113 codeFileName = fullCodePath;
5114 resourceFileName = fullResourcePath;
5115 }
5116
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005117 FileInstallArgs(Uri packageURI, String pkgName) {
5118 super(packageURI, null, 0, null);
5119 boolean fwdLocked = isFwdLocked(flags);
5120 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5121 String apkName = getNextCodePath(null, pkgName, ".apk");
5122 codeFileName = new File(installDir, apkName + ".apk").getPath();
5123 resourceFileName = getResourcePathFromCodePath();
5124 }
5125
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005126 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5127 return imcs.checkFreeStorage(false, packageURI);
5128 }
5129
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005130 String getCodePath() {
5131 return codeFileName;
5132 }
5133
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005134 void createCopyFile() {
5135 boolean fwdLocked = isFwdLocked(flags);
5136 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5137 codeFileName = createTempPackageFile(installDir).getPath();
5138 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005139 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005140 }
5141
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005142 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005143 if (temp) {
5144 // Generate temp file name
5145 createCopyFile();
5146 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005147 // Get a ParcelFileDescriptor to write to the output file
5148 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005149 if (!created) {
5150 try {
5151 codeFile.createNewFile();
5152 // Set permissions
5153 if (!setPermissions()) {
5154 // Failed setting permissions.
5155 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5156 }
5157 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005158 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005159 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5160 }
5161 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005162 ParcelFileDescriptor out = null;
5163 try {
5164 out = ParcelFileDescriptor.open(codeFile,
5165 ParcelFileDescriptor.MODE_READ_WRITE);
5166 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005167 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005168 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5169 }
5170 // Copy the resource now
5171 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5172 try {
5173 if (imcs.copyResource(packageURI, out)) {
5174 ret = PackageManager.INSTALL_SUCCEEDED;
5175 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005176 } finally {
5177 try { if (out != null) out.close(); } catch (IOException e) {}
5178 }
5179 return ret;
5180 }
5181
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005182 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005183 if (status != PackageManager.INSTALL_SUCCEEDED) {
5184 cleanUp();
5185 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005186 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005187 }
5188
5189 boolean doRename(int status, final String pkgName, String oldCodePath) {
5190 if (status != PackageManager.INSTALL_SUCCEEDED) {
5191 cleanUp();
5192 return false;
5193 } else {
5194 // Rename based on packageName
5195 File codeFile = new File(getCodePath());
5196 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5197 File desFile = new File(installDir, apkName + ".apk");
5198 if (!codeFile.renameTo(desFile)) {
5199 return false;
5200 }
5201 // Reset paths since the file has been renamed.
5202 codeFileName = desFile.getPath();
5203 resourceFileName = getResourcePathFromCodePath();
5204 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005205 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005206 // Failed setting permissions.
5207 return false;
5208 }
5209 return true;
5210 }
5211 }
5212
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005213 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005214 if (status != PackageManager.INSTALL_SUCCEEDED) {
5215 cleanUp();
5216 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005217 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005218 }
5219
5220 String getResourcePath() {
5221 return resourceFileName;
5222 }
5223
5224 String getResourcePathFromCodePath() {
5225 String codePath = getCodePath();
5226 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5227 String apkNameOnly = getApkName(codePath);
5228 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5229 } else {
5230 return codePath;
5231 }
5232 }
5233
5234 private boolean cleanUp() {
5235 boolean ret = true;
5236 String sourceDir = getCodePath();
5237 String publicSourceDir = getResourcePath();
5238 if (sourceDir != null) {
5239 File sourceFile = new File(sourceDir);
5240 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005241 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005242 ret = false;
5243 }
5244 // Delete application's code and resources
5245 sourceFile.delete();
5246 }
5247 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5248 final File publicSourceFile = new File(publicSourceDir);
5249 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005250 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005251 }
5252 if (publicSourceFile.exists()) {
5253 publicSourceFile.delete();
5254 }
5255 }
5256 return ret;
5257 }
5258
5259 void cleanUpResourcesLI() {
5260 String sourceDir = getCodePath();
5261 if (cleanUp() && mInstaller != null) {
5262 int retCode = mInstaller.rmdex(sourceDir);
5263 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005264 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005265 + " at location "
5266 + sourceDir + ", retcode=" + retCode);
5267 // we don't consider this to be a failure of the core package deletion
5268 }
5269 }
5270 }
5271
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005272 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005273 // TODO Do this in a more elegant way later on. for now just a hack
5274 if (!isFwdLocked(flags)) {
5275 final int filePermissions =
5276 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5277 |FileUtils.S_IROTH;
5278 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5279 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005280 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005281 getCodePath()
5282 + ". The return code was: " + retCode);
5283 // TODO Define new internal error
5284 return false;
5285 }
5286 return true;
5287 }
5288 return true;
5289 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005290
5291 boolean doPostDeleteLI(boolean delete) {
5292 cleanUpResourcesLI();
5293 return true;
5294 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005295 }
5296
5297 class SdInstallArgs extends InstallArgs {
5298 String cid;
5299 String cachePath;
5300 static final String RES_FILE_NAME = "pkg.apk";
5301
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005302 SdInstallArgs(InstallParams params) {
5303 super(params.packageURI, params.observer,
5304 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005305 }
5306
5307 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005308 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005309 // Extract cid from fullCodePath
5310 int eidx = fullCodePath.lastIndexOf("/");
5311 String subStr1 = fullCodePath.substring(0, eidx);
5312 int sidx = subStr1.lastIndexOf("/");
5313 cid = subStr1.substring(sidx+1, eidx);
5314 cachePath = subStr1;
5315 }
5316
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005317 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005318 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5319 this.cid = cid;
5320 }
5321
5322 SdInstallArgs(Uri packageURI, String cid) {
5323 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005324 this.cid = cid;
5325 }
5326
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005327 void createCopyFile() {
5328 cid = getTempContainerId();
5329 }
5330
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005331 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5332 return imcs.checkFreeStorage(true, packageURI);
5333 }
5334
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005335 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005336 if (temp) {
5337 createCopyFile();
5338 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005339 cachePath = imcs.copyResourceToContainer(
5340 packageURI, cid,
5341 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005342 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5343 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005344 }
5345
5346 @Override
5347 String getCodePath() {
5348 return cachePath + "/" + RES_FILE_NAME;
5349 }
5350
5351 @Override
5352 String getResourcePath() {
5353 return cachePath + "/" + RES_FILE_NAME;
5354 }
5355
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005356 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005357 if (status != PackageManager.INSTALL_SUCCEEDED) {
5358 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005359 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005360 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005361 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005362 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005363 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005364 if (cachePath == null) {
5365 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5366 }
5367 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005368 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005369 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005370 }
5371
5372 boolean doRename(int status, final String pkgName,
5373 String oldCodePath) {
5374 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005375 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005376 if (PackageHelper.isContainerMounted(cid)) {
5377 // Unmount the container
5378 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005379 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005380 return false;
5381 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005382 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005383 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005384 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5385 " which might be stale. Will try to clean up.");
5386 // Clean up the stale container and proceed to recreate.
5387 if (!PackageHelper.destroySdDir(newCacheId)) {
5388 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5389 return false;
5390 }
5391 // Successfully cleaned up stale container. Try to rename again.
5392 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5393 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5394 + " inspite of cleaning it up.");
5395 return false;
5396 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005397 }
5398 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005399 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005400 newCachePath = PackageHelper.mountSdDir(newCacheId,
5401 getEncryptKey(), Process.SYSTEM_UID);
5402 } else {
5403 newCachePath = PackageHelper.getSdDir(newCacheId);
5404 }
5405 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005406 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005407 return false;
5408 }
5409 Log.i(TAG, "Succesfully renamed " + cid +
5410 " at path: " + cachePath + " to " + newCacheId +
5411 " at new path: " + newCachePath);
5412 cid = newCacheId;
5413 cachePath = newCachePath;
5414 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005415 }
5416
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005417 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005418 if (status != PackageManager.INSTALL_SUCCEEDED) {
5419 cleanUp();
5420 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005421 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005422 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005423 PackageHelper.mountSdDir(cid,
5424 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005425 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005426 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005427 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005428 }
5429
5430 private void cleanUp() {
5431 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005432 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005433 }
5434
5435 void cleanUpResourcesLI() {
5436 String sourceFile = getCodePath();
5437 // Remove dex file
5438 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005439 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005440 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005441 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005442 + " at location "
5443 + sourceFile.toString() + ", retcode=" + retCode);
5444 // we don't consider this to be a failure of the core package deletion
5445 }
5446 }
5447 cleanUp();
5448 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005449
5450 boolean matchContainer(String app) {
5451 if (cid.startsWith(app)) {
5452 return true;
5453 }
5454 return false;
5455 }
5456
5457 String getPackageName() {
5458 int idx = cid.lastIndexOf("-");
5459 if (idx == -1) {
5460 return cid;
5461 }
5462 return cid.substring(0, idx);
5463 }
5464
5465 boolean doPostDeleteLI(boolean delete) {
5466 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005467 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005468 if (mounted) {
5469 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005470 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005471 }
5472 if (ret && delete) {
5473 cleanUpResourcesLI();
5474 }
5475 return ret;
5476 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005477 };
5478
5479 // Utility method used to create code paths based on package name and available index.
5480 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5481 String idxStr = "";
5482 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005483 // Fall back to default value of idx=1 if prefix is not
5484 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005485 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005486 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005487 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005488 if (subStr.endsWith(suffix)) {
5489 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005490 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005491 // If oldCodePath already contains prefix find out the
5492 // ending index to either increment or decrement.
5493 int sidx = subStr.lastIndexOf(prefix);
5494 if (sidx != -1) {
5495 subStr = subStr.substring(sidx + prefix.length());
5496 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005497 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5498 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005499 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005500 try {
5501 idx = Integer.parseInt(subStr);
5502 if (idx <= 1) {
5503 idx++;
5504 } else {
5505 idx--;
5506 }
5507 } catch(NumberFormatException e) {
5508 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005509 }
5510 }
5511 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005512 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005513 return prefix + idxStr;
5514 }
5515
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005516 // Utility method used to ignore ADD/REMOVE events
5517 // by directory observer.
5518 private static boolean ignoreCodePath(String fullPathStr) {
5519 String apkName = getApkName(fullPathStr);
5520 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5521 if (idx != -1 && ((idx+1) < apkName.length())) {
5522 // Make sure the package ends with a numeral
5523 String version = apkName.substring(idx+1);
5524 try {
5525 Integer.parseInt(version);
5526 return true;
5527 } catch (NumberFormatException e) {}
5528 }
5529 return false;
5530 }
5531
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005532 // Utility method that returns the relative package path with respect
5533 // to the installation directory. Like say for /data/data/com.test-1.apk
5534 // string com.test-1 is returned.
5535 static String getApkName(String codePath) {
5536 if (codePath == null) {
5537 return null;
5538 }
5539 int sidx = codePath.lastIndexOf("/");
5540 int eidx = codePath.lastIndexOf(".");
5541 if (eidx == -1) {
5542 eidx = codePath.length();
5543 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005544 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005545 return null;
5546 }
5547 return codePath.substring(sidx+1, eidx);
5548 }
5549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 class PackageInstalledInfo {
5551 String name;
5552 int uid;
5553 PackageParser.Package pkg;
5554 int returnCode;
5555 PackageRemovedInfo removedInfo;
5556 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 /*
5559 * Install a non-existing package.
5560 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005561 private void installNewPackageLI(PackageParser.Package pkg,
5562 int parseFlags,
5563 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 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005566 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005567
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005568 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 res.name = pkgName;
5570 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005571 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5572 // A package with the same name is already installed, though
5573 // it has been renamed to an older name. The package we
5574 // are trying to install should be installed as an update to
5575 // the existing one, but that has not been requested, so bail.
5576 Slog.w(TAG, "Attempt to re-install " + pkgName
5577 + " without first uninstalling package running as "
5578 + mSettings.mRenamedPackages.get(pkgName));
5579 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5580 return;
5581 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005582 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005584 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 + " without first uninstalling.");
5586 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5587 return;
5588 }
5589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005591 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005593 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5595 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5596 }
5597 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005598 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005599 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005600 res);
5601 // delete the partially installed application. the data directory will have to be
5602 // restored if it was already existing
5603 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5604 // remove package from internal structures. Note that we want deletePackageX to
5605 // delete the package data and cache directories that it created in
5606 // scanPackageLocked, unless those directories existed before we even tried to
5607 // install.
5608 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005609 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005610 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5611 res.removedInfo);
5612 }
5613 }
5614 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005615
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005616 private void replacePackageLI(PackageParser.Package pkg,
5617 int parseFlags,
5618 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005619 String installerPackageName, PackageInstalledInfo res) {
5620
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005621 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005622 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 // First find the old package info and check signatures
5624 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005625 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005626 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005627 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005628 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5629 return;
5630 }
5631 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005632 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005633 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005634 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005636 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 }
5638 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005641 PackageParser.Package pkg,
5642 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005643 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 PackageParser.Package newPackage = null;
5645 String pkgName = deletedPackage.packageName;
5646 boolean deletedPkg = true;
5647 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005648
Jacek Surazski65e13172009-04-28 15:26:38 +02005649 String oldInstallerPackageName = null;
5650 synchronized (mPackages) {
5651 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5652 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005655 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 res.removedInfo)) {
5657 // If the existing package was'nt successfully deleted
5658 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5659 deletedPkg = false;
5660 } else {
5661 // Successfully deleted the old package. Now proceed with re-installation
5662 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005663 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005665 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5667 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005668 }
5669 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005670 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005671 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 res);
5673 updatedSettings = true;
5674 }
5675 }
5676
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005677 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 // remove package from internal structures. Note that we want deletePackageX to
5679 // delete the package data and cache directories that it created in
5680 // scanPackageLocked, unless those directories existed before we even tried to
5681 // install.
5682 if(updatedSettings) {
5683 deletePackageLI(
5684 pkgName, true,
5685 PackageManager.DONT_DELETE_DATA,
5686 res.removedInfo);
5687 }
5688 // Since we failed to install the new package we need to restore the old
5689 // package that we deleted.
5690 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005691 File restoreFile = new File(deletedPackage.mPath);
5692 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005693 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005694 return;
5695 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005696 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005697 boolean oldOnSd = isExternal(deletedPackage);
5698 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5699 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5700 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5701 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5702 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5703 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5704 return;
5705 }
5706 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005707 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005708 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005709 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005710 mSettings.writeLP();
5711 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005712 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 }
5714 }
5715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005718 PackageParser.Package pkg,
5719 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005720 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 PackageParser.Package newPackage = null;
5722 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005723 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 PackageParser.PARSE_IS_SYSTEM;
5725 String packageName = deletedPackage.packageName;
5726 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5727 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005728 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 return;
5730 }
5731 PackageParser.Package oldPkg;
5732 PackageSetting oldPkgSetting;
5733 synchronized (mPackages) {
5734 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005735 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5737 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005738 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 return;
5740 }
5741 }
5742 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5743 res.removedInfo.removedPackage = packageName;
5744 // Remove existing system package
5745 removePackageLI(oldPkg, true);
5746 synchronized (mPackages) {
5747 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5748 }
5749
5750 // Successfully disabled the old package. Now proceed with re-installation
5751 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5752 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005753 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005755 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5757 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5758 }
5759 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005760 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 updatedSettings = true;
5762 }
5763
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005764 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 // Re installation failed. Restore old information
5766 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005767 if (newPackage != null) {
5768 removePackageLI(newPackage, true);
5769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005771 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005773 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 // Restore the old system information in Settings
5775 synchronized(mPackages) {
5776 if(updatedSettings) {
5777 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005778 mSettings.setInstallerPackageName(packageName,
5779 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 }
5781 mSettings.writeLP();
5782 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005783 } else {
5784 // If this is an update to an existing update, setup
5785 // to remove the existing update.
5786 synchronized (mPackages) {
5787 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5788 if (ps != null && ps.codePathString != null &&
5789 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5790 int installFlags = 0;
5791 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
5792 oldPkgSetting.resourcePathString);
5793 }
5794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 }
5796 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005797
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005798 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005799 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005800 int retCode;
5801 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5802 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5803 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005804 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005805 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5806 }
5807 }
5808 return PackageManager.INSTALL_SUCCEEDED;
5809 }
5810
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005811 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005812 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005813 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 synchronized (mPackages) {
5815 //write settings. the installStatus will be incomplete at this stage.
5816 //note that the new package setting would have already been
5817 //added to mPackages. It hasn't been persisted yet.
5818 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5819 mSettings.writeLP();
5820 }
5821
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005822 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005823 != PackageManager.INSTALL_SUCCEEDED) {
5824 // Discontinue if moving dex files failed.
5825 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005827 if((res.returnCode = setPermissionsLI(newPackage))
5828 != PackageManager.INSTALL_SUCCEEDED) {
5829 if (mInstaller != null) {
5830 mInstaller.rmdex(newPackage.mScanPath);
5831 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005832 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005833 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005834 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005837 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005838 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 res.name = pkgName;
5840 res.uid = newPackage.applicationInfo.uid;
5841 res.pkg = newPackage;
5842 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005843 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5845 //to update install status
5846 mSettings.writeLP();
5847 }
5848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005849
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005850 private void installPackageLI(InstallArgs args,
5851 boolean newInstall, PackageInstalledInfo res) {
5852 int pFlags = args.flags;
5853 String installerPackageName = args.installerPackageName;
5854 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005855 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005856 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005857 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005858 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005859 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005860 // Result object to be returned
5861 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5862
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005863 // Retrieve PackageSettings and parse package
5864 int parseFlags = PackageParser.PARSE_CHATTY |
5865 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5866 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5867 parseFlags |= mDefParseFlags;
5868 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5869 pp.setSeparateProcesses(mSeparateProcesses);
5870 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5871 null, mMetrics, parseFlags);
5872 if (pkg == null) {
5873 res.returnCode = pp.getParseError();
5874 return;
5875 }
5876 String pkgName = res.name = pkg.packageName;
5877 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5878 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5879 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5880 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005882 }
5883 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5884 res.returnCode = pp.getParseError();
5885 return;
5886 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005887 // Get rid of all references to package scan path via parser.
5888 pp = null;
5889 String oldCodePath = null;
5890 boolean systemApp = false;
5891 synchronized (mPackages) {
5892 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005893 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5894 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005895 if (pkg.mOriginalPackages != null
5896 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005897 && mPackages.containsKey(oldName)) {
5898 // This package is derived from an original package,
5899 // and this device has been updating from that original
5900 // name. We must continue using the original name, so
5901 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005902 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005903 pkgName = pkg.packageName;
5904 replace = true;
5905 } else if (mPackages.containsKey(pkgName)) {
5906 // This package, under its official name, already exists
5907 // on the device; we should replace it.
5908 replace = true;
5909 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005910 }
5911 PackageSetting ps = mSettings.mPackages.get(pkgName);
5912 if (ps != null) {
5913 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5914 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5915 systemApp = (ps.pkg.applicationInfo.flags &
5916 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005917 }
5918 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005920
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005921 if (systemApp && onSd) {
5922 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005923 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005924 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5925 return;
5926 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005927
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005928 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5929 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5930 return;
5931 }
5932 // Set application objects path explicitly after the rename
5933 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005934 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005935 replacePackageLI(pkg, parseFlags, scanMode,
5936 installerPackageName, res);
5937 } else {
5938 installNewPackageLI(pkg, parseFlags, scanMode,
5939 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 }
5941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005942
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005943 private int setPermissionsLI(PackageParser.Package newPackage) {
5944 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005945 int retCode = 0;
5946 // TODO Gross hack but fix later. Ideally move this to be a post installation
5947 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005948 if ((newPackage.applicationInfo.flags
5949 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5950 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 try {
5952 extractPublicFiles(newPackage, destResourceFile);
5953 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005954 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 -08005955 " forward-locked app.");
5956 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5957 } finally {
5958 //TODO clean up the extracted public files
5959 }
5960 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005961 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 newPackage.applicationInfo.uid);
5963 } else {
5964 final int filePermissions =
5965 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005966 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 newPackage.applicationInfo.uid);
5968 }
5969 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005970 // The permissions on the resource file was set when it was copied for
5971 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005975 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005976 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005978 // TODO Define new internal error
5979 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980 }
5981 return PackageManager.INSTALL_SUCCEEDED;
5982 }
5983
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005984 private boolean isForwardLocked(PackageParser.Package pkg) {
5985 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005986 }
5987
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005988 private boolean isExternal(PackageParser.Package pkg) {
5989 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
5990 }
5991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005992 private void extractPublicFiles(PackageParser.Package newPackage,
5993 File publicZipFile) throws IOException {
5994 final ZipOutputStream publicZipOutStream =
5995 new ZipOutputStream(new FileOutputStream(publicZipFile));
5996 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5997
5998 // Copy manifest, resources.arsc and res directory to public zip
5999
6000 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6001 while (privateZipEntries.hasMoreElements()) {
6002 final ZipEntry zipEntry = privateZipEntries.nextElement();
6003 final String zipEntryName = zipEntry.getName();
6004 if ("AndroidManifest.xml".equals(zipEntryName)
6005 || "resources.arsc".equals(zipEntryName)
6006 || zipEntryName.startsWith("res/")) {
6007 try {
6008 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6009 } catch (IOException e) {
6010 try {
6011 publicZipOutStream.close();
6012 throw e;
6013 } finally {
6014 publicZipFile.delete();
6015 }
6016 }
6017 }
6018 }
6019
6020 publicZipOutStream.close();
6021 FileUtils.setPermissions(
6022 publicZipFile.getAbsolutePath(),
6023 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6024 -1, -1);
6025 }
6026
6027 private static void copyZipEntry(ZipEntry zipEntry,
6028 ZipFile inZipFile,
6029 ZipOutputStream outZipStream) throws IOException {
6030 byte[] buffer = new byte[4096];
6031 int num;
6032
6033 ZipEntry newEntry;
6034 if (zipEntry.getMethod() == ZipEntry.STORED) {
6035 // Preserve the STORED method of the input entry.
6036 newEntry = new ZipEntry(zipEntry);
6037 } else {
6038 // Create a new entry so that the compressed len is recomputed.
6039 newEntry = new ZipEntry(zipEntry.getName());
6040 }
6041 outZipStream.putNextEntry(newEntry);
6042
6043 InputStream data = inZipFile.getInputStream(zipEntry);
6044 while ((num = data.read(buffer)) > 0) {
6045 outZipStream.write(buffer, 0, num);
6046 }
6047 outZipStream.flush();
6048 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 private void deleteTempPackageFiles() {
6051 FilenameFilter filter = new FilenameFilter() {
6052 public boolean accept(File dir, String name) {
6053 return name.startsWith("vmdl") && name.endsWith(".tmp");
6054 }
6055 };
6056 String tmpFilesList[] = mAppInstallDir.list(filter);
6057 if(tmpFilesList == null) {
6058 return;
6059 }
6060 for(int i = 0; i < tmpFilesList.length; i++) {
6061 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6062 tmpFile.delete();
6063 }
6064 }
6065
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006066 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006067 File tmpPackageFile;
6068 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006069 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006071 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006072 return null;
6073 }
6074 try {
6075 FileUtils.setPermissions(
6076 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6077 -1, -1);
6078 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006079 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006080 return null;
6081 }
6082 return tmpPackageFile;
6083 }
6084
6085 public void deletePackage(final String packageName,
6086 final IPackageDeleteObserver observer,
6087 final int flags) {
6088 mContext.enforceCallingOrSelfPermission(
6089 android.Manifest.permission.DELETE_PACKAGES, null);
6090 // Queue up an async operation since the package deletion may take a little while.
6091 mHandler.post(new Runnable() {
6092 public void run() {
6093 mHandler.removeCallbacks(this);
6094 final boolean succeded = deletePackageX(packageName, true, true, flags);
6095 if (observer != null) {
6096 try {
6097 observer.packageDeleted(succeded);
6098 } catch (RemoteException e) {
6099 Log.i(TAG, "Observer no longer exists.");
6100 } //end catch
6101 } //end if
6102 } //end run
6103 });
6104 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 /**
6107 * This method is an internal method that could be get invoked either
6108 * to delete an installed package or to clean up a failed installation.
6109 * After deleting an installed package, a broadcast is sent to notify any
6110 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006111 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112 * installation wouldn't have sent the initial broadcast either
6113 * The key steps in deleting a package are
6114 * deleting the package information in internal structures like mPackages,
6115 * deleting the packages base directories through installd
6116 * updating mSettings to reflect current status
6117 * persisting settings for later use
6118 * sending a broadcast if necessary
6119 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6121 boolean deleteCodeAndResources, int flags) {
6122 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006123 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006125 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6126 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6127 try {
6128 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006129 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006130 return false;
6131 }
6132 } catch (RemoteException e) {
6133 }
6134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006136 res = deletePackageLI(packageName, deleteCodeAndResources,
6137 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006141 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006142 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006143
6144 // If the removed package was a system update, the old system packaged
6145 // was re-enabled; we need to broadcast this information
6146 if (systemUpdate) {
6147 Bundle extras = new Bundle(1);
6148 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6149 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6150
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006151 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6152 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006155 // Force a gc here.
6156 Runtime.getRuntime().gc();
6157 // Delete the resources here after sending the broadcast to let
6158 // other processes clean up before deleting resources.
6159 if (info.args != null) {
6160 synchronized (mInstallLock) {
6161 info.args.doPostDeleteLI(deleteCodeAndResources);
6162 }
6163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 return res;
6165 }
6166
6167 static class PackageRemovedInfo {
6168 String removedPackage;
6169 int uid = -1;
6170 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006171 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006172 // Clean up resources deleted packages.
6173 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006174
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006175 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 Bundle extras = new Bundle(1);
6177 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6178 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6179 if (replacing) {
6180 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6181 }
6182 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006183 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 }
6185 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006186 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 }
6188 }
6189 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 /*
6192 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6193 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006194 * 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 -08006195 * delete a partially installed application.
6196 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006197 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 int flags) {
6199 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006200 if (outInfo != null) {
6201 outInfo.removedPackage = packageName;
6202 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006203 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 // Retrieve object to delete permissions for shared user later on
6205 PackageSetting deletedPs;
6206 synchronized (mPackages) {
6207 deletedPs = mSettings.mPackages.get(packageName);
6208 }
6209 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6210 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006211 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006213 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 + packageName + ", retcode=" + retCode);
6215 // we don't consider this to be a failure of the core package deletion
6216 }
6217 } else {
6218 //for emulator
6219 PackageParser.Package pkg = mPackages.get(packageName);
6220 File dataDir = new File(pkg.applicationInfo.dataDir);
6221 dataDir.delete();
6222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 }
6224 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006225 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006226 schedulePackageCleaning(packageName);
6227
6228 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6229 if (outInfo != null) {
6230 outInfo.removedUid = mSettings.removePackageLP(packageName);
6231 }
6232 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006233 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006234 if (deletedPs.sharedUser != null) {
6235 // remove permissions associated with package
6236 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6237 }
6238 }
6239 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006240 // remove from preferred activities.
6241 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6242 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6243 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6244 removed.add(pa);
6245 }
6246 }
6247 for (PreferredActivity pa : removed) {
6248 mSettings.mPreferredActivities.removeFilter(pa);
6249 }
6250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006252 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 }
6254 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 /*
6257 * Tries to delete system package.
6258 */
6259 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006260 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 ApplicationInfo applicationInfo = p.applicationInfo;
6262 //applicable for non-partially installed applications only
6263 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006264 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 return false;
6266 }
6267 PackageSetting ps = null;
6268 // Confirm if the system package has been updated
6269 // An updated system app can be deleted. This will also have to restore
6270 // the system pkg from system partition
6271 synchronized (mPackages) {
6272 ps = mSettings.getDisabledSystemPkg(p.packageName);
6273 }
6274 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006275 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 return false;
6277 } else {
6278 Log.i(TAG, "Deleting system pkg from data partition");
6279 }
6280 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006281 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006282 boolean deleteCodeAndResources = false;
6283 if (ps.versionCode < p.mVersionCode) {
6284 // Delete code and resources for downgrades
6285 deleteCodeAndResources = true;
6286 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6287 flags &= ~PackageManager.DONT_DELETE_DATA;
6288 }
6289 } else {
6290 // Preserve data by setting flag
6291 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6292 flags |= PackageManager.DONT_DELETE_DATA;
6293 }
6294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6296 if (!ret) {
6297 return false;
6298 }
6299 synchronized (mPackages) {
6300 // Reinstate the old system package
6301 mSettings.enableSystemPackageLP(p.packageName);
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006302 // Remove any native libraries.
6303 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 }
6305 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006306 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006308 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006311 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 return false;
6313 }
6314 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006315 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 mSettings.writeLP();
6317 }
6318 return true;
6319 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6322 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6323 ApplicationInfo applicationInfo = p.applicationInfo;
6324 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006325 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006326 return false;
6327 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006328 if (outInfo != null) {
6329 outInfo.uid = applicationInfo.uid;
6330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331
6332 // Delete package data from internal structures and also remove data if flag is set
6333 removePackageDataLI(p, outInfo, flags);
6334
6335 // Delete application code and resources
6336 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006337 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006338 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006339 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006340 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6341 PackageManager.INSTALL_FORWARD_LOCK : 0;
6342 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006343 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 }
6345 return true;
6346 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 /*
6349 * This method handles package deletion in general
6350 */
6351 private boolean deletePackageLI(String packageName,
6352 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6353 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006354 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 return false;
6356 }
6357 PackageParser.Package p;
6358 boolean dataOnly = false;
6359 synchronized (mPackages) {
6360 p = mPackages.get(packageName);
6361 if (p == null) {
6362 //this retrieves partially installed apps
6363 dataOnly = true;
6364 PackageSetting ps = mSettings.mPackages.get(packageName);
6365 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006366 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 return false;
6368 }
6369 p = ps.pkg;
6370 }
6371 }
6372 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006373 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 return false;
6375 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 if (dataOnly) {
6378 // Delete application data first
6379 removePackageDataLI(p, outInfo, flags);
6380 return true;
6381 }
6382 // At this point the package should have ApplicationInfo associated with it
6383 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006384 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 return false;
6386 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006387 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6389 Log.i(TAG, "Removing system package:"+p.packageName);
6390 // When an updated system application is deleted we delete the existing resources as well and
6391 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006392 ret = deleteSystemPackageLI(p, flags, outInfo);
6393 } else {
6394 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006395 // Kill application pre-emptively especially for apps on sd.
6396 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006397 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006399 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 public void clearApplicationUserData(final String packageName,
6403 final IPackageDataObserver observer) {
6404 mContext.enforceCallingOrSelfPermission(
6405 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6406 // Queue up an async operation since the package deletion may take a little while.
6407 mHandler.post(new Runnable() {
6408 public void run() {
6409 mHandler.removeCallbacks(this);
6410 final boolean succeeded;
6411 synchronized (mInstallLock) {
6412 succeeded = clearApplicationUserDataLI(packageName);
6413 }
6414 if (succeeded) {
6415 // invoke DeviceStorageMonitor's update method to clear any notifications
6416 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6417 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6418 if (dsm != null) {
6419 dsm.updateMemory();
6420 }
6421 }
6422 if(observer != null) {
6423 try {
6424 observer.onRemoveCompleted(packageName, succeeded);
6425 } catch (RemoteException e) {
6426 Log.i(TAG, "Observer no longer exists.");
6427 }
6428 } //end if observer
6429 } //end run
6430 });
6431 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 private boolean clearApplicationUserDataLI(String packageName) {
6434 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006435 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 return false;
6437 }
6438 PackageParser.Package p;
6439 boolean dataOnly = false;
6440 synchronized (mPackages) {
6441 p = mPackages.get(packageName);
6442 if(p == null) {
6443 dataOnly = true;
6444 PackageSetting ps = mSettings.mPackages.get(packageName);
6445 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006446 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 return false;
6448 }
6449 p = ps.pkg;
6450 }
6451 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 if(!dataOnly) {
6454 //need to check this only for fully installed applications
6455 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006456 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 return false;
6458 }
6459 final ApplicationInfo applicationInfo = p.applicationInfo;
6460 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006461 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 return false;
6463 }
6464 }
6465 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006466 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006468 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 + packageName);
6470 return false;
6471 }
6472 }
6473 return true;
6474 }
6475
6476 public void deleteApplicationCacheFiles(final String packageName,
6477 final IPackageDataObserver observer) {
6478 mContext.enforceCallingOrSelfPermission(
6479 android.Manifest.permission.DELETE_CACHE_FILES, null);
6480 // Queue up an async operation since the package deletion may take a little while.
6481 mHandler.post(new Runnable() {
6482 public void run() {
6483 mHandler.removeCallbacks(this);
6484 final boolean succeded;
6485 synchronized (mInstallLock) {
6486 succeded = deleteApplicationCacheFilesLI(packageName);
6487 }
6488 if(observer != null) {
6489 try {
6490 observer.onRemoveCompleted(packageName, succeded);
6491 } catch (RemoteException e) {
6492 Log.i(TAG, "Observer no longer exists.");
6493 }
6494 } //end if observer
6495 } //end run
6496 });
6497 }
6498
6499 private boolean deleteApplicationCacheFilesLI(String packageName) {
6500 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006501 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 return false;
6503 }
6504 PackageParser.Package p;
6505 synchronized (mPackages) {
6506 p = mPackages.get(packageName);
6507 }
6508 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006509 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 return false;
6511 }
6512 final ApplicationInfo applicationInfo = p.applicationInfo;
6513 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006514 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 return false;
6516 }
6517 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006518 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006520 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 + packageName);
6522 return false;
6523 }
6524 }
6525 return true;
6526 }
6527
6528 public void getPackageSizeInfo(final String packageName,
6529 final IPackageStatsObserver observer) {
6530 mContext.enforceCallingOrSelfPermission(
6531 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6532 // Queue up an async operation since the package deletion may take a little while.
6533 mHandler.post(new Runnable() {
6534 public void run() {
6535 mHandler.removeCallbacks(this);
6536 PackageStats lStats = new PackageStats(packageName);
6537 final boolean succeded;
6538 synchronized (mInstallLock) {
6539 succeded = getPackageSizeInfoLI(packageName, lStats);
6540 }
6541 if(observer != null) {
6542 try {
6543 observer.onGetStatsCompleted(lStats, succeded);
6544 } catch (RemoteException e) {
6545 Log.i(TAG, "Observer no longer exists.");
6546 }
6547 } //end if observer
6548 } //end run
6549 });
6550 }
6551
6552 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6553 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006554 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006555 return false;
6556 }
6557 PackageParser.Package p;
6558 boolean dataOnly = false;
6559 synchronized (mPackages) {
6560 p = mPackages.get(packageName);
6561 if(p == null) {
6562 dataOnly = true;
6563 PackageSetting ps = mSettings.mPackages.get(packageName);
6564 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006565 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 return false;
6567 }
6568 p = ps.pkg;
6569 }
6570 }
6571 String publicSrcDir = null;
6572 if(!dataOnly) {
6573 final ApplicationInfo applicationInfo = p.applicationInfo;
6574 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006575 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006576 return false;
6577 }
6578 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6579 }
6580 if (mInstaller != null) {
6581 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006582 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 if (res < 0) {
6584 return false;
6585 } else {
6586 return true;
6587 }
6588 }
6589 return true;
6590 }
6591
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006593 public void addPackageToPreferred(String packageName) {
6594 mContext.enforceCallingOrSelfPermission(
6595 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006596 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 }
6598
6599 public void removePackageFromPreferred(String packageName) {
6600 mContext.enforceCallingOrSelfPermission(
6601 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006602 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006603 }
6604
6605 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006606 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 }
6608
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006609 int getUidTargetSdkVersionLockedLP(int uid) {
6610 Object obj = mSettings.getUserIdLP(uid);
6611 if (obj instanceof SharedUserSetting) {
6612 SharedUserSetting sus = (SharedUserSetting)obj;
6613 final int N = sus.packages.size();
6614 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6615 Iterator<PackageSetting> it = sus.packages.iterator();
6616 int i=0;
6617 while (it.hasNext()) {
6618 PackageSetting ps = it.next();
6619 if (ps.pkg != null) {
6620 int v = ps.pkg.applicationInfo.targetSdkVersion;
6621 if (v < vers) vers = v;
6622 }
6623 }
6624 return vers;
6625 } else if (obj instanceof PackageSetting) {
6626 PackageSetting ps = (PackageSetting)obj;
6627 if (ps.pkg != null) {
6628 return ps.pkg.applicationInfo.targetSdkVersion;
6629 }
6630 }
6631 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6632 }
6633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 public void addPreferredActivity(IntentFilter filter, int match,
6635 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006637 if (mContext.checkCallingOrSelfPermission(
6638 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6639 != PackageManager.PERMISSION_GRANTED) {
6640 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6641 < Build.VERSION_CODES.FROYO) {
6642 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6643 + Binder.getCallingUid());
6644 return;
6645 }
6646 mContext.enforceCallingOrSelfPermission(
6647 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6648 }
6649
6650 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6652 mSettings.mPreferredActivities.addFilter(
6653 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006654 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 }
6656 }
6657
Satish Sampath8dbe6122009-06-02 23:35:54 +01006658 public void replacePreferredActivity(IntentFilter filter, int match,
6659 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006660 if (filter.countActions() != 1) {
6661 throw new IllegalArgumentException(
6662 "replacePreferredActivity expects filter to have only 1 action.");
6663 }
6664 if (filter.countCategories() != 1) {
6665 throw new IllegalArgumentException(
6666 "replacePreferredActivity expects filter to have only 1 category.");
6667 }
6668 if (filter.countDataAuthorities() != 0
6669 || filter.countDataPaths() != 0
6670 || filter.countDataSchemes() != 0
6671 || filter.countDataTypes() != 0) {
6672 throw new IllegalArgumentException(
6673 "replacePreferredActivity expects filter to have no data authorities, " +
6674 "paths, schemes or types.");
6675 }
6676 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006677 if (mContext.checkCallingOrSelfPermission(
6678 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6679 != PackageManager.PERMISSION_GRANTED) {
6680 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6681 < Build.VERSION_CODES.FROYO) {
6682 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6683 + Binder.getCallingUid());
6684 return;
6685 }
6686 mContext.enforceCallingOrSelfPermission(
6687 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6688 }
6689
Satish Sampath8dbe6122009-06-02 23:35:54 +01006690 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6691 String action = filter.getAction(0);
6692 String category = filter.getCategory(0);
6693 while (it.hasNext()) {
6694 PreferredActivity pa = it.next();
6695 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6696 it.remove();
6697 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6698 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6699 }
6700 }
6701 addPreferredActivity(filter, match, set, activity);
6702 }
6703 }
6704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006707 int uid = Binder.getCallingUid();
6708 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006709 if (pkg == null || pkg.applicationInfo.uid != uid) {
6710 if (mContext.checkCallingOrSelfPermission(
6711 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6712 != PackageManager.PERMISSION_GRANTED) {
6713 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6714 < Build.VERSION_CODES.FROYO) {
6715 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6716 + Binder.getCallingUid());
6717 return;
6718 }
6719 mContext.enforceCallingOrSelfPermission(
6720 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6721 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006722 }
6723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006725 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 }
6727 }
6728 }
6729
6730 boolean clearPackagePreferredActivitiesLP(String packageName) {
6731 boolean changed = false;
6732 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6733 while (it.hasNext()) {
6734 PreferredActivity pa = it.next();
6735 if (pa.mActivity.getPackageName().equals(packageName)) {
6736 it.remove();
6737 changed = true;
6738 }
6739 }
6740 return changed;
6741 }
6742
6743 public int getPreferredActivities(List<IntentFilter> outFilters,
6744 List<ComponentName> outActivities, String packageName) {
6745
6746 int num = 0;
6747 synchronized (mPackages) {
6748 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6749 while (it.hasNext()) {
6750 PreferredActivity pa = it.next();
6751 if (packageName == null
6752 || pa.mActivity.getPackageName().equals(packageName)) {
6753 if (outFilters != null) {
6754 outFilters.add(new IntentFilter(pa));
6755 }
6756 if (outActivities != null) {
6757 outActivities.add(pa.mActivity);
6758 }
6759 }
6760 }
6761 }
6762
6763 return num;
6764 }
6765
6766 public void setApplicationEnabledSetting(String appPackageName,
6767 int newState, int flags) {
6768 setEnabledSetting(appPackageName, null, newState, flags);
6769 }
6770
6771 public void setComponentEnabledSetting(ComponentName componentName,
6772 int newState, int flags) {
6773 setEnabledSetting(componentName.getPackageName(),
6774 componentName.getClassName(), newState, flags);
6775 }
6776
6777 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006778 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6780 || newState == COMPONENT_ENABLED_STATE_ENABLED
6781 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6782 throw new IllegalArgumentException("Invalid new component state: "
6783 + newState);
6784 }
6785 PackageSetting pkgSetting;
6786 final int uid = Binder.getCallingUid();
6787 final int permission = mContext.checkCallingPermission(
6788 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6789 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006790 boolean sendNow = false;
6791 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006792 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006794 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006795 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006796 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006798 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006800 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 }
6802 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006803 "Unknown component: " + packageName
6804 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 }
6806 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6807 throw new SecurityException(
6808 "Permission Denial: attempt to change component state from pid="
6809 + Binder.getCallingPid()
6810 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6811 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006812 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006814 if (pkgSetting.enabled == newState) {
6815 // Nothing to do
6816 return;
6817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 pkgSetting.enabled = newState;
6819 } else {
6820 // We're dealing with a component level state change
6821 switch (newState) {
6822 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006823 if (!pkgSetting.enableComponentLP(className)) {
6824 return;
6825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006826 break;
6827 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006828 if (!pkgSetting.disableComponentLP(className)) {
6829 return;
6830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006831 break;
6832 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006833 if (!pkgSetting.restoreComponentLP(className)) {
6834 return;
6835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 break;
6837 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006838 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006839 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 }
6841 }
6842 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006843 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006844 components = mPendingBroadcasts.get(packageName);
6845 boolean newPackage = components == null;
6846 if (newPackage) {
6847 components = new ArrayList<String>();
6848 }
6849 if (!components.contains(componentName)) {
6850 components.add(componentName);
6851 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006852 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6853 sendNow = true;
6854 // Purge entry from pending broadcast list if another one exists already
6855 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006856 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006857 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006858 if (newPackage) {
6859 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006860 }
6861 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6862 // Schedule a message
6863 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6864 }
6865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006866 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 long callingId = Binder.clearCallingIdentity();
6869 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006870 if (sendNow) {
6871 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006872 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 } finally {
6875 Binder.restoreCallingIdentity(callingId);
6876 }
6877 }
6878
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006879 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006880 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6881 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6882 + " components=" + componentNames);
6883 Bundle extras = new Bundle(4);
6884 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6885 String nameList[] = new String[componentNames.size()];
6886 componentNames.toArray(nameList);
6887 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006888 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6889 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006890 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006891 }
6892
Jacek Surazski65e13172009-04-28 15:26:38 +02006893 public String getInstallerPackageName(String packageName) {
6894 synchronized (mPackages) {
6895 PackageSetting pkg = mSettings.mPackages.get(packageName);
6896 if (pkg == null) {
6897 throw new IllegalArgumentException("Unknown package: " + packageName);
6898 }
6899 return pkg.installerPackageName;
6900 }
6901 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 public int getApplicationEnabledSetting(String appPackageName) {
6904 synchronized (mPackages) {
6905 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6906 if (pkg == null) {
6907 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6908 }
6909 return pkg.enabled;
6910 }
6911 }
6912
6913 public int getComponentEnabledSetting(ComponentName componentName) {
6914 synchronized (mPackages) {
6915 final String packageNameStr = componentName.getPackageName();
6916 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6917 if (pkg == null) {
6918 throw new IllegalArgumentException("Unknown component: " + componentName);
6919 }
6920 final String classNameStr = componentName.getClassName();
6921 return pkg.currentEnabledStateLP(classNameStr);
6922 }
6923 }
6924
6925 public void enterSafeMode() {
6926 if (!mSystemReady) {
6927 mSafeMode = true;
6928 }
6929 }
6930
6931 public void systemReady() {
6932 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006933
6934 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006935 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006936 mContext.getContentResolver(),
6937 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006938 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006939 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006940 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 }
6943
6944 public boolean isSafeMode() {
6945 return mSafeMode;
6946 }
6947
6948 public boolean hasSystemUidErrors() {
6949 return mHasSystemUidErrors;
6950 }
6951
6952 static String arrayToString(int[] array) {
6953 StringBuffer buf = new StringBuffer(128);
6954 buf.append('[');
6955 if (array != null) {
6956 for (int i=0; i<array.length; i++) {
6957 if (i > 0) buf.append(", ");
6958 buf.append(array[i]);
6959 }
6960 }
6961 buf.append(']');
6962 return buf.toString();
6963 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 @Override
6966 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6967 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6968 != PackageManager.PERMISSION_GRANTED) {
6969 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6970 + Binder.getCallingPid()
6971 + ", uid=" + Binder.getCallingUid()
6972 + " without permission "
6973 + android.Manifest.permission.DUMP);
6974 return;
6975 }
6976
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006977 String packageName = null;
6978
6979 int opti = 0;
6980 while (opti < args.length) {
6981 String opt = args[opti];
6982 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6983 break;
6984 }
6985 opti++;
6986 if ("-a".equals(opt)) {
6987 // Right now we only know how to print all.
6988 } else if ("-h".equals(opt)) {
6989 pw.println("Package manager dump options:");
6990 pw.println(" [-h] [cmd] ...");
6991 pw.println(" cmd may be one of:");
6992 pw.println(" [package.name]: info about given package");
6993 return;
6994 } else {
6995 pw.println("Unknown argument: " + opt + "; use -h for help");
6996 }
6997 }
6998
6999 // Is the caller requesting to dump a particular piece of data?
7000 if (opti < args.length) {
7001 String cmd = args[opti];
7002 opti++;
7003 // Is this a package name?
7004 if ("android".equals(cmd) || cmd.contains(".")) {
7005 packageName = cmd;
7006 }
7007 }
7008
7009 boolean printedTitle = false;
7010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007012 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
7013 printedTitle = true;
7014 }
7015 if (mReceivers.dump(pw, printedTitle
7016 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7017 " ", packageName)) {
7018 printedTitle = true;
7019 }
7020 if (mServices.dump(pw, printedTitle
7021 ? "\nService Resolver Table:" : "Service Resolver Table:",
7022 " ", packageName)) {
7023 printedTitle = true;
7024 }
7025 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7026 ? "\nPreferred Activities:" : "Preferred Activities:",
7027 " ", packageName)) {
7028 printedTitle = true;
7029 }
7030 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 {
7032 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007033 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7034 continue;
7035 }
7036 if (!printedSomething) {
7037 if (printedTitle) pw.println(" ");
7038 pw.println("Permissions:");
7039 printedSomething = true;
7040 printedTitle = true;
7041 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007042 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7043 pw.print(Integer.toHexString(System.identityHashCode(p)));
7044 pw.println("):");
7045 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7046 pw.print(" uid="); pw.print(p.uid);
7047 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007048 pw.print(" type="); pw.print(p.type);
7049 pw.print(" prot="); pw.println(p.protectionLevel);
7050 if (p.packageSetting != null) {
7051 pw.print(" packageSetting="); pw.println(p.packageSetting);
7052 }
7053 if (p.perm != null) {
7054 pw.print(" perm="); pw.println(p.perm);
7055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 }
7057 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007058 printedSomething = false;
7059 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007060 {
7061 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007062 if (packageName != null && !packageName.equals(ps.realName)
7063 && !packageName.equals(ps.name)) {
7064 continue;
7065 }
7066 if (!printedSomething) {
7067 if (printedTitle) pw.println(" ");
7068 pw.println("Packages:");
7069 printedSomething = true;
7070 printedTitle = true;
7071 }
7072 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007073 pw.print(" Package [");
7074 pw.print(ps.realName != null ? ps.realName : ps.name);
7075 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007076 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7077 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007078 if (ps.realName != null) {
7079 pw.print(" compat name="); pw.println(ps.name);
7080 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007081 pw.print(" userId="); pw.print(ps.userId);
7082 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7083 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7084 pw.print(" pkg="); pw.println(ps.pkg);
7085 pw.print(" codePath="); pw.println(ps.codePathString);
7086 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007088 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007089 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007090 pw.print(" supportsScreens=[");
7091 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007092 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007093 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007094 if (!first) pw.print(", ");
7095 first = false;
7096 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007098 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007099 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007100 if (!first) pw.print(", ");
7101 first = false;
7102 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007103 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007104 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007105 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007106 if (!first) pw.print(", ");
7107 first = false;
7108 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007109 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007110 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007111 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007112 if (!first) pw.print(", ");
7113 first = false;
7114 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007115 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007116 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007117 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7118 if (!first) pw.print(", ");
7119 first = false;
7120 pw.print("anyDensity");
7121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007122 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007123 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007124 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7125 pw.print(" signatures="); pw.println(ps.signatures);
7126 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007127 pw.print(" haveGids="); pw.println(ps.haveGids);
7128 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007129 pw.print(" installStatus="); pw.print(ps.installStatus);
7130 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007131 if (ps.disabledComponents.size() > 0) {
7132 pw.println(" disabledComponents:");
7133 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007134 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007135 }
7136 }
7137 if (ps.enabledComponents.size() > 0) {
7138 pw.println(" enabledComponents:");
7139 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007140 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007141 }
7142 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007143 if (ps.grantedPermissions.size() > 0) {
7144 pw.println(" grantedPermissions:");
7145 for (String s : ps.grantedPermissions) {
7146 pw.print(" "); pw.println(s);
7147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007149 }
7150 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007151 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007152 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007153 for (HashMap.Entry<String, String> e
7154 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007155 if (packageName != null && !packageName.equals(e.getKey())
7156 && !packageName.equals(e.getValue())) {
7157 continue;
7158 }
7159 if (!printedSomething) {
7160 if (printedTitle) pw.println(" ");
7161 pw.println("Renamed packages:");
7162 printedSomething = true;
7163 printedTitle = true;
7164 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007165 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7166 pw.println(e.getValue());
7167 }
7168 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007169 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007170 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007171 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007172 if (packageName != null && !packageName.equals(ps.realName)
7173 && !packageName.equals(ps.name)) {
7174 continue;
7175 }
7176 if (!printedSomething) {
7177 if (printedTitle) pw.println(" ");
7178 pw.println("Hidden system packages:");
7179 printedSomething = true;
7180 printedTitle = true;
7181 }
7182 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007183 pw.print(ps.realName != null ? ps.realName : ps.name);
7184 pw.print("] (");
7185 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7186 pw.println("):");
7187 if (ps.realName != null) {
7188 pw.print(" compat name="); pw.println(ps.name);
7189 }
7190 pw.print(" userId="); pw.println(ps.userId);
7191 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7192 pw.print(" codePath="); pw.println(ps.codePathString);
7193 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7194 }
7195 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007196 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 {
7198 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007199 if (packageName != null && su != packageSharedUser) {
7200 continue;
7201 }
7202 if (!printedSomething) {
7203 if (printedTitle) pw.println(" ");
7204 pw.println("Shared users:");
7205 printedSomething = true;
7206 printedTitle = true;
7207 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007208 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7209 pw.print(Integer.toHexString(System.identityHashCode(su)));
7210 pw.println("):");
7211 pw.print(" userId="); pw.print(su.userId);
7212 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213 pw.println(" grantedPermissions:");
7214 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007215 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007217 }
7218 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007219
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007220 if (packageName == null) {
7221 if (printedTitle) pw.println(" ");
7222 printedTitle = true;
7223 pw.println("Settings parse messages:");
7224 pw.println(mSettings.mReadMessages.toString());
7225
7226 pw.println(" ");
7227 pw.println("Package warning messages:");
7228 File fname = getSettingsProblemFile();
7229 FileInputStream in;
7230 try {
7231 in = new FileInputStream(fname);
7232 int avail = in.available();
7233 byte[] data = new byte[avail];
7234 in.read(data);
7235 pw.println(new String(data));
7236 } catch (FileNotFoundException e) {
7237 } catch (IOException e) {
7238 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007240 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007241
7242 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007243 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007244 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007245 if (packageName != null && !packageName.equals(p.info.packageName)) {
7246 continue;
7247 }
7248 if (!printedSomething) {
7249 if (printedTitle) pw.println(" ");
7250 pw.println("Registered ContentProviders:");
7251 printedSomething = true;
7252 printedTitle = true;
7253 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007254 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007255 pw.println(p.toString());
7256 }
7257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007258 }
7259
7260 static final class BasePermission {
7261 final static int TYPE_NORMAL = 0;
7262 final static int TYPE_BUILTIN = 1;
7263 final static int TYPE_DYNAMIC = 2;
7264
7265 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007266 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007267 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007268 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007269 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007270 PackageParser.Permission perm;
7271 PermissionInfo pendingInfo;
7272 int uid;
7273 int[] gids;
7274
7275 BasePermission(String _name, String _sourcePackage, int _type) {
7276 name = _name;
7277 sourcePackage = _sourcePackage;
7278 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007279 // Default to most conservative protection level.
7280 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7281 }
7282
7283 public String toString() {
7284 return "BasePermission{"
7285 + Integer.toHexString(System.identityHashCode(this))
7286 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 }
7288 }
7289
7290 static class PackageSignatures {
7291 private Signature[] mSignatures;
7292
7293 PackageSignatures(Signature[] sigs) {
7294 assignSignatures(sigs);
7295 }
7296
7297 PackageSignatures() {
7298 }
7299
7300 void writeXml(XmlSerializer serializer, String tagName,
7301 ArrayList<Signature> pastSignatures) throws IOException {
7302 if (mSignatures == null) {
7303 return;
7304 }
7305 serializer.startTag(null, tagName);
7306 serializer.attribute(null, "count",
7307 Integer.toString(mSignatures.length));
7308 for (int i=0; i<mSignatures.length; i++) {
7309 serializer.startTag(null, "cert");
7310 final Signature sig = mSignatures[i];
7311 final int sigHash = sig.hashCode();
7312 final int numPast = pastSignatures.size();
7313 int j;
7314 for (j=0; j<numPast; j++) {
7315 Signature pastSig = pastSignatures.get(j);
7316 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7317 serializer.attribute(null, "index", Integer.toString(j));
7318 break;
7319 }
7320 }
7321 if (j >= numPast) {
7322 pastSignatures.add(sig);
7323 serializer.attribute(null, "index", Integer.toString(numPast));
7324 serializer.attribute(null, "key", sig.toCharsString());
7325 }
7326 serializer.endTag(null, "cert");
7327 }
7328 serializer.endTag(null, tagName);
7329 }
7330
7331 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7332 throws IOException, XmlPullParserException {
7333 String countStr = parser.getAttributeValue(null, "count");
7334 if (countStr == null) {
7335 reportSettingsProblem(Log.WARN,
7336 "Error in package manager settings: <signatures> has"
7337 + " no count at " + parser.getPositionDescription());
7338 XmlUtils.skipCurrentTag(parser);
7339 }
7340 final int count = Integer.parseInt(countStr);
7341 mSignatures = new Signature[count];
7342 int pos = 0;
7343
7344 int outerDepth = parser.getDepth();
7345 int type;
7346 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7347 && (type != XmlPullParser.END_TAG
7348 || parser.getDepth() > outerDepth)) {
7349 if (type == XmlPullParser.END_TAG
7350 || type == XmlPullParser.TEXT) {
7351 continue;
7352 }
7353
7354 String tagName = parser.getName();
7355 if (tagName.equals("cert")) {
7356 if (pos < count) {
7357 String index = parser.getAttributeValue(null, "index");
7358 if (index != null) {
7359 try {
7360 int idx = Integer.parseInt(index);
7361 String key = parser.getAttributeValue(null, "key");
7362 if (key == null) {
7363 if (idx >= 0 && idx < pastSignatures.size()) {
7364 Signature sig = pastSignatures.get(idx);
7365 if (sig != null) {
7366 mSignatures[pos] = pastSignatures.get(idx);
7367 pos++;
7368 } else {
7369 reportSettingsProblem(Log.WARN,
7370 "Error in package manager settings: <cert> "
7371 + "index " + index + " is not defined at "
7372 + parser.getPositionDescription());
7373 }
7374 } else {
7375 reportSettingsProblem(Log.WARN,
7376 "Error in package manager settings: <cert> "
7377 + "index " + index + " is out of bounds at "
7378 + parser.getPositionDescription());
7379 }
7380 } else {
7381 while (pastSignatures.size() <= idx) {
7382 pastSignatures.add(null);
7383 }
7384 Signature sig = new Signature(key);
7385 pastSignatures.set(idx, sig);
7386 mSignatures[pos] = sig;
7387 pos++;
7388 }
7389 } catch (NumberFormatException e) {
7390 reportSettingsProblem(Log.WARN,
7391 "Error in package manager settings: <cert> "
7392 + "index " + index + " is not a number at "
7393 + parser.getPositionDescription());
7394 }
7395 } else {
7396 reportSettingsProblem(Log.WARN,
7397 "Error in package manager settings: <cert> has"
7398 + " no index at " + parser.getPositionDescription());
7399 }
7400 } else {
7401 reportSettingsProblem(Log.WARN,
7402 "Error in package manager settings: too "
7403 + "many <cert> tags, expected " + count
7404 + " at " + parser.getPositionDescription());
7405 }
7406 } else {
7407 reportSettingsProblem(Log.WARN,
7408 "Unknown element under <cert>: "
7409 + parser.getName());
7410 }
7411 XmlUtils.skipCurrentTag(parser);
7412 }
7413
7414 if (pos < count) {
7415 // Should never happen -- there is an error in the written
7416 // settings -- but if it does we don't want to generate
7417 // a bad array.
7418 Signature[] newSigs = new Signature[pos];
7419 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7420 mSignatures = newSigs;
7421 }
7422 }
7423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007424 private void assignSignatures(Signature[] sigs) {
7425 if (sigs == null) {
7426 mSignatures = null;
7427 return;
7428 }
7429 mSignatures = new Signature[sigs.length];
7430 for (int i=0; i<sigs.length; i++) {
7431 mSignatures[i] = sigs[i];
7432 }
7433 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007435 @Override
7436 public String toString() {
7437 StringBuffer buf = new StringBuffer(128);
7438 buf.append("PackageSignatures{");
7439 buf.append(Integer.toHexString(System.identityHashCode(this)));
7440 buf.append(" [");
7441 if (mSignatures != null) {
7442 for (int i=0; i<mSignatures.length; i++) {
7443 if (i > 0) buf.append(", ");
7444 buf.append(Integer.toHexString(
7445 System.identityHashCode(mSignatures[i])));
7446 }
7447 }
7448 buf.append("]}");
7449 return buf.toString();
7450 }
7451 }
7452
7453 static class PreferredActivity extends IntentFilter {
7454 final int mMatch;
7455 final String[] mSetPackages;
7456 final String[] mSetClasses;
7457 final String[] mSetComponents;
7458 final ComponentName mActivity;
7459 final String mShortActivity;
7460 String mParseError;
7461
7462 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7463 ComponentName activity) {
7464 super(filter);
7465 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7466 mActivity = activity;
7467 mShortActivity = activity.flattenToShortString();
7468 mParseError = null;
7469 if (set != null) {
7470 final int N = set.length;
7471 String[] myPackages = new String[N];
7472 String[] myClasses = new String[N];
7473 String[] myComponents = new String[N];
7474 for (int i=0; i<N; i++) {
7475 ComponentName cn = set[i];
7476 if (cn == null) {
7477 mSetPackages = null;
7478 mSetClasses = null;
7479 mSetComponents = null;
7480 return;
7481 }
7482 myPackages[i] = cn.getPackageName().intern();
7483 myClasses[i] = cn.getClassName().intern();
7484 myComponents[i] = cn.flattenToShortString().intern();
7485 }
7486 mSetPackages = myPackages;
7487 mSetClasses = myClasses;
7488 mSetComponents = myComponents;
7489 } else {
7490 mSetPackages = null;
7491 mSetClasses = null;
7492 mSetComponents = null;
7493 }
7494 }
7495
7496 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7497 IOException {
7498 mShortActivity = parser.getAttributeValue(null, "name");
7499 mActivity = ComponentName.unflattenFromString(mShortActivity);
7500 if (mActivity == null) {
7501 mParseError = "Bad activity name " + mShortActivity;
7502 }
7503 String matchStr = parser.getAttributeValue(null, "match");
7504 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7505 String setCountStr = parser.getAttributeValue(null, "set");
7506 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7507
7508 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7509 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7510 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7511
7512 int setPos = 0;
7513
7514 int outerDepth = parser.getDepth();
7515 int type;
7516 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7517 && (type != XmlPullParser.END_TAG
7518 || parser.getDepth() > outerDepth)) {
7519 if (type == XmlPullParser.END_TAG
7520 || type == XmlPullParser.TEXT) {
7521 continue;
7522 }
7523
7524 String tagName = parser.getName();
7525 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7526 // + parser.getDepth() + " tag=" + tagName);
7527 if (tagName.equals("set")) {
7528 String name = parser.getAttributeValue(null, "name");
7529 if (name == null) {
7530 if (mParseError == null) {
7531 mParseError = "No name in set tag in preferred activity "
7532 + mShortActivity;
7533 }
7534 } else if (setPos >= setCount) {
7535 if (mParseError == null) {
7536 mParseError = "Too many set tags in preferred activity "
7537 + mShortActivity;
7538 }
7539 } else {
7540 ComponentName cn = ComponentName.unflattenFromString(name);
7541 if (cn == null) {
7542 if (mParseError == null) {
7543 mParseError = "Bad set name " + name + " in preferred activity "
7544 + mShortActivity;
7545 }
7546 } else {
7547 myPackages[setPos] = cn.getPackageName();
7548 myClasses[setPos] = cn.getClassName();
7549 myComponents[setPos] = name;
7550 setPos++;
7551 }
7552 }
7553 XmlUtils.skipCurrentTag(parser);
7554 } else if (tagName.equals("filter")) {
7555 //Log.i(TAG, "Starting to parse filter...");
7556 readFromXml(parser);
7557 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7558 // + parser.getDepth() + " tag=" + parser.getName());
7559 } else {
7560 reportSettingsProblem(Log.WARN,
7561 "Unknown element under <preferred-activities>: "
7562 + parser.getName());
7563 XmlUtils.skipCurrentTag(parser);
7564 }
7565 }
7566
7567 if (setPos != setCount) {
7568 if (mParseError == null) {
7569 mParseError = "Not enough set tags (expected " + setCount
7570 + " but found " + setPos + ") in " + mShortActivity;
7571 }
7572 }
7573
7574 mSetPackages = myPackages;
7575 mSetClasses = myClasses;
7576 mSetComponents = myComponents;
7577 }
7578
7579 public void writeToXml(XmlSerializer serializer) throws IOException {
7580 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7581 serializer.attribute(null, "name", mShortActivity);
7582 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7583 serializer.attribute(null, "set", Integer.toString(NS));
7584 for (int s=0; s<NS; s++) {
7585 serializer.startTag(null, "set");
7586 serializer.attribute(null, "name", mSetComponents[s]);
7587 serializer.endTag(null, "set");
7588 }
7589 serializer.startTag(null, "filter");
7590 super.writeToXml(serializer);
7591 serializer.endTag(null, "filter");
7592 }
7593
7594 boolean sameSet(List<ResolveInfo> query, int priority) {
7595 if (mSetPackages == null) return false;
7596 final int NQ = query.size();
7597 final int NS = mSetPackages.length;
7598 int numMatch = 0;
7599 for (int i=0; i<NQ; i++) {
7600 ResolveInfo ri = query.get(i);
7601 if (ri.priority != priority) continue;
7602 ActivityInfo ai = ri.activityInfo;
7603 boolean good = false;
7604 for (int j=0; j<NS; j++) {
7605 if (mSetPackages[j].equals(ai.packageName)
7606 && mSetClasses[j].equals(ai.name)) {
7607 numMatch++;
7608 good = true;
7609 break;
7610 }
7611 }
7612 if (!good) return false;
7613 }
7614 return numMatch == NS;
7615 }
7616 }
7617
7618 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007619 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007621 HashSet<String> grantedPermissions = new HashSet<String>();
7622 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007625 setFlags(pkgFlags);
7626 }
7627
7628 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007629 this.pkgFlags = pkgFlags & (
7630 ApplicationInfo.FLAG_SYSTEM |
7631 ApplicationInfo.FLAG_FORWARD_LOCK |
7632 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633 }
7634 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 /**
7637 * Settings base class for pending and resolved classes.
7638 */
7639 static class PackageSettingBase extends GrantedPermissions {
7640 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007641 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007642 File codePath;
7643 String codePathString;
7644 File resourcePath;
7645 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007646 private long timeStamp;
7647 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007648 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007650 boolean uidError;
7651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 PackageSignatures signatures = new PackageSignatures();
7653
7654 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007655 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007657 /* Explicitly disabled components */
7658 HashSet<String> disabledComponents = new HashSet<String>(0);
7659 /* Explicitly enabled components */
7660 HashSet<String> enabledComponents = new HashSet<String>(0);
7661 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7662 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007663
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007664 PackageSettingBase origPackage;
7665
Jacek Surazski65e13172009-04-28 15:26:38 +02007666 /* package name of the app that installed this package */
7667 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007669 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007670 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007671 super(pkgFlags);
7672 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007673 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007674 init(codePath, resourcePath, pVersionCode);
7675 }
7676
7677 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 this.codePath = codePath;
7679 this.codePathString = codePath.toString();
7680 this.resourcePath = resourcePath;
7681 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007682 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007683 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007684
Jacek Surazski65e13172009-04-28 15:26:38 +02007685 public void setInstallerPackageName(String packageName) {
7686 installerPackageName = packageName;
7687 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007688
Jacek Surazski65e13172009-04-28 15:26:38 +02007689 String getInstallerPackageName() {
7690 return installerPackageName;
7691 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 public void setInstallStatus(int newStatus) {
7694 installStatus = newStatus;
7695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007697 public int getInstallStatus() {
7698 return installStatus;
7699 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 public void setTimeStamp(long newStamp) {
7702 if (newStamp != timeStamp) {
7703 timeStamp = newStamp;
7704 timeStampString = Long.toString(newStamp);
7705 }
7706 }
7707
7708 public void setTimeStamp(long newStamp, String newStampStr) {
7709 timeStamp = newStamp;
7710 timeStampString = newStampStr;
7711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007713 public long getTimeStamp() {
7714 return timeStamp;
7715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717 public String getTimeStampStr() {
7718 return timeStampString;
7719 }
7720
7721 public void copyFrom(PackageSettingBase base) {
7722 grantedPermissions = base.grantedPermissions;
7723 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007725 timeStamp = base.timeStamp;
7726 timeStampString = base.timeStampString;
7727 signatures = base.signatures;
7728 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007729 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 disabledComponents = base.disabledComponents;
7731 enabledComponents = base.enabledComponents;
7732 enabled = base.enabled;
7733 installStatus = base.installStatus;
7734 }
7735
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007736 boolean enableComponentLP(String componentClassName) {
7737 boolean changed = disabledComponents.remove(componentClassName);
7738 changed |= enabledComponents.add(componentClassName);
7739 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 }
7741
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007742 boolean disableComponentLP(String componentClassName) {
7743 boolean changed = enabledComponents.remove(componentClassName);
7744 changed |= disabledComponents.add(componentClassName);
7745 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007746 }
7747
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007748 boolean restoreComponentLP(String componentClassName) {
7749 boolean changed = enabledComponents.remove(componentClassName);
7750 changed |= disabledComponents.remove(componentClassName);
7751 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007752 }
7753
7754 int currentEnabledStateLP(String componentName) {
7755 if (enabledComponents.contains(componentName)) {
7756 return COMPONENT_ENABLED_STATE_ENABLED;
7757 } else if (disabledComponents.contains(componentName)) {
7758 return COMPONENT_ENABLED_STATE_DISABLED;
7759 } else {
7760 return COMPONENT_ENABLED_STATE_DEFAULT;
7761 }
7762 }
7763 }
7764
7765 /**
7766 * Settings data for a particular package we know about.
7767 */
7768 static final class PackageSetting extends PackageSettingBase {
7769 int userId;
7770 PackageParser.Package pkg;
7771 SharedUserSetting sharedUser;
7772
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007773 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007774 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007775 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007778 @Override
7779 public String toString() {
7780 return "PackageSetting{"
7781 + Integer.toHexString(System.identityHashCode(this))
7782 + " " + name + "/" + userId + "}";
7783 }
7784 }
7785
7786 /**
7787 * Settings data for a particular shared user ID we know about.
7788 */
7789 static final class SharedUserSetting extends GrantedPermissions {
7790 final String name;
7791 int userId;
7792 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7793 final PackageSignatures signatures = new PackageSignatures();
7794
7795 SharedUserSetting(String _name, int _pkgFlags) {
7796 super(_pkgFlags);
7797 name = _name;
7798 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 @Override
7801 public String toString() {
7802 return "SharedUserSetting{"
7803 + Integer.toHexString(System.identityHashCode(this))
7804 + " " + name + "/" + userId + "}";
7805 }
7806 }
7807
7808 /**
7809 * Holds information about dynamic settings.
7810 */
7811 private static final class Settings {
7812 private final File mSettingsFilename;
7813 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007814 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 private final HashMap<String, PackageSetting> mPackages =
7816 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 // List of replaced system applications
7818 final HashMap<String, PackageSetting> mDisabledSysPackages =
7819 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007820
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007821 // These are the last platform API version we were using for
7822 // the apps installed on internal and external storage. It is
7823 // used to grant newer permissions one time during a system upgrade.
7824 int mInternalSdkPlatform;
7825 int mExternalSdkPlatform;
7826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 // The user's preferred activities associated with particular intent
7828 // filters.
7829 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7830 new IntentResolver<PreferredActivity, PreferredActivity>() {
7831 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007832 protected String packageForFilter(PreferredActivity filter) {
7833 return filter.mActivity.getPackageName();
7834 }
7835 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007836 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007837 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007838 out.print(prefix); out.print(
7839 Integer.toHexString(System.identityHashCode(filter)));
7840 out.print(' ');
7841 out.print(filter.mActivity.flattenToShortString());
7842 out.print(" match=0x");
7843 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007845 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007847 out.print(prefix); out.print(" ");
7848 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 }
7850 }
7851 }
7852 };
7853 private final HashMap<String, SharedUserSetting> mSharedUsers =
7854 new HashMap<String, SharedUserSetting>();
7855 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7856 private final SparseArray<Object> mOtherUserIds =
7857 new SparseArray<Object>();
7858
7859 // For reading/writing settings file.
7860 private final ArrayList<Signature> mPastSignatures =
7861 new ArrayList<Signature>();
7862
7863 // Mapping from permission names to info about them.
7864 final HashMap<String, BasePermission> mPermissions =
7865 new HashMap<String, BasePermission>();
7866
7867 // Mapping from permission tree names to info about them.
7868 final HashMap<String, BasePermission> mPermissionTrees =
7869 new HashMap<String, BasePermission>();
7870
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007871 // Packages that have been uninstalled and still need their external
7872 // storage data deleted.
7873 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7874
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007875 // Packages that have been renamed since they were first installed.
7876 // Keys are the new names of the packages, values are the original
7877 // names. The packages appear everwhere else under their original
7878 // names.
7879 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007881 private final StringBuilder mReadMessages = new StringBuilder();
7882
7883 private static final class PendingPackage extends PackageSettingBase {
7884 final int sharedId;
7885
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007886 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007887 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007888 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 this.sharedId = sharedId;
7890 }
7891 }
7892 private final ArrayList<PendingPackage> mPendingPackages
7893 = new ArrayList<PendingPackage>();
7894
7895 Settings() {
7896 File dataDir = Environment.getDataDirectory();
7897 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007898 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 systemDir.mkdirs();
7900 FileUtils.setPermissions(systemDir.toString(),
7901 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7902 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7903 -1, -1);
7904 mSettingsFilename = new File(systemDir, "packages.xml");
7905 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007906 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007907 }
7908
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007909 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007910 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007911 int pkgFlags, boolean create, boolean add) {
7912 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007913 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007914 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 return p;
7916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007917
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007918 PackageSetting peekPackageLP(String name) {
7919 return mPackages.get(name);
7920 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 PackageSetting p = mPackages.get(name);
7922 if (p != null && p.codePath.getPath().equals(codePath)) {
7923 return p;
7924 }
7925 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007926 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007929 void setInstallStatus(String pkgName, int status) {
7930 PackageSetting p = mPackages.get(pkgName);
7931 if(p != null) {
7932 if(p.getInstallStatus() != status) {
7933 p.setInstallStatus(status);
7934 }
7935 }
7936 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007937
Jacek Surazski65e13172009-04-28 15:26:38 +02007938 void setInstallerPackageName(String pkgName,
7939 String installerPkgName) {
7940 PackageSetting p = mPackages.get(pkgName);
7941 if(p != null) {
7942 p.setInstallerPackageName(installerPkgName);
7943 }
7944 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007945
Jacek Surazski65e13172009-04-28 15:26:38 +02007946 String getInstallerPackageName(String pkgName) {
7947 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007948 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007949 }
7950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007951 int getInstallStatus(String pkgName) {
7952 PackageSetting p = mPackages.get(pkgName);
7953 if(p != null) {
7954 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007956 return -1;
7957 }
7958
7959 SharedUserSetting getSharedUserLP(String name,
7960 int pkgFlags, boolean create) {
7961 SharedUserSetting s = mSharedUsers.get(name);
7962 if (s == null) {
7963 if (!create) {
7964 return null;
7965 }
7966 s = new SharedUserSetting(name, pkgFlags);
7967 if (MULTIPLE_APPLICATION_UIDS) {
7968 s.userId = newUserIdLP(s);
7969 } else {
7970 s.userId = FIRST_APPLICATION_UID;
7971 }
7972 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7973 // < 0 means we couldn't assign a userid; fall out and return
7974 // s, which is currently null
7975 if (s.userId >= 0) {
7976 mSharedUsers.put(name, s);
7977 }
7978 }
7979
7980 return s;
7981 }
7982
7983 int disableSystemPackageLP(String name) {
7984 PackageSetting p = mPackages.get(name);
7985 if(p == null) {
7986 Log.w(TAG, "Package:"+name+" is not an installed package");
7987 return -1;
7988 }
7989 PackageSetting dp = mDisabledSysPackages.get(name);
7990 // always make sure the system package code and resource paths dont change
7991 if(dp == null) {
7992 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7993 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7994 }
7995 mDisabledSysPackages.put(name, p);
7996 }
7997 return removePackageLP(name);
7998 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 PackageSetting enableSystemPackageLP(String name) {
8001 PackageSetting p = mDisabledSysPackages.get(name);
8002 if(p == null) {
8003 Log.w(TAG, "Package:"+name+" is not disabled");
8004 return null;
8005 }
8006 // Reset flag in ApplicationInfo object
8007 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8008 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8009 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008010 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008011 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 mDisabledSysPackages.remove(name);
8013 return ret;
8014 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008015
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008016 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008017 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008018 PackageSetting p = mPackages.get(name);
8019 if (p != null) {
8020 if (p.userId == uid) {
8021 return p;
8022 }
8023 reportSettingsProblem(Log.ERROR,
8024 "Adding duplicate package, keeping first: " + name);
8025 return null;
8026 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008027 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008028 p.userId = uid;
8029 if (addUserIdLP(uid, p, name)) {
8030 mPackages.put(name, p);
8031 return p;
8032 }
8033 return null;
8034 }
8035
8036 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8037 SharedUserSetting s = mSharedUsers.get(name);
8038 if (s != null) {
8039 if (s.userId == uid) {
8040 return s;
8041 }
8042 reportSettingsProblem(Log.ERROR,
8043 "Adding duplicate shared user, keeping first: " + name);
8044 return null;
8045 }
8046 s = new SharedUserSetting(name, pkgFlags);
8047 s.userId = uid;
8048 if (addUserIdLP(uid, s, name)) {
8049 mSharedUsers.put(name, s);
8050 return s;
8051 }
8052 return null;
8053 }
8054
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008055 // Transfer ownership of permissions from one package to another.
8056 private void transferPermissions(String origPkg, String newPkg) {
8057 // Transfer ownership of permissions to the new package.
8058 for (int i=0; i<2; i++) {
8059 HashMap<String, BasePermission> permissions =
8060 i == 0 ? mPermissionTrees : mPermissions;
8061 for (BasePermission bp : permissions.values()) {
8062 if (origPkg.equals(bp.sourcePackage)) {
8063 if (DEBUG_UPGRADE) Log.v(TAG,
8064 "Moving permission " + bp.name
8065 + " from pkg " + bp.sourcePackage
8066 + " to " + newPkg);
8067 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008068 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008069 bp.perm = null;
8070 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008071 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008072 }
8073 bp.uid = 0;
8074 bp.gids = null;
8075 }
8076 }
8077 }
8078 }
8079
8080 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008081 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008082 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 PackageSetting p = mPackages.get(name);
8084 if (p != null) {
8085 if (!p.codePath.equals(codePath)) {
8086 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008087 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008088 // This is an updated system app with versions in both system
8089 // and data partition. Just let the most recent version
8090 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008091 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008092 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008093 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008094 // Just a change in the code path is not an issue, but
8095 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008096 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008097 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008098 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008099 }
8100 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008101 reportSettingsProblem(Log.WARN,
8102 "Package " + name + " shared user changed from "
8103 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8104 + " to "
8105 + (sharedUser != null ? sharedUser.name : "<nothing>")
8106 + "; replacing with new");
8107 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008108 } else {
8109 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8110 // If what we are scanning is a system package, then
8111 // make it so, regardless of whether it was previously
8112 // installed only in the data partition.
8113 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008115 }
8116 }
8117 if (p == null) {
8118 // Create a new PackageSettings entry. this can end up here because
8119 // of code path mismatch or user id mismatch of an updated system partition
8120 if (!create) {
8121 return null;
8122 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008123 if (origPackage != null) {
8124 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008125 p = new PackageSetting(origPackage.name, name, codePath,
8126 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008127 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8128 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008129 // Note that we will retain the new package's signature so
8130 // that we can keep its data.
8131 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008132 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008133 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008134 p.sharedUser = origPackage.sharedUser;
8135 p.userId = origPackage.userId;
8136 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008137 mRenamedPackages.put(name, origPackage.name);
8138 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008139 // Update new package state.
8140 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008142 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008143 p.setTimeStamp(codePath.lastModified());
8144 p.sharedUser = sharedUser;
8145 if (sharedUser != null) {
8146 p.userId = sharedUser.userId;
8147 } else if (MULTIPLE_APPLICATION_UIDS) {
8148 // Clone the setting here for disabled system packages
8149 PackageSetting dis = mDisabledSysPackages.get(name);
8150 if (dis != null) {
8151 // For disabled packages a new setting is created
8152 // from the existing user id. This still has to be
8153 // added to list of user id's
8154 // Copy signatures from previous setting
8155 if (dis.signatures.mSignatures != null) {
8156 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8157 }
8158 p.userId = dis.userId;
8159 // Clone permissions
8160 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008161 // Clone component info
8162 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8163 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8164 // Add new setting to list of user ids
8165 addUserIdLP(p.userId, p, name);
8166 } else {
8167 // Assign new user id
8168 p.userId = newUserIdLP(p);
8169 }
8170 } else {
8171 p.userId = FIRST_APPLICATION_UID;
8172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 }
8174 if (p.userId < 0) {
8175 reportSettingsProblem(Log.WARN,
8176 "Package " + name + " could not be assigned a valid uid");
8177 return null;
8178 }
8179 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008180 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008181 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008182 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008183 }
8184 }
8185 return p;
8186 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008187
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008188 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008189 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008190 String codePath = pkg.applicationInfo.sourceDir;
8191 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008192 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008193 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008194 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008195 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008196 p.codePath = new File(codePath);
8197 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008198 }
8199 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008200 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008201 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008202 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008203 p.resourcePath = new File(resourcePath);
8204 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008205 }
8206 // Update version code if needed
8207 if (pkg.mVersionCode != p.versionCode) {
8208 p.versionCode = pkg.mVersionCode;
8209 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008210 // Update signatures if needed.
8211 if (p.signatures.mSignatures == null) {
8212 p.signatures.assignSignatures(pkg.mSignatures);
8213 }
8214 // If this app defines a shared user id initialize
8215 // the shared user signatures as well.
8216 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8217 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8218 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008219 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8220 }
8221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 // Utility method that adds a PackageSetting to mPackages and
8223 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008224 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 SharedUserSetting sharedUser) {
8226 mPackages.put(name, p);
8227 if (sharedUser != null) {
8228 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8229 reportSettingsProblem(Log.ERROR,
8230 "Package " + p.name + " was user "
8231 + p.sharedUser + " but is now " + sharedUser
8232 + "; I am not changing its files so it will probably fail!");
8233 p.sharedUser.packages.remove(p);
8234 } else if (p.userId != sharedUser.userId) {
8235 reportSettingsProblem(Log.ERROR,
8236 "Package " + p.name + " was user id " + p.userId
8237 + " but is now user " + sharedUser
8238 + " with id " + sharedUser.userId
8239 + "; I am not changing its files so it will probably fail!");
8240 }
8241
8242 sharedUser.packages.add(p);
8243 p.sharedUser = sharedUser;
8244 p.userId = sharedUser.userId;
8245 }
8246 }
8247
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008248 /*
8249 * Update the shared user setting when a package using
8250 * specifying the shared user id is removed. The gids
8251 * associated with each permission of the deleted package
8252 * are removed from the shared user's gid list only if its
8253 * not in use by other permissions of packages in the
8254 * shared user setting.
8255 */
8256 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008257 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008258 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 return;
8260 }
8261 // No sharedUserId
8262 if (deletedPs.sharedUser == null) {
8263 return;
8264 }
8265 SharedUserSetting sus = deletedPs.sharedUser;
8266 // Update permissions
8267 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8268 boolean used = false;
8269 if (!sus.grantedPermissions.contains (eachPerm)) {
8270 continue;
8271 }
8272 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008273 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008274 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008275 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 used = true;
8277 break;
8278 }
8279 }
8280 if (!used) {
8281 // can safely delete this permission from list
8282 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283 }
8284 }
8285 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008286 int newGids[] = globalGids;
8287 for (String eachPerm : sus.grantedPermissions) {
8288 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008289 if (bp != null) {
8290 newGids = appendInts(newGids, bp.gids);
8291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008292 }
8293 sus.gids = newGids;
8294 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 private int removePackageLP(String name) {
8297 PackageSetting p = mPackages.get(name);
8298 if (p != null) {
8299 mPackages.remove(name);
8300 if (p.sharedUser != null) {
8301 p.sharedUser.packages.remove(p);
8302 if (p.sharedUser.packages.size() == 0) {
8303 mSharedUsers.remove(p.sharedUser.name);
8304 removeUserIdLP(p.sharedUser.userId);
8305 return p.sharedUser.userId;
8306 }
8307 } else {
8308 removeUserIdLP(p.userId);
8309 return p.userId;
8310 }
8311 }
8312 return -1;
8313 }
8314
8315 private boolean addUserIdLP(int uid, Object obj, Object name) {
8316 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8317 return false;
8318 }
8319
8320 if (uid >= FIRST_APPLICATION_UID) {
8321 int N = mUserIds.size();
8322 final int index = uid - FIRST_APPLICATION_UID;
8323 while (index >= N) {
8324 mUserIds.add(null);
8325 N++;
8326 }
8327 if (mUserIds.get(index) != null) {
8328 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008329 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008330 + " name=" + name);
8331 return false;
8332 }
8333 mUserIds.set(index, obj);
8334 } else {
8335 if (mOtherUserIds.get(uid) != null) {
8336 reportSettingsProblem(Log.ERROR,
8337 "Adding duplicate shared id: " + uid
8338 + " name=" + name);
8339 return false;
8340 }
8341 mOtherUserIds.put(uid, obj);
8342 }
8343 return true;
8344 }
8345
8346 public Object getUserIdLP(int uid) {
8347 if (uid >= FIRST_APPLICATION_UID) {
8348 int N = mUserIds.size();
8349 final int index = uid - FIRST_APPLICATION_UID;
8350 return index < N ? mUserIds.get(index) : null;
8351 } else {
8352 return mOtherUserIds.get(uid);
8353 }
8354 }
8355
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008356 private Set<String> findPackagesWithFlag(int flag) {
8357 Set<String> ret = new HashSet<String>();
8358 for (PackageSetting ps : mPackages.values()) {
8359 // Has to match atleast all the flag bits set on flag
8360 if ((ps.pkgFlags & flag) == flag) {
8361 ret.add(ps.name);
8362 }
8363 }
8364 return ret;
8365 }
8366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008367 private void removeUserIdLP(int uid) {
8368 if (uid >= FIRST_APPLICATION_UID) {
8369 int N = mUserIds.size();
8370 final int index = uid - FIRST_APPLICATION_UID;
8371 if (index < N) mUserIds.set(index, null);
8372 } else {
8373 mOtherUserIds.remove(uid);
8374 }
8375 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008377 void writeLP() {
8378 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8379
8380 // Keep the old settings around until we know the new ones have
8381 // been successfully written.
8382 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008383 // Presence of backup settings file indicates that we failed
8384 // to persist settings earlier. So preserve the older
8385 // backup for future reference since the current settings
8386 // might have been corrupted.
8387 if (!mBackupSettingsFilename.exists()) {
8388 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008389 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008390 return;
8391 }
8392 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008393 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008394 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008396 }
8397
8398 mPastSignatures.clear();
8399
8400 try {
8401 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8402
8403 //XmlSerializer serializer = XmlUtils.serializerInstance();
8404 XmlSerializer serializer = new FastXmlSerializer();
8405 serializer.setOutput(str, "utf-8");
8406 serializer.startDocument(null, true);
8407 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8408
8409 serializer.startTag(null, "packages");
8410
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008411 serializer.startTag(null, "last-platform-version");
8412 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8413 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8414 serializer.endTag(null, "last-platform-version");
8415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416 serializer.startTag(null, "permission-trees");
8417 for (BasePermission bp : mPermissionTrees.values()) {
8418 writePermission(serializer, bp);
8419 }
8420 serializer.endTag(null, "permission-trees");
8421
8422 serializer.startTag(null, "permissions");
8423 for (BasePermission bp : mPermissions.values()) {
8424 writePermission(serializer, bp);
8425 }
8426 serializer.endTag(null, "permissions");
8427
8428 for (PackageSetting pkg : mPackages.values()) {
8429 writePackage(serializer, pkg);
8430 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008432 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8433 writeDisabledSysPackage(serializer, pkg);
8434 }
8435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008436 serializer.startTag(null, "preferred-activities");
8437 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8438 serializer.startTag(null, "item");
8439 pa.writeToXml(serializer);
8440 serializer.endTag(null, "item");
8441 }
8442 serializer.endTag(null, "preferred-activities");
8443
8444 for (SharedUserSetting usr : mSharedUsers.values()) {
8445 serializer.startTag(null, "shared-user");
8446 serializer.attribute(null, "name", usr.name);
8447 serializer.attribute(null, "userId",
8448 Integer.toString(usr.userId));
8449 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8450 serializer.startTag(null, "perms");
8451 for (String name : usr.grantedPermissions) {
8452 serializer.startTag(null, "item");
8453 serializer.attribute(null, "name", name);
8454 serializer.endTag(null, "item");
8455 }
8456 serializer.endTag(null, "perms");
8457 serializer.endTag(null, "shared-user");
8458 }
8459
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008460 if (mPackagesToBeCleaned.size() > 0) {
8461 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8462 serializer.startTag(null, "cleaning-package");
8463 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8464 serializer.endTag(null, "cleaning-package");
8465 }
8466 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008467
8468 if (mRenamedPackages.size() > 0) {
8469 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8470 serializer.startTag(null, "renamed-package");
8471 serializer.attribute(null, "new", e.getKey());
8472 serializer.attribute(null, "old", e.getValue());
8473 serializer.endTag(null, "renamed-package");
8474 }
8475 }
8476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008477 serializer.endTag(null, "packages");
8478
8479 serializer.endDocument();
8480
8481 str.flush();
8482 str.close();
8483
8484 // New settings successfully written, old ones are no longer
8485 // needed.
8486 mBackupSettingsFilename.delete();
8487 FileUtils.setPermissions(mSettingsFilename.toString(),
8488 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8489 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8490 |FileUtils.S_IROTH,
8491 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008492
8493 // Write package list file now, use a JournaledFile.
8494 //
8495 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8496 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8497
8498 str = new FileOutputStream(journal.chooseForWrite());
8499 try {
8500 StringBuilder sb = new StringBuilder();
8501 for (PackageSetting pkg : mPackages.values()) {
8502 ApplicationInfo ai = pkg.pkg.applicationInfo;
8503 String dataPath = ai.dataDir;
8504 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8505
8506 // Avoid any application that has a space in its path
8507 // or that is handled by the system.
8508 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8509 continue;
8510
8511 // we store on each line the following information for now:
8512 //
8513 // pkgName - package name
8514 // userId - application-specific user id
8515 // debugFlag - 0 or 1 if the package is debuggable.
8516 // dataPath - path to package's data path
8517 //
8518 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8519 //
8520 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8521 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8522 // system/core/run-as/run-as.c
8523 //
8524 sb.setLength(0);
8525 sb.append(ai.packageName);
8526 sb.append(" ");
8527 sb.append((int)ai.uid);
8528 sb.append(isDebug ? " 1 " : " 0 ");
8529 sb.append(dataPath);
8530 sb.append("\n");
8531 str.write(sb.toString().getBytes());
8532 }
8533 str.flush();
8534 str.close();
8535 journal.commit();
8536 }
8537 catch (Exception e) {
8538 journal.rollback();
8539 }
8540
8541 FileUtils.setPermissions(mPackageListFilename.toString(),
8542 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8543 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8544 |FileUtils.S_IROTH,
8545 -1, -1);
8546
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008547 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008548
8549 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008550 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 -08008551 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008552 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 -08008553 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008554 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008555 if (mSettingsFilename.exists()) {
8556 if (!mSettingsFilename.delete()) {
8557 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8558 }
8559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008560 //Debug.stopMethodTracing();
8561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008562
8563 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008564 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 serializer.startTag(null, "updated-package");
8566 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008567 if (pkg.realName != null) {
8568 serializer.attribute(null, "realName", pkg.realName);
8569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008570 serializer.attribute(null, "codePath", pkg.codePathString);
8571 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008572 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8574 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8575 }
8576 if (pkg.sharedUser == null) {
8577 serializer.attribute(null, "userId",
8578 Integer.toString(pkg.userId));
8579 } else {
8580 serializer.attribute(null, "sharedUserId",
8581 Integer.toString(pkg.userId));
8582 }
8583 serializer.startTag(null, "perms");
8584 if (pkg.sharedUser == null) {
8585 // If this is a shared user, the permissions will
8586 // be written there. We still need to write an
8587 // empty permissions list so permissionsFixed will
8588 // be set.
8589 for (final String name : pkg.grantedPermissions) {
8590 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008591 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 // We only need to write signature or system permissions but this wont
8593 // match the semantics of grantedPermissions. So write all permissions.
8594 serializer.startTag(null, "item");
8595 serializer.attribute(null, "name", name);
8596 serializer.endTag(null, "item");
8597 }
8598 }
8599 }
8600 serializer.endTag(null, "perms");
8601 serializer.endTag(null, "updated-package");
8602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008603
8604 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008605 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008606 serializer.startTag(null, "package");
8607 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008608 if (pkg.realName != null) {
8609 serializer.attribute(null, "realName", pkg.realName);
8610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 serializer.attribute(null, "codePath", pkg.codePathString);
8612 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8613 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8614 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008615 serializer.attribute(null, "flags",
8616 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008617 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008618 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008619 if (pkg.sharedUser == null) {
8620 serializer.attribute(null, "userId",
8621 Integer.toString(pkg.userId));
8622 } else {
8623 serializer.attribute(null, "sharedUserId",
8624 Integer.toString(pkg.userId));
8625 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008626 if (pkg.uidError) {
8627 serializer.attribute(null, "uidError", "true");
8628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8630 serializer.attribute(null, "enabled",
8631 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8632 ? "true" : "false");
8633 }
8634 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8635 serializer.attribute(null, "installStatus", "false");
8636 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008637 if (pkg.installerPackageName != null) {
8638 serializer.attribute(null, "installer", pkg.installerPackageName);
8639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8641 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8642 serializer.startTag(null, "perms");
8643 if (pkg.sharedUser == null) {
8644 // If this is a shared user, the permissions will
8645 // be written there. We still need to write an
8646 // empty permissions list so permissionsFixed will
8647 // be set.
8648 for (final String name : pkg.grantedPermissions) {
8649 serializer.startTag(null, "item");
8650 serializer.attribute(null, "name", name);
8651 serializer.endTag(null, "item");
8652 }
8653 }
8654 serializer.endTag(null, "perms");
8655 }
8656 if (pkg.disabledComponents.size() > 0) {
8657 serializer.startTag(null, "disabled-components");
8658 for (final String name : pkg.disabledComponents) {
8659 serializer.startTag(null, "item");
8660 serializer.attribute(null, "name", name);
8661 serializer.endTag(null, "item");
8662 }
8663 serializer.endTag(null, "disabled-components");
8664 }
8665 if (pkg.enabledComponents.size() > 0) {
8666 serializer.startTag(null, "enabled-components");
8667 for (final String name : pkg.enabledComponents) {
8668 serializer.startTag(null, "item");
8669 serializer.attribute(null, "name", name);
8670 serializer.endTag(null, "item");
8671 }
8672 serializer.endTag(null, "enabled-components");
8673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008675 serializer.endTag(null, "package");
8676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 void writePermission(XmlSerializer serializer, BasePermission bp)
8679 throws XmlPullParserException, java.io.IOException {
8680 if (bp.type != BasePermission.TYPE_BUILTIN
8681 && bp.sourcePackage != null) {
8682 serializer.startTag(null, "item");
8683 serializer.attribute(null, "name", bp.name);
8684 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008685 if (bp.protectionLevel !=
8686 PermissionInfo.PROTECTION_NORMAL) {
8687 serializer.attribute(null, "protection",
8688 Integer.toString(bp.protectionLevel));
8689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690 if (DEBUG_SETTINGS) Log.v(TAG,
8691 "Writing perm: name=" + bp.name + " type=" + bp.type);
8692 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8693 PermissionInfo pi = bp.perm != null ? bp.perm.info
8694 : bp.pendingInfo;
8695 if (pi != null) {
8696 serializer.attribute(null, "type", "dynamic");
8697 if (pi.icon != 0) {
8698 serializer.attribute(null, "icon",
8699 Integer.toString(pi.icon));
8700 }
8701 if (pi.nonLocalizedLabel != null) {
8702 serializer.attribute(null, "label",
8703 pi.nonLocalizedLabel.toString());
8704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008705 }
8706 }
8707 serializer.endTag(null, "item");
8708 }
8709 }
8710
8711 String getReadMessagesLP() {
8712 return mReadMessages.toString();
8713 }
8714
Oscar Montemayora8529f62009-11-18 10:14:20 -08008715 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8717 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008718 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719 while(its.hasNext()) {
8720 String key = its.next();
8721 PackageSetting ps = mPackages.get(key);
8722 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008723 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008724 }
8725 }
8726 return ret;
8727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008729 boolean readLP() {
8730 FileInputStream str = null;
8731 if (mBackupSettingsFilename.exists()) {
8732 try {
8733 str = new FileInputStream(mBackupSettingsFilename);
8734 mReadMessages.append("Reading from backup settings file\n");
8735 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008736 if (mSettingsFilename.exists()) {
8737 // If both the backup and settings file exist, we
8738 // ignore the settings since it might have been
8739 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008740 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008741 mSettingsFilename.delete();
8742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008743 } catch (java.io.IOException e) {
8744 // We'll try for the normal settings file.
8745 }
8746 }
8747
8748 mPastSignatures.clear();
8749
8750 try {
8751 if (str == null) {
8752 if (!mSettingsFilename.exists()) {
8753 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008754 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008755 return false;
8756 }
8757 str = new FileInputStream(mSettingsFilename);
8758 }
8759 XmlPullParser parser = Xml.newPullParser();
8760 parser.setInput(str, null);
8761
8762 int type;
8763 while ((type=parser.next()) != XmlPullParser.START_TAG
8764 && type != XmlPullParser.END_DOCUMENT) {
8765 ;
8766 }
8767
8768 if (type != XmlPullParser.START_TAG) {
8769 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008770 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 return false;
8772 }
8773
8774 int outerDepth = parser.getDepth();
8775 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8776 && (type != XmlPullParser.END_TAG
8777 || parser.getDepth() > outerDepth)) {
8778 if (type == XmlPullParser.END_TAG
8779 || type == XmlPullParser.TEXT) {
8780 continue;
8781 }
8782
8783 String tagName = parser.getName();
8784 if (tagName.equals("package")) {
8785 readPackageLP(parser);
8786 } else if (tagName.equals("permissions")) {
8787 readPermissionsLP(mPermissions, parser);
8788 } else if (tagName.equals("permission-trees")) {
8789 readPermissionsLP(mPermissionTrees, parser);
8790 } else if (tagName.equals("shared-user")) {
8791 readSharedUserLP(parser);
8792 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008793 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794 } else if (tagName.equals("preferred-activities")) {
8795 readPreferredActivitiesLP(parser);
8796 } else if(tagName.equals("updated-package")) {
8797 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008798 } else if (tagName.equals("cleaning-package")) {
8799 String name = parser.getAttributeValue(null, "name");
8800 if (name != null) {
8801 mPackagesToBeCleaned.add(name);
8802 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008803 } else if (tagName.equals("renamed-package")) {
8804 String nname = parser.getAttributeValue(null, "new");
8805 String oname = parser.getAttributeValue(null, "old");
8806 if (nname != null && oname != null) {
8807 mRenamedPackages.put(nname, oname);
8808 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008809 } else if (tagName.equals("last-platform-version")) {
8810 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8811 try {
8812 String internal = parser.getAttributeValue(null, "internal");
8813 if (internal != null) {
8814 mInternalSdkPlatform = Integer.parseInt(internal);
8815 }
8816 String external = parser.getAttributeValue(null, "external");
8817 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008818 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008819 }
8820 } catch (NumberFormatException e) {
8821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008822 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008823 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008824 + parser.getName());
8825 XmlUtils.skipCurrentTag(parser);
8826 }
8827 }
8828
8829 str.close();
8830
8831 } catch(XmlPullParserException e) {
8832 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008833 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008834
8835 } catch(java.io.IOException e) {
8836 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008837 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008838
8839 }
8840
8841 int N = mPendingPackages.size();
8842 for (int i=0; i<N; i++) {
8843 final PendingPackage pp = mPendingPackages.get(i);
8844 Object idObj = getUserIdLP(pp.sharedId);
8845 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008846 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008847 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008848 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008849 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008850 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008851 + pp.name);
8852 continue;
8853 }
8854 p.copyFrom(pp);
8855 } else if (idObj != null) {
8856 String msg = "Bad package setting: package " + pp.name
8857 + " has shared uid " + pp.sharedId
8858 + " that is not a shared uid\n";
8859 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008860 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861 } else {
8862 String msg = "Bad package setting: package " + pp.name
8863 + " has shared uid " + pp.sharedId
8864 + " that is not defined\n";
8865 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008866 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 }
8868 }
8869 mPendingPackages.clear();
8870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008871 mReadMessages.append("Read completed successfully: "
8872 + mPackages.size() + " packages, "
8873 + mSharedUsers.size() + " shared uids\n");
8874
8875 return true;
8876 }
8877
8878 private int readInt(XmlPullParser parser, String ns, String name,
8879 int defValue) {
8880 String v = parser.getAttributeValue(ns, name);
8881 try {
8882 if (v == null) {
8883 return defValue;
8884 }
8885 return Integer.parseInt(v);
8886 } catch (NumberFormatException e) {
8887 reportSettingsProblem(Log.WARN,
8888 "Error in package manager settings: attribute " +
8889 name + " has bad integer value " + v + " at "
8890 + parser.getPositionDescription());
8891 }
8892 return defValue;
8893 }
8894
8895 private void readPermissionsLP(HashMap<String, BasePermission> out,
8896 XmlPullParser parser)
8897 throws IOException, XmlPullParserException {
8898 int outerDepth = parser.getDepth();
8899 int type;
8900 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8901 && (type != XmlPullParser.END_TAG
8902 || parser.getDepth() > outerDepth)) {
8903 if (type == XmlPullParser.END_TAG
8904 || type == XmlPullParser.TEXT) {
8905 continue;
8906 }
8907
8908 String tagName = parser.getName();
8909 if (tagName.equals("item")) {
8910 String name = parser.getAttributeValue(null, "name");
8911 String sourcePackage = parser.getAttributeValue(null, "package");
8912 String ptype = parser.getAttributeValue(null, "type");
8913 if (name != null && sourcePackage != null) {
8914 boolean dynamic = "dynamic".equals(ptype);
8915 BasePermission bp = new BasePermission(name, sourcePackage,
8916 dynamic
8917 ? BasePermission.TYPE_DYNAMIC
8918 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008919 bp.protectionLevel = readInt(parser, null, "protection",
8920 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008921 if (dynamic) {
8922 PermissionInfo pi = new PermissionInfo();
8923 pi.packageName = sourcePackage.intern();
8924 pi.name = name.intern();
8925 pi.icon = readInt(parser, null, "icon", 0);
8926 pi.nonLocalizedLabel = parser.getAttributeValue(
8927 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008928 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008929 bp.pendingInfo = pi;
8930 }
8931 out.put(bp.name, bp);
8932 } else {
8933 reportSettingsProblem(Log.WARN,
8934 "Error in package manager settings: permissions has"
8935 + " no name at " + parser.getPositionDescription());
8936 }
8937 } else {
8938 reportSettingsProblem(Log.WARN,
8939 "Unknown element reading permissions: "
8940 + parser.getName() + " at "
8941 + parser.getPositionDescription());
8942 }
8943 XmlUtils.skipCurrentTag(parser);
8944 }
8945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008948 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008950 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008951 String codePathStr = parser.getAttributeValue(null, "codePath");
8952 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008953 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008954 resourcePathStr = codePathStr;
8955 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008956 String version = parser.getAttributeValue(null, "version");
8957 int versionCode = 0;
8958 if (version != null) {
8959 try {
8960 versionCode = Integer.parseInt(version);
8961 } catch (NumberFormatException e) {
8962 }
8963 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 int pkgFlags = 0;
8966 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008967 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008968 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008969 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008970 String timeStampStr = parser.getAttributeValue(null, "ts");
8971 if (timeStampStr != null) {
8972 try {
8973 long timeStamp = Long.parseLong(timeStampStr);
8974 ps.setTimeStamp(timeStamp, timeStampStr);
8975 } catch (NumberFormatException e) {
8976 }
8977 }
8978 String idStr = parser.getAttributeValue(null, "userId");
8979 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8980 if(ps.userId <= 0) {
8981 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8982 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8983 }
8984 int outerDepth = parser.getDepth();
8985 int type;
8986 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8987 && (type != XmlPullParser.END_TAG
8988 || parser.getDepth() > outerDepth)) {
8989 if (type == XmlPullParser.END_TAG
8990 || type == XmlPullParser.TEXT) {
8991 continue;
8992 }
8993
8994 String tagName = parser.getName();
8995 if (tagName.equals("perms")) {
8996 readGrantedPermissionsLP(parser,
8997 ps.grantedPermissions);
8998 } else {
8999 reportSettingsProblem(Log.WARN,
9000 "Unknown element under <updated-package>: "
9001 + parser.getName());
9002 XmlUtils.skipCurrentTag(parser);
9003 }
9004 }
9005 mDisabledSysPackages.put(name, ps);
9006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009008 private void readPackageLP(XmlPullParser parser)
9009 throws XmlPullParserException, IOException {
9010 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009011 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012 String idStr = null;
9013 String sharedIdStr = null;
9014 String codePathStr = null;
9015 String resourcePathStr = null;
9016 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009017 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009018 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009019 int pkgFlags = 0;
9020 String timeStampStr;
9021 long timeStamp = 0;
9022 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009023 String version = null;
9024 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 try {
9026 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009027 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009029 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009030 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9031 codePathStr = parser.getAttributeValue(null, "codePath");
9032 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009033 version = parser.getAttributeValue(null, "version");
9034 if (version != null) {
9035 try {
9036 versionCode = Integer.parseInt(version);
9037 } catch (NumberFormatException e) {
9038 }
9039 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009040 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009041
9042 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009043 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009044 try {
9045 pkgFlags = Integer.parseInt(systemStr);
9046 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009047 }
9048 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009049 // For backward compatibility
9050 systemStr = parser.getAttributeValue(null, "system");
9051 if (systemStr != null) {
9052 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9053 } else {
9054 // Old settings that don't specify system... just treat
9055 // them as system, good enough.
9056 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009058 }
9059 timeStampStr = parser.getAttributeValue(null, "ts");
9060 if (timeStampStr != null) {
9061 try {
9062 timeStamp = Long.parseLong(timeStampStr);
9063 } catch (NumberFormatException e) {
9064 }
9065 }
9066 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9067 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9068 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9069 if (resourcePathStr == null) {
9070 resourcePathStr = codePathStr;
9071 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009072 if (realName != null) {
9073 realName = realName.intern();
9074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009075 if (name == null) {
9076 reportSettingsProblem(Log.WARN,
9077 "Error in package manager settings: <package> has no name at "
9078 + parser.getPositionDescription());
9079 } else if (codePathStr == null) {
9080 reportSettingsProblem(Log.WARN,
9081 "Error in package manager settings: <package> has no codePath at "
9082 + parser.getPositionDescription());
9083 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009084 packageSetting = addPackageLP(name.intern(), realName,
9085 new File(codePathStr), new File(resourcePathStr),
9086 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009087 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9088 + ": userId=" + userId + " pkg=" + packageSetting);
9089 if (packageSetting == null) {
9090 reportSettingsProblem(Log.ERROR,
9091 "Failure adding uid " + userId
9092 + " while parsing settings at "
9093 + parser.getPositionDescription());
9094 } else {
9095 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9096 }
9097 } else if (sharedIdStr != null) {
9098 userId = sharedIdStr != null
9099 ? Integer.parseInt(sharedIdStr) : 0;
9100 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009101 packageSetting = new PendingPackage(name.intern(), realName,
9102 new File(codePathStr), new File(resourcePathStr),
9103 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009104 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9105 mPendingPackages.add((PendingPackage) packageSetting);
9106 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9107 + ": sharedUserId=" + userId + " pkg="
9108 + packageSetting);
9109 } else {
9110 reportSettingsProblem(Log.WARN,
9111 "Error in package manager settings: package "
9112 + name + " has bad sharedId " + sharedIdStr
9113 + " at " + parser.getPositionDescription());
9114 }
9115 } else {
9116 reportSettingsProblem(Log.WARN,
9117 "Error in package manager settings: package "
9118 + name + " has bad userId " + idStr + " at "
9119 + parser.getPositionDescription());
9120 }
9121 } catch (NumberFormatException e) {
9122 reportSettingsProblem(Log.WARN,
9123 "Error in package manager settings: package "
9124 + name + " has bad userId " + idStr + " at "
9125 + parser.getPositionDescription());
9126 }
9127 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009128 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009129 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009130 final String enabledStr = parser.getAttributeValue(null, "enabled");
9131 if (enabledStr != null) {
9132 if (enabledStr.equalsIgnoreCase("true")) {
9133 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9134 } else if (enabledStr.equalsIgnoreCase("false")) {
9135 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9136 } else if (enabledStr.equalsIgnoreCase("default")) {
9137 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9138 } else {
9139 reportSettingsProblem(Log.WARN,
9140 "Error in package manager settings: package "
9141 + name + " has bad enabled value: " + idStr
9142 + " at " + parser.getPositionDescription());
9143 }
9144 } else {
9145 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9146 }
9147 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9148 if (installStatusStr != null) {
9149 if (installStatusStr.equalsIgnoreCase("false")) {
9150 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9151 } else {
9152 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9153 }
9154 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009156 int outerDepth = parser.getDepth();
9157 int type;
9158 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9159 && (type != XmlPullParser.END_TAG
9160 || parser.getDepth() > outerDepth)) {
9161 if (type == XmlPullParser.END_TAG
9162 || type == XmlPullParser.TEXT) {
9163 continue;
9164 }
9165
9166 String tagName = parser.getName();
9167 if (tagName.equals("disabled-components")) {
9168 readDisabledComponentsLP(packageSetting, parser);
9169 } else if (tagName.equals("enabled-components")) {
9170 readEnabledComponentsLP(packageSetting, parser);
9171 } else if (tagName.equals("sigs")) {
9172 packageSetting.signatures.readXml(parser, mPastSignatures);
9173 } else if (tagName.equals("perms")) {
9174 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009175 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009176 packageSetting.permissionsFixed = true;
9177 } else {
9178 reportSettingsProblem(Log.WARN,
9179 "Unknown element under <package>: "
9180 + parser.getName());
9181 XmlUtils.skipCurrentTag(parser);
9182 }
9183 }
9184 } else {
9185 XmlUtils.skipCurrentTag(parser);
9186 }
9187 }
9188
9189 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9190 XmlPullParser parser)
9191 throws IOException, XmlPullParserException {
9192 int outerDepth = parser.getDepth();
9193 int type;
9194 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9195 && (type != XmlPullParser.END_TAG
9196 || parser.getDepth() > outerDepth)) {
9197 if (type == XmlPullParser.END_TAG
9198 || type == XmlPullParser.TEXT) {
9199 continue;
9200 }
9201
9202 String tagName = parser.getName();
9203 if (tagName.equals("item")) {
9204 String name = parser.getAttributeValue(null, "name");
9205 if (name != null) {
9206 packageSetting.disabledComponents.add(name.intern());
9207 } else {
9208 reportSettingsProblem(Log.WARN,
9209 "Error in package manager settings: <disabled-components> has"
9210 + " no name at " + parser.getPositionDescription());
9211 }
9212 } else {
9213 reportSettingsProblem(Log.WARN,
9214 "Unknown element under <disabled-components>: "
9215 + parser.getName());
9216 }
9217 XmlUtils.skipCurrentTag(parser);
9218 }
9219 }
9220
9221 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9222 XmlPullParser parser)
9223 throws IOException, XmlPullParserException {
9224 int outerDepth = parser.getDepth();
9225 int type;
9226 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9227 && (type != XmlPullParser.END_TAG
9228 || parser.getDepth() > outerDepth)) {
9229 if (type == XmlPullParser.END_TAG
9230 || type == XmlPullParser.TEXT) {
9231 continue;
9232 }
9233
9234 String tagName = parser.getName();
9235 if (tagName.equals("item")) {
9236 String name = parser.getAttributeValue(null, "name");
9237 if (name != null) {
9238 packageSetting.enabledComponents.add(name.intern());
9239 } else {
9240 reportSettingsProblem(Log.WARN,
9241 "Error in package manager settings: <enabled-components> has"
9242 + " no name at " + parser.getPositionDescription());
9243 }
9244 } else {
9245 reportSettingsProblem(Log.WARN,
9246 "Unknown element under <enabled-components>: "
9247 + parser.getName());
9248 }
9249 XmlUtils.skipCurrentTag(parser);
9250 }
9251 }
9252
9253 private void readSharedUserLP(XmlPullParser parser)
9254 throws XmlPullParserException, IOException {
9255 String name = null;
9256 String idStr = null;
9257 int pkgFlags = 0;
9258 SharedUserSetting su = null;
9259 try {
9260 name = parser.getAttributeValue(null, "name");
9261 idStr = parser.getAttributeValue(null, "userId");
9262 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9263 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9264 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9265 }
9266 if (name == null) {
9267 reportSettingsProblem(Log.WARN,
9268 "Error in package manager settings: <shared-user> has no name at "
9269 + parser.getPositionDescription());
9270 } else if (userId == 0) {
9271 reportSettingsProblem(Log.WARN,
9272 "Error in package manager settings: shared-user "
9273 + name + " has bad userId " + idStr + " at "
9274 + parser.getPositionDescription());
9275 } else {
9276 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9277 reportSettingsProblem(Log.ERROR,
9278 "Occurred while parsing settings at "
9279 + parser.getPositionDescription());
9280 }
9281 }
9282 } catch (NumberFormatException e) {
9283 reportSettingsProblem(Log.WARN,
9284 "Error in package manager settings: package "
9285 + name + " has bad userId " + idStr + " at "
9286 + parser.getPositionDescription());
9287 };
9288
9289 if (su != null) {
9290 int outerDepth = parser.getDepth();
9291 int type;
9292 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9293 && (type != XmlPullParser.END_TAG
9294 || parser.getDepth() > outerDepth)) {
9295 if (type == XmlPullParser.END_TAG
9296 || type == XmlPullParser.TEXT) {
9297 continue;
9298 }
9299
9300 String tagName = parser.getName();
9301 if (tagName.equals("sigs")) {
9302 su.signatures.readXml(parser, mPastSignatures);
9303 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009304 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009305 } else {
9306 reportSettingsProblem(Log.WARN,
9307 "Unknown element under <shared-user>: "
9308 + parser.getName());
9309 XmlUtils.skipCurrentTag(parser);
9310 }
9311 }
9312
9313 } else {
9314 XmlUtils.skipCurrentTag(parser);
9315 }
9316 }
9317
9318 private void readGrantedPermissionsLP(XmlPullParser parser,
9319 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9320 int outerDepth = parser.getDepth();
9321 int type;
9322 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9323 && (type != XmlPullParser.END_TAG
9324 || parser.getDepth() > outerDepth)) {
9325 if (type == XmlPullParser.END_TAG
9326 || type == XmlPullParser.TEXT) {
9327 continue;
9328 }
9329
9330 String tagName = parser.getName();
9331 if (tagName.equals("item")) {
9332 String name = parser.getAttributeValue(null, "name");
9333 if (name != null) {
9334 outPerms.add(name.intern());
9335 } else {
9336 reportSettingsProblem(Log.WARN,
9337 "Error in package manager settings: <perms> has"
9338 + " no name at " + parser.getPositionDescription());
9339 }
9340 } else {
9341 reportSettingsProblem(Log.WARN,
9342 "Unknown element under <perms>: "
9343 + parser.getName());
9344 }
9345 XmlUtils.skipCurrentTag(parser);
9346 }
9347 }
9348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009349 private void readPreferredActivitiesLP(XmlPullParser parser)
9350 throws XmlPullParserException, IOException {
9351 int outerDepth = parser.getDepth();
9352 int type;
9353 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9354 && (type != XmlPullParser.END_TAG
9355 || parser.getDepth() > outerDepth)) {
9356 if (type == XmlPullParser.END_TAG
9357 || type == XmlPullParser.TEXT) {
9358 continue;
9359 }
9360
9361 String tagName = parser.getName();
9362 if (tagName.equals("item")) {
9363 PreferredActivity pa = new PreferredActivity(parser);
9364 if (pa.mParseError == null) {
9365 mPreferredActivities.addFilter(pa);
9366 } else {
9367 reportSettingsProblem(Log.WARN,
9368 "Error in package manager settings: <preferred-activity> "
9369 + pa.mParseError + " at "
9370 + parser.getPositionDescription());
9371 }
9372 } else {
9373 reportSettingsProblem(Log.WARN,
9374 "Unknown element under <preferred-activities>: "
9375 + parser.getName());
9376 XmlUtils.skipCurrentTag(parser);
9377 }
9378 }
9379 }
9380
9381 // Returns -1 if we could not find an available UserId to assign
9382 private int newUserIdLP(Object obj) {
9383 // Let's be stupidly inefficient for now...
9384 final int N = mUserIds.size();
9385 for (int i=0; i<N; i++) {
9386 if (mUserIds.get(i) == null) {
9387 mUserIds.set(i, obj);
9388 return FIRST_APPLICATION_UID + i;
9389 }
9390 }
9391
9392 // None left?
9393 if (N >= MAX_APPLICATION_UIDS) {
9394 return -1;
9395 }
9396
9397 mUserIds.add(obj);
9398 return FIRST_APPLICATION_UID + N;
9399 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 public PackageSetting getDisabledSystemPkg(String name) {
9402 synchronized(mPackages) {
9403 PackageSetting ps = mDisabledSysPackages.get(name);
9404 return ps;
9405 }
9406 }
9407
9408 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9409 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9410 if (Config.LOGV) {
9411 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9412 + " componentName = " + componentInfo.name);
9413 Log.v(TAG, "enabledComponents: "
9414 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9415 Log.v(TAG, "disabledComponents: "
9416 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9417 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009418 if (packageSettings == null) {
9419 if (false) {
9420 Log.w(TAG, "WAITING FOR DEBUGGER");
9421 Debug.waitForDebugger();
9422 Log.i(TAG, "We will crash!");
9423 }
9424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009425 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9426 || ((componentInfo.enabled
9427 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9428 || (componentInfo.applicationInfo.enabled
9429 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9430 && !packageSettings.disabledComponents.contains(componentInfo.name))
9431 || packageSettings.enabledComponents.contains(componentInfo.name));
9432 }
9433 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009434
9435 // ------- apps on sdcard specific code -------
9436 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009437 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009438 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009439 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009440 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009441
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009442 private String getEncryptKey() {
9443 try {
9444 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9445 if (sdEncKey == null) {
9446 sdEncKey = SystemKeyStore.getInstance().
9447 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9448 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009449 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009450 return null;
9451 }
9452 }
9453 return sdEncKey;
9454 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009455 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009456 return null;
9457 }
9458 }
9459
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009460 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009461 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009462 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009463 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009464 if (list != null) {
9465 int idx = 0;
9466 int idList[] = new int[MAX_CONTAINERS];
9467 boolean neverFound = true;
9468 for (String name : list) {
9469 // Ignore null entries
9470 if (name == null) {
9471 continue;
9472 }
9473 int sidx = name.indexOf(prefix);
9474 if (sidx == -1) {
9475 // Not a temp file. just ignore
9476 continue;
9477 }
9478 String subStr = name.substring(sidx + prefix.length());
9479 idList[idx] = -1;
9480 if (subStr != null) {
9481 try {
9482 int cid = Integer.parseInt(subStr);
9483 idList[idx++] = cid;
9484 neverFound = false;
9485 } catch (NumberFormatException e) {
9486 }
9487 }
9488 }
9489 if (!neverFound) {
9490 // Sort idList
9491 Arrays.sort(idList);
9492 for (int j = 1; j <= idList.length; j++) {
9493 if (idList[j-1] != j) {
9494 tmpIdx = j;
9495 break;
9496 }
9497 }
9498 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009499 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009500 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009501 }
9502
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009503 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009504 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009505 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009506 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9507 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9508 throw new SecurityException("Media status can only be updated by the system");
9509 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009510 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009511 Log.i(TAG, "Updating external media status from " +
9512 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9513 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009514 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9515 mediaStatus+", mMediaMounted=" + mMediaMounted);
9516 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009517 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9518 reportStatus ? 1 : 0, -1);
9519 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009520 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009521 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009522 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009523 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009524 // Queue up an async operation since the package installation may take a little while.
9525 mHandler.post(new Runnable() {
9526 public void run() {
9527 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009528 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009529 }
9530 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009531 }
9532
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009533 /*
9534 * Collect information of applications on external media, map them
9535 * against existing containers and update information based on current
9536 * mount status. Please note that we always have to report status
9537 * if reportStatus has been set to true especially when unloading packages.
9538 */
9539 private void updateExternalMediaStatusInner(boolean mediaStatus,
9540 boolean reportStatus) {
9541 // Collection of uids
9542 int uidArr[] = null;
9543 // Collection of stale containers
9544 HashSet<String> removeCids = new HashSet<String>();
9545 // Collection of packages on external media with valid containers.
9546 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9547 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009548 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009549 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009550 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009551 } else {
9552 // Process list of secure containers and categorize them
9553 // as active or stale based on their package internal state.
9554 int uidList[] = new int[list.length];
9555 int num = 0;
9556 synchronized (mPackages) {
9557 for (String cid : list) {
9558 SdInstallArgs args = new SdInstallArgs(cid);
9559 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009560 String pkgName = args.getPackageName();
9561 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009562 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9563 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009564 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009565 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009566 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9567 PackageSetting ps = mSettings.mPackages.get(pkgName);
Dianne Hackbornc956f372010-04-29 11:56:40 -07009568 if (ps != null && ps.codePathString != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009569 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9570 " corresponds to pkg : " + pkgName +
9571 " at code path: " + ps.codePathString);
9572 // We do have a valid package installed on sdcard
9573 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009574 int uid = ps.userId;
9575 if (uid != -1) {
9576 uidList[num++] = uid;
9577 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009578 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009579 // Stale container on sdcard. Just delete
9580 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9581 removeCids.add(cid);
9582 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009583 }
9584 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009585
9586 if (num > 0) {
9587 // Sort uid list
9588 Arrays.sort(uidList, 0, num);
9589 // Throw away duplicates
9590 uidArr = new int[num];
9591 uidArr[0] = uidList[0];
9592 int di = 0;
9593 for (int i = 1; i < num; i++) {
9594 if (uidList[i-1] != uidList[i]) {
9595 uidArr[di++] = uidList[i];
9596 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009597 }
9598 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009599 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009600 // Process packages with valid entries.
9601 if (mediaStatus) {
9602 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009603 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009604 startCleaningPackages();
9605 } else {
9606 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009607 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009608 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009609 }
9610
9611 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009612 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009613 int size = pkgList.size();
9614 if (size > 0) {
9615 // Send broadcasts here
9616 Bundle extras = new Bundle();
9617 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9618 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009619 if (uidArr != null) {
9620 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9621 }
9622 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9623 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009624 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009625 }
9626 }
9627
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009628 /*
9629 * Look at potentially valid container ids from processCids
9630 * If package information doesn't match the one on record
9631 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009632 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009633 */
9634 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009635 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009636 ArrayList<String> pkgList = new ArrayList<String>();
9637 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009638 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009639 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009640 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009641 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9642 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009643 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009644 try {
9645 // Make sure there are no container errors first.
9646 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9647 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009648 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009649 " when installing from sdcard");
9650 continue;
9651 }
9652 // Check code path here.
9653 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009654 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009655 " does not match one in settings " + codePath);
9656 continue;
9657 }
9658 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009659 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009660 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009661 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009662 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9663 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009664 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009665 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009666 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009667 retCode = PackageManager.INSTALL_SUCCEEDED;
9668 pkgList.add(pkg.packageName);
9669 // Post process args
9670 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9671 }
9672 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009673 Slog.i(TAG, "Failed to install pkg from " +
9674 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009675 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009676 }
9677
9678 } finally {
9679 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9680 // Don't destroy container here. Wait till gc clears things up.
9681 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009682 }
9683 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009684 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009685 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009686 // If the platform SDK has changed since the last time we booted,
9687 // we need to re-grant app permission to catch any new ones that
9688 // appear. This is really a hack, and means that apps can in some
9689 // cases get permissions that the user didn't initially explicitly
9690 // allow... it would be nice to have some better way to handle
9691 // this situation.
9692 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9693 != mSdkVersion;
9694 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9695 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9696 + "; regranting permissions for external storage");
9697 mSettings.mExternalSdkPlatform = mSdkVersion;
9698
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009699 // Make sure group IDs have been assigned, and any permission
9700 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009701 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009702 // Persist settings
9703 mSettings.writeLP();
9704 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009705 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009706 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009707 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009708 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009709 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009710 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009711 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009712 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009713 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009714 if (removeCids != null) {
9715 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009716 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009717 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009718 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009719 }
9720
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009721 /*
9722 * Utility method to unload a list of specified containers
9723 */
9724 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9725 // Just unmount all valid containers.
9726 for (SdInstallArgs arg : cidArgs) {
9727 synchronized (mInstallLock) {
9728 arg.doPostDeleteLI(false);
9729 }
9730 }
9731 }
9732
9733 /*
9734 * Unload packages mounted on external media. This involves deleting
9735 * package data from internal structures, sending broadcasts about
9736 * diabled packages, gc'ing to free up references, unmounting all
9737 * secure containers corresponding to packages on external media, and
9738 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9739 * Please note that we always have to post this message if status has
9740 * been requested no matter what.
9741 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009742 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009743 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009744 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009745 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009746 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009747 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009748 for (SdInstallArgs args : keys) {
9749 String cid = args.cid;
9750 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009751 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009752 // Delete package internally
9753 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9754 synchronized (mInstallLock) {
9755 boolean res = deletePackageLI(pkgName, false,
9756 PackageManager.DONT_DELETE_DATA, outInfo);
9757 if (res) {
9758 pkgList.add(pkgName);
9759 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009760 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009761 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009762 }
9763 }
9764 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009765 // We have to absolutely send UPDATED_MEDIA_STATUS only
9766 // after confirming that all the receivers processed the ordered
9767 // broadcast when packages get disabled, force a gc to clean things up.
9768 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009769 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009770 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9771 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9772 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009773 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9774 reportStatus ? 1 : 0, 1, keys);
9775 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009776 }
9777 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009778 } else {
9779 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9780 reportStatus ? 1 : 0, -1, keys);
9781 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009782 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009783 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009784
9785 public void movePackage(final String packageName,
9786 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009787 mContext.enforceCallingOrSelfPermission(
9788 android.Manifest.permission.MOVE_PACKAGE, null);
9789 int returnCode = PackageManager.MOVE_SUCCEEDED;
9790 int currFlags = 0;
9791 int newFlags = 0;
9792 synchronized (mPackages) {
9793 PackageParser.Package pkg = mPackages.get(packageName);
9794 if (pkg == null) {
9795 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009796 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009797 // Disable moving fwd locked apps and system packages
9798 if (pkg.applicationInfo != null &&
9799 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9800 Slog.w(TAG, "Cannot move system application");
9801 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9802 } else if (pkg.applicationInfo != null &&
9803 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9804 Slog.w(TAG, "Cannot move forward locked app.");
9805 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009806 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009807 // Find install location first
9808 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9809 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9810 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009811 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009812 } else {
9813 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9814 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9815 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9816 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9817 if (newFlags == currFlags) {
9818 Slog.w(TAG, "No move required. Trying to move to same location");
9819 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9820 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009821 }
9822 }
9823 }
9824 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07009825 processPendingMove(new MoveParams(null, observer, 0, packageName), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009826 } else {
9827 Message msg = mHandler.obtainMessage(INIT_COPY);
9828 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9829 pkg.applicationInfo.publicSourceDir);
9830 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9831 packageName);
9832 msg.obj = mp;
9833 mHandler.sendMessage(msg);
9834 }
9835 }
9836 }
9837
9838 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9839 // Queue up an async operation since the package deletion may take a little while.
9840 mHandler.post(new Runnable() {
9841 public void run() {
9842 mHandler.removeCallbacks(this);
9843 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009844 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9845 int uidArr[] = null;
9846 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009847 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009848 PackageParser.Package pkg = mPackages.get(mp.packageName);
9849 if (pkg == null ) {
9850 Slog.w(TAG, " Package " + mp.packageName +
9851 " doesn't exist. Aborting move");
9852 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9853 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9854 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9855 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9856 " Aborting move and returning error");
9857 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9858 } else {
9859 uidArr = new int[] { pkg.applicationInfo.uid };
9860 pkgList = new ArrayList<String>();
9861 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009862 }
9863 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009864 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9865 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009866 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009867 // Update package code and resource paths
9868 synchronized (mInstallLock) {
9869 synchronized (mPackages) {
9870 PackageParser.Package pkg = mPackages.get(mp.packageName);
9871 // Recheck for package again.
9872 if (pkg == null ) {
9873 Slog.w(TAG, " Package " + mp.packageName +
9874 " doesn't exist. Aborting move");
9875 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9876 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9877 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9878 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9879 " Aborting move and returning error");
9880 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9881 } else {
9882 String oldCodePath = pkg.mPath;
9883 String newCodePath = mp.targetArgs.getCodePath();
9884 String newResPath = mp.targetArgs.getResourcePath();
9885 pkg.mPath = newCodePath;
9886 // Move dex files around
9887 if (moveDexFilesLI(pkg)
9888 != PackageManager.INSTALL_SUCCEEDED) {
9889 // Moving of dex files failed. Set
9890 // error code and abort move.
9891 pkg.mPath = pkg.mScanPath;
9892 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9893 } else {
9894 pkg.mScanPath = newCodePath;
9895 pkg.applicationInfo.sourceDir = newCodePath;
9896 pkg.applicationInfo.publicSourceDir = newResPath;
9897 PackageSetting ps = (PackageSetting) pkg.mExtras;
9898 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9899 ps.codePathString = ps.codePath.getPath();
9900 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9901 ps.resourcePathString = ps.resourcePath.getPath();
9902 // Set the application info flag correctly.
9903 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9904 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9905 } else {
9906 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9907 }
9908 ps.setFlags(pkg.applicationInfo.flags);
9909 mAppDirs.remove(oldCodePath);
9910 mAppDirs.put(newCodePath, pkg);
9911 // Persist settings
9912 mSettings.writeLP();
9913 }
9914 }
9915 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009916 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009917 // Send resources available broadcast
9918 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009919 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009920 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009921 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009922 // Clean up failed installation
9923 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009924 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009925 }
9926 } else {
9927 // Force a gc to clear things up.
9928 Runtime.getRuntime().gc();
9929 // Delete older code
9930 synchronized (mInstallLock) {
9931 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009932 }
9933 }
9934 IPackageMoveObserver observer = mp.observer;
9935 if (observer != null) {
9936 try {
9937 observer.packageMoved(mp.packageName, returnCode);
9938 } catch (RemoteException e) {
9939 Log.i(TAG, "Observer no longer exists.");
9940 }
9941 }
9942 }
9943 });
9944 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009945
9946 public boolean setInstallLocation(int loc) {
9947 mContext.enforceCallingOrSelfPermission(
9948 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9949 if (getInstallLocation() == loc) {
9950 return true;
9951 }
9952 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9953 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9954 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9955 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9956 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9957 return true;
9958 }
9959 return false;
9960 }
9961
9962 public int getInstallLocation() {
9963 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9964 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009966}