blob: b1e5d32c0fd7e7507981fd9744467fa0ddaeefbf [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;
Tom Taylord4a47292009-12-21 13:59:18 -080021import com.android.common.FastXmlSerializer;
22import com.android.common.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
24import org.xmlpull.v1.XmlPullParser;
25import org.xmlpull.v1.XmlPullParserException;
26import org.xmlpull.v1.XmlSerializer;
27
28import android.app.ActivityManagerNative;
29import android.app.IActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070034import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080035import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070036import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.pm.ActivityInfo;
38import android.content.pm.ApplicationInfo;
39import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070040import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.IPackageDataObserver;
42import android.content.pm.IPackageDeleteObserver;
43import android.content.pm.IPackageInstallObserver;
44import android.content.pm.IPackageManager;
45import android.content.pm.IPackageStatsObserver;
46import android.content.pm.InstrumentationInfo;
47import android.content.pm.PackageInfo;
48import android.content.pm.PackageManager;
49import android.content.pm.PackageStats;
50import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
51import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
52import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
53import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
54import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
55import android.content.pm.PackageParser;
56import android.content.pm.PermissionInfo;
57import android.content.pm.PermissionGroupInfo;
58import android.content.pm.ProviderInfo;
59import android.content.pm.ResolveInfo;
60import android.content.pm.ServiceInfo;
61import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.Uri;
63import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070064import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080066import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080068import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070069import android.os.Looper;
70import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Parcel;
72import android.os.RemoteException;
73import android.os.Environment;
74import android.os.FileObserver;
75import android.os.FileUtils;
76import android.os.Handler;
San Mehatb1043402010-02-05 08:26:50 -080077import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.os.ParcelFileDescriptor;
79import android.os.Process;
80import android.os.ServiceManager;
81import android.os.SystemClock;
82import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080083import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.util.*;
85import android.view.Display;
86import android.view.WindowManager;
87
88import java.io.File;
89import java.io.FileDescriptor;
90import java.io.FileInputStream;
91import java.io.FileNotFoundException;
92import java.io.FileOutputStream;
93import java.io.FileReader;
94import java.io.FilenameFilter;
95import java.io.IOException;
96import java.io.InputStream;
97import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -080098import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -080099import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.util.ArrayList;
101import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700102import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.Collections;
104import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800105import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.Enumeration;
107import java.util.HashMap;
108import java.util.HashSet;
109import java.util.Iterator;
110import java.util.List;
111import java.util.Map;
112import java.util.Set;
113import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800114import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import java.util.zip.ZipFile;
116import java.util.zip.ZipOutputStream;
117
118class PackageManagerService extends IPackageManager.Stub {
119 private static final String TAG = "PackageManager";
120 private static final boolean DEBUG_SETTINGS = false;
121 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800122 private static final boolean DEBUG_UPGRADE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
124 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
125 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400126 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 private static final int FIRST_APPLICATION_UID =
128 Process.FIRST_APPLICATION_UID;
129 private static final int MAX_APPLICATION_UIDS = 1000;
130
131 private static final boolean SHOW_INFO = false;
132
133 private static final boolean GET_CERTIFICATES = true;
134
Oscar Montemayora8529f62009-11-18 10:14:20 -0800135 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private static final int REMOVE_EVENTS =
138 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
139 private static final int ADD_EVENTS =
140 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
141
142 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
143
144 static final int SCAN_MONITOR = 1<<0;
145 static final int SCAN_NO_DEX = 1<<1;
146 static final int SCAN_FORCE_DEX = 1<<2;
147 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800148 static final int SCAN_NEW_INSTALL = 1<<4;
149 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800151 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
152 "com.android.defcontainer",
153 "com.android.defcontainer.DefaultContainerService");
154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
156 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700157 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Dianne Hackborn851a5412009-05-08 12:06:44 -0700159 final int mSdkVersion = Build.VERSION.SDK_INT;
160 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
161 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 final Context mContext;
164 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700165 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 final DisplayMetrics mMetrics;
167 final int mDefParseFlags;
168 final String[] mSeparateProcesses;
169
170 // This is where all application persistent data goes.
171 final File mAppDataDir;
172
Oscar Montemayora8529f62009-11-18 10:14:20 -0800173 // If Encrypted File System feature is enabled, all application persistent data
174 // should go here instead.
175 final File mSecureAppDataDir;
176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 // This is the object monitoring the framework dir.
178 final FileObserver mFrameworkInstallObserver;
179
180 // This is the object monitoring the system app dir.
181 final FileObserver mSystemInstallObserver;
182
183 // This is the object monitoring mAppInstallDir.
184 final FileObserver mAppInstallObserver;
185
186 // This is the object monitoring mDrmAppPrivateInstallDir.
187 final FileObserver mDrmAppInstallObserver;
188
189 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
190 // LOCK HELD. Can be called with mInstallLock held.
191 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 final File mFrameworkDir;
194 final File mSystemAppDir;
195 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700196 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
198 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
199 // apps.
200 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 // Lock for state used when installing and doing other long running
205 // operations. Methods that must be called with this lock held have
206 // the prefix "LI".
207 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 // These are the directories in the 3rd party applications installed dir
210 // that we have currently loaded packages from. Keys are the application's
211 // installed zip file (absolute codePath), and values are Package.
212 final HashMap<String, PackageParser.Package> mAppDirs =
213 new HashMap<String, PackageParser.Package>();
214
215 // Information for the parser to write more useful error messages.
216 File mScanningPath;
217 int mLastScanError;
218
219 final int[] mOutPermissions = new int[3];
220
221 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // Keys are String (package name), values are Package. This also serves
224 // as the lock for the global state. Methods that must be called with
225 // this lock held have the prefix "LP".
226 final HashMap<String, PackageParser.Package> mPackages =
227 new HashMap<String, PackageParser.Package>();
228
229 final Settings mSettings;
230 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
232 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
233 int[] mGlobalGids;
234
235 // These are the built-in uid -> permission mappings that were read from the
236 // etc/permissions.xml file.
237 final SparseArray<HashSet<String>> mSystemPermissions =
238 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // These are the built-in shared libraries that were read from the
241 // etc/permissions.xml file.
242 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800243
Dianne Hackborn49237342009-08-27 20:08:01 -0700244 // Temporary for building the final shared libraries for an .apk.
245 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800246
Dianne Hackborn49237342009-08-27 20:08:01 -0700247 // These are the features this devices supports that were read from the
248 // etc/permissions.xml file.
249 final HashMap<String, FeatureInfo> mAvailableFeatures =
250 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 // All available activities, for your resolving pleasure.
253 final ActivityIntentResolver mActivities =
254 new ActivityIntentResolver();
255
256 // All available receivers, for your resolving pleasure.
257 final ActivityIntentResolver mReceivers =
258 new ActivityIntentResolver();
259
260 // All available services, for your resolving pleasure.
261 final ServiceIntentResolver mServices = new ServiceIntentResolver();
262
263 // Keys are String (provider class name), values are Provider.
264 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
265 new HashMap<ComponentName, PackageParser.Provider>();
266
267 // Mapping from provider base names (first directory in content URI codePath)
268 // to the provider information.
269 final HashMap<String, PackageParser.Provider> mProviders =
270 new HashMap<String, PackageParser.Provider>();
271
272 // Mapping from instrumentation class names to info about them.
273 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
274 new HashMap<ComponentName, PackageParser.Instrumentation>();
275
276 // Mapping from permission names to info about them.
277 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
278 new HashMap<String, PackageParser.PermissionGroup>();
279
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800280 // Packages whose data we have transfered into another package, thus
281 // should no longer exist.
282 final HashSet<String> mTransferedPackages = new HashSet<String>();
283
Dianne Hackborn854060af2009-07-09 18:14:31 -0700284 // Broadcast actions that are only available to the system.
285 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 boolean mSystemReady;
288 boolean mSafeMode;
289 boolean mHasSystemUidErrors;
290
291 ApplicationInfo mAndroidApplication;
292 final ActivityInfo mResolveActivity = new ActivityInfo();
293 final ResolveInfo mResolveInfo = new ResolveInfo();
294 ComponentName mResolveComponentName;
295 PackageParser.Package mPlatformPackage;
296
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700297 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800298 final HashMap<String, ArrayList<String>> mPendingBroadcasts
299 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700300 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800301 static final int MCS_BOUND = 3;
302 static final int END_COPY = 4;
303 static final int INIT_COPY = 5;
304 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800305 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700306 // Delay time in millisecs
307 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800308 private ServiceConnection mDefContainerConn = new ServiceConnection() {
309 public void onServiceConnected(ComponentName name, IBinder service) {
310 IMediaContainerService imcs =
311 IMediaContainerService.Stub.asInterface(service);
312 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
313 mHandler.sendMessage(msg);
314 }
315
316 public void onServiceDisconnected(ComponentName name) {
317 }
318 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700319
320 class PackageHandler extends Handler {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800321 final ArrayList<InstallArgs> mPendingInstalls =
322 new ArrayList<InstallArgs>();
323 // Service Connection to remote media container service to copy
324 // package uri's from external media onto secure containers
325 // or internal storage.
326 private IMediaContainerService mContainerService = null;
327
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700328 PackageHandler(Looper looper) {
329 super(looper);
330 }
331 public void handleMessage(Message msg) {
332 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800333 case INIT_COPY: {
334 InstallArgs args = (InstallArgs) msg.obj;
335 args.createCopyFile();
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800336 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800337 if (mContainerService != null) {
338 // No need to add to pending list. Use remote stub directly
339 handleStartCopy(args);
340 } else {
341 if (mContext.bindService(service, mDefContainerConn,
342 Context.BIND_AUTO_CREATE)) {
343 mPendingInstalls.add(args);
344 } else {
345 Log.e(TAG, "Failed to bind to media container service");
346 // Indicate install failure TODO add new error code
347 processPendingInstall(args,
348 PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800349 }
350 }
351 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800352 }
353 case MCS_BOUND: {
354 // Initialize mContainerService if needed.
355 if (msg.obj != null) {
356 mContainerService = (IMediaContainerService) msg.obj;
357 }
358 if (mPendingInstalls.size() > 0) {
359 InstallArgs args = mPendingInstalls.remove(0);
360 if (args != null) {
361 handleStartCopy(args);
362 }
363 }
364 break;
365 }
366 case MCS_UNBIND : {
367 if (mPendingInstalls.size() == 0) {
368 mContext.unbindService(mDefContainerConn);
369 mContainerService = null;
370 }
371 break;
372 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700373 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800374 String packages[];
375 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700376 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700377 int uids[];
378 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800379 if (mPendingBroadcasts == null) {
380 return;
381 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700382 size = mPendingBroadcasts.size();
383 if (size <= 0) {
384 // Nothing to be done. Just return
385 return;
386 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800387 packages = new String[size];
388 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700389 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800390 Iterator<HashMap.Entry<String, ArrayList<String>>>
391 it = mPendingBroadcasts.entrySet().iterator();
392 int i = 0;
393 while (it.hasNext() && i < size) {
394 HashMap.Entry<String, ArrayList<String>> ent = it.next();
395 packages[i] = ent.getKey();
396 components[i] = ent.getValue();
397 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700398 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800399 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700400 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800401 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700402 mPendingBroadcasts.clear();
403 }
404 // Send broadcasts
405 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800406 sendPackageChangedBroadcast(packages[i], true,
407 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700408 }
409 break;
410 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800411 case START_CLEANING_PACKAGE: {
412 String packageName = (String)msg.obj;
413 synchronized (mPackages) {
414 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
415 mSettings.mPackagesToBeCleaned.add(packageName);
416 }
417 }
418 startCleaningPackages();
419 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700420 }
421 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800422
423 // Utility method to initiate copying apk via media
424 // container service.
425 private void handleStartCopy(InstallArgs args) {
426 int ret = PackageManager.INSTALL_SUCCEEDED;
427 if (mContainerService == null) {
428 // Install error
429 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
430 } else {
431 ret = args.copyApk(mContainerService);
432 }
433 mHandler.sendEmptyMessage(MCS_UNBIND);
434 processPendingInstall(args, ret);
435 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700436 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800437
438 static boolean installOnSd(int flags) {
439 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
440 ((flags & PackageManager.INSTALL_ON_SDCARD) == 0)) {
441 return false;
442 }
443 return true;
444 }
445
446 static boolean isFwdLocked(int flags) {
447 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
448 return true;
449 }
450 return false;
451 }
452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 public static final IPackageManager main(Context context, boolean factoryTest) {
454 PackageManagerService m = new PackageManagerService(context, factoryTest);
455 ServiceManager.addService("package", m);
456 return m;
457 }
458
459 static String[] splitString(String str, char sep) {
460 int count = 1;
461 int i = 0;
462 while ((i=str.indexOf(sep, i)) >= 0) {
463 count++;
464 i++;
465 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 String[] res = new String[count];
468 i=0;
469 count = 0;
470 int lastI=0;
471 while ((i=str.indexOf(sep, i)) >= 0) {
472 res[count] = str.substring(lastI, i);
473 count++;
474 i++;
475 lastI = i;
476 }
477 res[count] = str.substring(lastI, str.length());
478 return res;
479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800482 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 if (mSdkVersion <= 0) {
486 Log.w(TAG, "**** ro.build.version.sdk not set!");
487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 mContext = context;
490 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700491 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 mMetrics = new DisplayMetrics();
493 mSettings = new Settings();
494 mSettings.addSharedUserLP("android.uid.system",
495 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
496 mSettings.addSharedUserLP("android.uid.phone",
497 MULTIPLE_APPLICATION_UIDS
498 ? RADIO_UID : FIRST_APPLICATION_UID,
499 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400500 mSettings.addSharedUserLP("android.uid.log",
501 MULTIPLE_APPLICATION_UIDS
502 ? LOG_UID : FIRST_APPLICATION_UID,
503 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504
505 String separateProcesses = SystemProperties.get("debug.separate_processes");
506 if (separateProcesses != null && separateProcesses.length() > 0) {
507 if ("*".equals(separateProcesses)) {
508 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
509 mSeparateProcesses = null;
510 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
511 } else {
512 mDefParseFlags = 0;
513 mSeparateProcesses = separateProcesses.split(",");
514 Log.w(TAG, "Running with debug.separate_processes: "
515 + separateProcesses);
516 }
517 } else {
518 mDefParseFlags = 0;
519 mSeparateProcesses = null;
520 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 Installer installer = new Installer();
523 // Little hacky thing to check if installd is here, to determine
524 // whether we are running on the simulator and thus need to take
525 // care of building the /data file structure ourself.
526 // (apparently the sim now has a working installer)
527 if (installer.ping() && Process.supportsProcesses()) {
528 mInstaller = installer;
529 } else {
530 mInstaller = null;
531 }
532
533 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
534 Display d = wm.getDefaultDisplay();
535 d.getMetrics(mMetrics);
536
537 synchronized (mInstallLock) {
538 synchronized (mPackages) {
539 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700540 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 File dataDir = Environment.getDataDirectory();
543 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800544 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
546
547 if (mInstaller == null) {
548 // Make sure these dirs exist, when we are running in
549 // the simulator.
550 // Make a wide-open directory for random misc stuff.
551 File miscDir = new File(dataDir, "misc");
552 miscDir.mkdirs();
553 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800554 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 mDrmAppPrivateInstallDir.mkdirs();
556 }
557
558 readPermissions();
559
560 mRestoredSettings = mSettings.readLP();
561 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800562
563 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800565
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800566 // Set flag to monitor and not change apk file paths when
567 // scanning install directories.
568 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700569 if (mNoDexOpt) {
570 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800571 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700577 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700580 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 /**
583 * Out of paranoia, ensure that everything in the boot class
584 * path has been dexed.
585 */
586 String bootClassPath = System.getProperty("java.boot.class.path");
587 if (bootClassPath != null) {
588 String[] paths = splitString(bootClassPath, ':');
589 for (int i=0; i<paths.length; i++) {
590 try {
591 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
592 libFiles.add(paths[i]);
593 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700594 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 }
596 } catch (FileNotFoundException e) {
597 Log.w(TAG, "Boot class path not found: " + paths[i]);
598 } catch (IOException e) {
599 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
600 }
601 }
602 } else {
603 Log.w(TAG, "No BOOTCLASSPATH found!");
604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 /**
607 * Also ensure all external libraries have had dexopt run on them.
608 */
609 if (mSharedLibraries.size() > 0) {
610 Iterator<String> libs = mSharedLibraries.values().iterator();
611 while (libs.hasNext()) {
612 String lib = libs.next();
613 try {
614 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
615 libFiles.add(lib);
616 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700617 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 }
619 } catch (FileNotFoundException e) {
620 Log.w(TAG, "Library not found: " + lib);
621 } catch (IOException e) {
622 Log.w(TAG, "Exception reading library: " + lib, e);
623 }
624 }
625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 // Gross hack for now: we know this file doesn't contain any
628 // code, so don't dexopt it to avoid the resulting log spew.
629 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 /**
632 * And there are a number of commands implemented in Java, which
633 * we currently need to do the dexopt on so that they can be
634 * run from a non-root shell.
635 */
636 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700637 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 for (int i=0; i<frameworkFiles.length; i++) {
639 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
640 String path = libPath.getPath();
641 // Skip the file if we alrady did it.
642 if (libFiles.contains(path)) {
643 continue;
644 }
645 // Skip the file if it is not a type we want to dexopt.
646 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
647 continue;
648 }
649 try {
650 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
651 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700652 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 }
654 } catch (FileNotFoundException e) {
655 Log.w(TAG, "Jar not found: " + path);
656 } catch (IOException e) {
657 Log.w(TAG, "Exception reading jar: " + path, e);
658 }
659 }
660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800661
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700662 if (didDexOpt) {
663 // If we had to do a dexopt of one of the previous
664 // things, then something on the system has changed.
665 // Consider this significant, and wipe away all other
666 // existing dexopt files to ensure we don't leave any
667 // dangling around.
668 String[] files = mDalvikCacheDir.list();
669 if (files != null) {
670 for (int i=0; i<files.length; i++) {
671 String fn = files[i];
672 if (fn.startsWith("data@app@")
673 || fn.startsWith("data@app-private@")) {
674 Log.i(TAG, "Pruning dalvik file: " + fn);
675 (new File(mDalvikCacheDir, fn)).delete();
676 }
677 }
678 }
679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800681
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800682 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 mFrameworkInstallObserver = new AppDirObserver(
684 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
685 mFrameworkInstallObserver.startWatching();
686 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800687 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800688
689 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
691 mSystemInstallObserver = new AppDirObserver(
692 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
693 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800694 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800695
696 if (mInstaller != null) {
697 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
698 mInstaller.moveFiles();
699 }
700
701 // Prune any system packages that no longer exist.
702 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
703 while (psit.hasNext()) {
704 PackageSetting ps = psit.next();
705 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
706 && !mPackages.containsKey(ps.name)) {
707 psit.remove();
708 String msg = "System package " + ps.name
709 + " no longer exists; wiping its data";
710 reportSettingsProblem(Log.WARN, msg);
711 if (mInstaller != null) {
712 // XXX how to set useEncryptedFSDir for packages that
713 // are not encrypted?
714 mInstaller.remove(ps.name, true);
715 }
716 }
717 }
718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 mAppInstallDir = new File(dataDir, "app");
720 if (mInstaller == null) {
721 // Make sure these dirs exist, when we are running in
722 // the simulator.
723 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
724 }
725 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800726 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 //clean up list
728 for(int i = 0; i < deletePkgsList.size(); i++) {
729 //clean up here
730 cleanupInstallFailedPackage(deletePkgsList.get(i));
731 }
732 //delete tmp files
733 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800734
735 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 SystemClock.uptimeMillis());
737 mAppInstallObserver = new AppDirObserver(
738 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
739 mAppInstallObserver.startWatching();
740 scanDirLI(mAppInstallDir, 0, scanMode);
741
742 mDrmAppInstallObserver = new AppDirObserver(
743 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
744 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800745 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800747 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 SystemClock.uptimeMillis());
749 Log.i(TAG, "Time to scan packages: "
750 + ((SystemClock.uptimeMillis()-startTime)/1000f)
751 + " seconds");
752
753 updatePermissionsLP();
754
755 mSettings.writeLP();
756
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800757 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 // Now after opening every single application zip, make sure they
761 // are all flushed. Not really needed, but keeps things nice and
762 // tidy.
763 Runtime.getRuntime().gc();
764 } // synchronized (mPackages)
765 } // synchronized (mInstallLock)
766 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 @Override
769 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
770 throws RemoteException {
771 try {
772 return super.onTransact(code, data, reply, flags);
773 } catch (RuntimeException e) {
774 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
775 Log.e(TAG, "Package Manager Crash", e);
776 }
777 throw e;
778 }
779 }
780
Dianne Hackborne6620b22010-01-22 14:46:21 -0800781 void cleanupInstallFailedPackage(PackageSetting ps) {
782 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800784 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
785 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 if (retCode < 0) {
787 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800788 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 }
790 } else {
791 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800792 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 File dataDir = new File(pkg.applicationInfo.dataDir);
794 dataDir.delete();
795 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800796 if (ps.codePath != null) {
797 if (!ps.codePath.delete()) {
798 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
799 }
800 }
801 if (ps.resourcePath != null) {
802 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
803 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
804 }
805 }
806 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 }
808
809 void readPermissions() {
810 // Read permissions from .../etc/permission directory.
811 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
812 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
813 Log.w(TAG, "No directory " + libraryDir + ", skipping");
814 return;
815 }
816 if (!libraryDir.canRead()) {
817 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
818 return;
819 }
820
821 // Iterate over the files in the directory and scan .xml files
822 for (File f : libraryDir.listFiles()) {
823 // We'll read platform.xml last
824 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
825 continue;
826 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 if (!f.getPath().endsWith(".xml")) {
829 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
830 continue;
831 }
832 if (!f.canRead()) {
833 Log.w(TAG, "Permissions library file " + f + " cannot be read");
834 continue;
835 }
836
837 readPermissionsFromXml(f);
838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
841 final File permFile = new File(Environment.getRootDirectory(),
842 "etc/permissions/platform.xml");
843 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800844
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700845 StringBuilder sb = new StringBuilder(128);
846 sb.append("Libs:");
847 Iterator<String> it = mSharedLibraries.keySet().iterator();
848 while (it.hasNext()) {
849 sb.append(' ');
850 String name = it.next();
851 sb.append(name);
852 sb.append(':');
853 sb.append(mSharedLibraries.get(name));
854 }
855 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800856
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700857 sb.setLength(0);
858 sb.append("Features:");
859 it = mAvailableFeatures.keySet().iterator();
860 while (it.hasNext()) {
861 sb.append(' ');
862 sb.append(it.next());
863 }
864 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800866
867 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 FileReader permReader = null;
869 try {
870 permReader = new FileReader(permFile);
871 } catch (FileNotFoundException e) {
872 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
873 return;
874 }
875
876 try {
877 XmlPullParser parser = Xml.newPullParser();
878 parser.setInput(permReader);
879
880 XmlUtils.beginDocument(parser, "permissions");
881
882 while (true) {
883 XmlUtils.nextElement(parser);
884 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
885 break;
886 }
887
888 String name = parser.getName();
889 if ("group".equals(name)) {
890 String gidStr = parser.getAttributeValue(null, "gid");
891 if (gidStr != null) {
892 int gid = Integer.parseInt(gidStr);
893 mGlobalGids = appendInt(mGlobalGids, gid);
894 } else {
895 Log.w(TAG, "<group> without gid at "
896 + parser.getPositionDescription());
897 }
898
899 XmlUtils.skipCurrentTag(parser);
900 continue;
901 } else if ("permission".equals(name)) {
902 String perm = parser.getAttributeValue(null, "name");
903 if (perm == null) {
904 Log.w(TAG, "<permission> without name at "
905 + parser.getPositionDescription());
906 XmlUtils.skipCurrentTag(parser);
907 continue;
908 }
909 perm = perm.intern();
910 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 } else if ("assign-permission".equals(name)) {
913 String perm = parser.getAttributeValue(null, "name");
914 if (perm == null) {
915 Log.w(TAG, "<assign-permission> without name at "
916 + parser.getPositionDescription());
917 XmlUtils.skipCurrentTag(parser);
918 continue;
919 }
920 String uidStr = parser.getAttributeValue(null, "uid");
921 if (uidStr == null) {
922 Log.w(TAG, "<assign-permission> without uid at "
923 + parser.getPositionDescription());
924 XmlUtils.skipCurrentTag(parser);
925 continue;
926 }
927 int uid = Process.getUidForName(uidStr);
928 if (uid < 0) {
929 Log.w(TAG, "<assign-permission> with unknown uid \""
930 + uidStr + "\" at "
931 + parser.getPositionDescription());
932 XmlUtils.skipCurrentTag(parser);
933 continue;
934 }
935 perm = perm.intern();
936 HashSet<String> perms = mSystemPermissions.get(uid);
937 if (perms == null) {
938 perms = new HashSet<String>();
939 mSystemPermissions.put(uid, perms);
940 }
941 perms.add(perm);
942 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 } else if ("library".equals(name)) {
945 String lname = parser.getAttributeValue(null, "name");
946 String lfile = parser.getAttributeValue(null, "file");
947 if (lname == null) {
948 Log.w(TAG, "<library> without name at "
949 + parser.getPositionDescription());
950 } else if (lfile == null) {
951 Log.w(TAG, "<library> without file at "
952 + parser.getPositionDescription());
953 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700954 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700955 mSharedLibraries.put(lname, lfile);
956 }
957 XmlUtils.skipCurrentTag(parser);
958 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800959
Dianne Hackborn49237342009-08-27 20:08:01 -0700960 } else if ("feature".equals(name)) {
961 String fname = parser.getAttributeValue(null, "name");
962 if (fname == null) {
963 Log.w(TAG, "<feature> without name at "
964 + parser.getPositionDescription());
965 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700966 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700967 FeatureInfo fi = new FeatureInfo();
968 fi.name = fname;
969 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
971 XmlUtils.skipCurrentTag(parser);
972 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 } else {
975 XmlUtils.skipCurrentTag(parser);
976 continue;
977 }
978
979 }
980 } catch (XmlPullParserException e) {
981 Log.w(TAG, "Got execption parsing permissions.", e);
982 } catch (IOException e) {
983 Log.w(TAG, "Got execption parsing permissions.", e);
984 }
985 }
986
987 void readPermission(XmlPullParser parser, String name)
988 throws IOException, XmlPullParserException {
989
990 name = name.intern();
991
992 BasePermission bp = mSettings.mPermissions.get(name);
993 if (bp == null) {
994 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
995 mSettings.mPermissions.put(name, bp);
996 }
997 int outerDepth = parser.getDepth();
998 int type;
999 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1000 && (type != XmlPullParser.END_TAG
1001 || parser.getDepth() > outerDepth)) {
1002 if (type == XmlPullParser.END_TAG
1003 || type == XmlPullParser.TEXT) {
1004 continue;
1005 }
1006
1007 String tagName = parser.getName();
1008 if ("group".equals(tagName)) {
1009 String gidStr = parser.getAttributeValue(null, "gid");
1010 if (gidStr != null) {
1011 int gid = Process.getGidForName(gidStr);
1012 bp.gids = appendInt(bp.gids, gid);
1013 } else {
1014 Log.w(TAG, "<group> without gid at "
1015 + parser.getPositionDescription());
1016 }
1017 }
1018 XmlUtils.skipCurrentTag(parser);
1019 }
1020 }
1021
1022 static int[] appendInt(int[] cur, int val) {
1023 if (cur == null) {
1024 return new int[] { val };
1025 }
1026 final int N = cur.length;
1027 for (int i=0; i<N; i++) {
1028 if (cur[i] == val) {
1029 return cur;
1030 }
1031 }
1032 int[] ret = new int[N+1];
1033 System.arraycopy(cur, 0, ret, 0, N);
1034 ret[N] = val;
1035 return ret;
1036 }
1037
1038 static int[] appendInts(int[] cur, int[] add) {
1039 if (add == null) return cur;
1040 if (cur == null) return add;
1041 final int N = add.length;
1042 for (int i=0; i<N; i++) {
1043 cur = appendInt(cur, add[i]);
1044 }
1045 return cur;
1046 }
1047
1048 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001049 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1050 // The package has been uninstalled but has retained data and resources.
1051 return PackageParser.generatePackageInfo(p, null, flags);
1052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 final PackageSetting ps = (PackageSetting)p.mExtras;
1054 if (ps == null) {
1055 return null;
1056 }
1057 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1058 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1059 }
1060
1061 public PackageInfo getPackageInfo(String packageName, int flags) {
1062 synchronized (mPackages) {
1063 PackageParser.Package p = mPackages.get(packageName);
1064 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001065 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 + ": " + p);
1067 if (p != null) {
1068 return generatePackageInfo(p, flags);
1069 }
1070 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1071 return generatePackageInfoFromSettingsLP(packageName, flags);
1072 }
1073 }
1074 return null;
1075 }
1076
1077 public int getPackageUid(String packageName) {
1078 synchronized (mPackages) {
1079 PackageParser.Package p = mPackages.get(packageName);
1080 if(p != null) {
1081 return p.applicationInfo.uid;
1082 }
1083 PackageSetting ps = mSettings.mPackages.get(packageName);
1084 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1085 return -1;
1086 }
1087 p = ps.pkg;
1088 return p != null ? p.applicationInfo.uid : -1;
1089 }
1090 }
1091
1092 public int[] getPackageGids(String packageName) {
1093 synchronized (mPackages) {
1094 PackageParser.Package p = mPackages.get(packageName);
1095 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001096 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 + ": " + p);
1098 if (p != null) {
1099 final PackageSetting ps = (PackageSetting)p.mExtras;
1100 final SharedUserSetting suid = ps.sharedUser;
1101 return suid != null ? suid.gids : ps.gids;
1102 }
1103 }
1104 // stupid thing to indicate an error.
1105 return new int[0];
1106 }
1107
1108 public PermissionInfo getPermissionInfo(String name, int flags) {
1109 synchronized (mPackages) {
1110 final BasePermission p = mSettings.mPermissions.get(name);
1111 if (p != null && p.perm != null) {
1112 return PackageParser.generatePermissionInfo(p.perm, flags);
1113 }
1114 return null;
1115 }
1116 }
1117
1118 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1119 synchronized (mPackages) {
1120 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1121 for (BasePermission p : mSettings.mPermissions.values()) {
1122 if (group == null) {
1123 if (p.perm.info.group == null) {
1124 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1125 }
1126 } else {
1127 if (group.equals(p.perm.info.group)) {
1128 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1129 }
1130 }
1131 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 if (out.size() > 0) {
1134 return out;
1135 }
1136 return mPermissionGroups.containsKey(group) ? out : null;
1137 }
1138 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1141 synchronized (mPackages) {
1142 return PackageParser.generatePermissionGroupInfo(
1143 mPermissionGroups.get(name), flags);
1144 }
1145 }
1146
1147 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1148 synchronized (mPackages) {
1149 final int N = mPermissionGroups.size();
1150 ArrayList<PermissionGroupInfo> out
1151 = new ArrayList<PermissionGroupInfo>(N);
1152 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1153 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1154 }
1155 return out;
1156 }
1157 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1160 PackageSetting ps = mSettings.mPackages.get(packageName);
1161 if(ps != null) {
1162 if(ps.pkg == null) {
1163 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1164 if(pInfo != null) {
1165 return pInfo.applicationInfo;
1166 }
1167 return null;
1168 }
1169 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1170 }
1171 return null;
1172 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1175 PackageSetting ps = mSettings.mPackages.get(packageName);
1176 if(ps != null) {
1177 if(ps.pkg == null) {
1178 ps.pkg = new PackageParser.Package(packageName);
1179 ps.pkg.applicationInfo.packageName = packageName;
1180 }
1181 return generatePackageInfo(ps.pkg, flags);
1182 }
1183 return null;
1184 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1187 synchronized (mPackages) {
1188 PackageParser.Package p = mPackages.get(packageName);
1189 if (Config.LOGV) Log.v(
1190 TAG, "getApplicationInfo " + packageName
1191 + ": " + p);
1192 if (p != null) {
1193 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001194 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 }
1196 if ("android".equals(packageName)||"system".equals(packageName)) {
1197 return mAndroidApplication;
1198 }
1199 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1200 return generateApplicationInfoFromSettingsLP(packageName, flags);
1201 }
1202 }
1203 return null;
1204 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001205
1206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1208 mContext.enforceCallingOrSelfPermission(
1209 android.Manifest.permission.CLEAR_APP_CACHE, null);
1210 // Queue up an async operation since clearing cache may take a little while.
1211 mHandler.post(new Runnable() {
1212 public void run() {
1213 mHandler.removeCallbacks(this);
1214 int retCode = -1;
1215 if (mInstaller != null) {
1216 retCode = mInstaller.freeCache(freeStorageSize);
1217 if (retCode < 0) {
1218 Log.w(TAG, "Couldn't clear application caches");
1219 }
1220 } //end if mInstaller
1221 if (observer != null) {
1222 try {
1223 observer.onRemoveCompleted(null, (retCode >= 0));
1224 } catch (RemoteException e) {
1225 Log.w(TAG, "RemoveException when invoking call back");
1226 }
1227 }
1228 }
1229 });
1230 }
1231
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001232 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001233 mContext.enforceCallingOrSelfPermission(
1234 android.Manifest.permission.CLEAR_APP_CACHE, null);
1235 // Queue up an async operation since clearing cache may take a little while.
1236 mHandler.post(new Runnable() {
1237 public void run() {
1238 mHandler.removeCallbacks(this);
1239 int retCode = -1;
1240 if (mInstaller != null) {
1241 retCode = mInstaller.freeCache(freeStorageSize);
1242 if (retCode < 0) {
1243 Log.w(TAG, "Couldn't clear application caches");
1244 }
1245 }
1246 if(pi != null) {
1247 try {
1248 // Callback via pending intent
1249 int code = (retCode >= 0) ? 1 : 0;
1250 pi.sendIntent(null, code, null,
1251 null, null);
1252 } catch (SendIntentException e1) {
1253 Log.i(TAG, "Failed to send pending intent");
1254 }
1255 }
1256 }
1257 });
1258 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1261 synchronized (mPackages) {
1262 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001263
1264 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001266 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 }
1268 if (mResolveComponentName.equals(component)) {
1269 return mResolveActivity;
1270 }
1271 }
1272 return null;
1273 }
1274
1275 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1276 synchronized (mPackages) {
1277 PackageParser.Activity a = mReceivers.mActivities.get(component);
1278 if (Config.LOGV) Log.v(
1279 TAG, "getReceiverInfo " + component + ": " + a);
1280 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1281 return PackageParser.generateActivityInfo(a, flags);
1282 }
1283 }
1284 return null;
1285 }
1286
1287 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1288 synchronized (mPackages) {
1289 PackageParser.Service s = mServices.mServices.get(component);
1290 if (Config.LOGV) Log.v(
1291 TAG, "getServiceInfo " + component + ": " + s);
1292 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1293 return PackageParser.generateServiceInfo(s, flags);
1294 }
1295 }
1296 return null;
1297 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 public String[] getSystemSharedLibraryNames() {
1300 Set<String> libSet;
1301 synchronized (mPackages) {
1302 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001303 int size = libSet.size();
1304 if (size > 0) {
1305 String[] libs = new String[size];
1306 libSet.toArray(libs);
1307 return libs;
1308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001310 return null;
1311 }
1312
1313 public FeatureInfo[] getSystemAvailableFeatures() {
1314 Collection<FeatureInfo> featSet;
1315 synchronized (mPackages) {
1316 featSet = mAvailableFeatures.values();
1317 int size = featSet.size();
1318 if (size > 0) {
1319 FeatureInfo[] features = new FeatureInfo[size+1];
1320 featSet.toArray(features);
1321 FeatureInfo fi = new FeatureInfo();
1322 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1323 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1324 features[size] = fi;
1325 return features;
1326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
1328 return null;
1329 }
1330
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001331 public boolean hasSystemFeature(String name) {
1332 synchronized (mPackages) {
1333 return mAvailableFeatures.containsKey(name);
1334 }
1335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 public int checkPermission(String permName, String pkgName) {
1338 synchronized (mPackages) {
1339 PackageParser.Package p = mPackages.get(pkgName);
1340 if (p != null && p.mExtras != null) {
1341 PackageSetting ps = (PackageSetting)p.mExtras;
1342 if (ps.sharedUser != null) {
1343 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1344 return PackageManager.PERMISSION_GRANTED;
1345 }
1346 } else if (ps.grantedPermissions.contains(permName)) {
1347 return PackageManager.PERMISSION_GRANTED;
1348 }
1349 }
1350 }
1351 return PackageManager.PERMISSION_DENIED;
1352 }
1353
1354 public int checkUidPermission(String permName, int uid) {
1355 synchronized (mPackages) {
1356 Object obj = mSettings.getUserIdLP(uid);
1357 if (obj != null) {
1358 if (obj instanceof SharedUserSetting) {
1359 SharedUserSetting sus = (SharedUserSetting)obj;
1360 if (sus.grantedPermissions.contains(permName)) {
1361 return PackageManager.PERMISSION_GRANTED;
1362 }
1363 } else if (obj instanceof PackageSetting) {
1364 PackageSetting ps = (PackageSetting)obj;
1365 if (ps.grantedPermissions.contains(permName)) {
1366 return PackageManager.PERMISSION_GRANTED;
1367 }
1368 }
1369 } else {
1370 HashSet<String> perms = mSystemPermissions.get(uid);
1371 if (perms != null && perms.contains(permName)) {
1372 return PackageManager.PERMISSION_GRANTED;
1373 }
1374 }
1375 }
1376 return PackageManager.PERMISSION_DENIED;
1377 }
1378
1379 private BasePermission findPermissionTreeLP(String permName) {
1380 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1381 if (permName.startsWith(bp.name) &&
1382 permName.length() > bp.name.length() &&
1383 permName.charAt(bp.name.length()) == '.') {
1384 return bp;
1385 }
1386 }
1387 return null;
1388 }
1389
1390 private BasePermission checkPermissionTreeLP(String permName) {
1391 if (permName != null) {
1392 BasePermission bp = findPermissionTreeLP(permName);
1393 if (bp != null) {
1394 if (bp.uid == Binder.getCallingUid()) {
1395 return bp;
1396 }
1397 throw new SecurityException("Calling uid "
1398 + Binder.getCallingUid()
1399 + " is not allowed to add to permission tree "
1400 + bp.name + " owned by uid " + bp.uid);
1401 }
1402 }
1403 throw new SecurityException("No permission tree found for " + permName);
1404 }
1405
1406 public boolean addPermission(PermissionInfo info) {
1407 synchronized (mPackages) {
1408 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1409 throw new SecurityException("Label must be specified in permission");
1410 }
1411 BasePermission tree = checkPermissionTreeLP(info.name);
1412 BasePermission bp = mSettings.mPermissions.get(info.name);
1413 boolean added = bp == null;
1414 if (added) {
1415 bp = new BasePermission(info.name, tree.sourcePackage,
1416 BasePermission.TYPE_DYNAMIC);
1417 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1418 throw new SecurityException(
1419 "Not allowed to modify non-dynamic permission "
1420 + info.name);
1421 }
1422 bp.perm = new PackageParser.Permission(tree.perm.owner,
1423 new PermissionInfo(info));
1424 bp.perm.info.packageName = tree.perm.info.packageName;
1425 bp.uid = tree.uid;
1426 if (added) {
1427 mSettings.mPermissions.put(info.name, bp);
1428 }
1429 mSettings.writeLP();
1430 return added;
1431 }
1432 }
1433
1434 public void removePermission(String name) {
1435 synchronized (mPackages) {
1436 checkPermissionTreeLP(name);
1437 BasePermission bp = mSettings.mPermissions.get(name);
1438 if (bp != null) {
1439 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1440 throw new SecurityException(
1441 "Not allowed to modify non-dynamic permission "
1442 + name);
1443 }
1444 mSettings.mPermissions.remove(name);
1445 mSettings.writeLP();
1446 }
1447 }
1448 }
1449
Dianne Hackborn854060af2009-07-09 18:14:31 -07001450 public boolean isProtectedBroadcast(String actionName) {
1451 synchronized (mPackages) {
1452 return mProtectedBroadcasts.contains(actionName);
1453 }
1454 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 public int checkSignatures(String pkg1, String pkg2) {
1457 synchronized (mPackages) {
1458 PackageParser.Package p1 = mPackages.get(pkg1);
1459 PackageParser.Package p2 = mPackages.get(pkg2);
1460 if (p1 == null || p1.mExtras == null
1461 || p2 == null || p2.mExtras == null) {
1462 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1463 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001464 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 }
1466 }
1467
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001468 public int checkUidSignatures(int uid1, int uid2) {
1469 synchronized (mPackages) {
1470 Signature[] s1;
1471 Signature[] s2;
1472 Object obj = mSettings.getUserIdLP(uid1);
1473 if (obj != null) {
1474 if (obj instanceof SharedUserSetting) {
1475 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1476 } else if (obj instanceof PackageSetting) {
1477 s1 = ((PackageSetting)obj).signatures.mSignatures;
1478 } else {
1479 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1480 }
1481 } else {
1482 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1483 }
1484 obj = mSettings.getUserIdLP(uid2);
1485 if (obj != null) {
1486 if (obj instanceof SharedUserSetting) {
1487 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1488 } else if (obj instanceof PackageSetting) {
1489 s2 = ((PackageSetting)obj).signatures.mSignatures;
1490 } else {
1491 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1492 }
1493 } else {
1494 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1495 }
1496 return checkSignaturesLP(s1, s2);
1497 }
1498 }
1499
1500 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1501 if (s1 == null) {
1502 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1504 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1505 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001506 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1508 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001509 final int N1 = s1.length;
1510 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 for (int i=0; i<N1; i++) {
1512 boolean match = false;
1513 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001514 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 match = true;
1516 break;
1517 }
1518 }
1519 if (!match) {
1520 return PackageManager.SIGNATURE_NO_MATCH;
1521 }
1522 }
1523 return PackageManager.SIGNATURE_MATCH;
1524 }
1525
1526 public String[] getPackagesForUid(int uid) {
1527 synchronized (mPackages) {
1528 Object obj = mSettings.getUserIdLP(uid);
1529 if (obj instanceof SharedUserSetting) {
1530 SharedUserSetting sus = (SharedUserSetting)obj;
1531 final int N = sus.packages.size();
1532 String[] res = new String[N];
1533 Iterator<PackageSetting> it = sus.packages.iterator();
1534 int i=0;
1535 while (it.hasNext()) {
1536 res[i++] = it.next().name;
1537 }
1538 return res;
1539 } else if (obj instanceof PackageSetting) {
1540 PackageSetting ps = (PackageSetting)obj;
1541 return new String[] { ps.name };
1542 }
1543 }
1544 return null;
1545 }
1546
1547 public String getNameForUid(int uid) {
1548 synchronized (mPackages) {
1549 Object obj = mSettings.getUserIdLP(uid);
1550 if (obj instanceof SharedUserSetting) {
1551 SharedUserSetting sus = (SharedUserSetting)obj;
1552 return sus.name + ":" + sus.userId;
1553 } else if (obj instanceof PackageSetting) {
1554 PackageSetting ps = (PackageSetting)obj;
1555 return ps.name;
1556 }
1557 }
1558 return null;
1559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 public int getUidForSharedUser(String sharedUserName) {
1562 if(sharedUserName == null) {
1563 return -1;
1564 }
1565 synchronized (mPackages) {
1566 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1567 if(suid == null) {
1568 return -1;
1569 }
1570 return suid.userId;
1571 }
1572 }
1573
1574 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1575 int flags) {
1576 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001577 return chooseBestActivity(intent, resolvedType, flags, query);
1578 }
1579
Mihai Predaeae850c2009-05-13 10:13:48 +02001580 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1581 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 if (query != null) {
1583 final int N = query.size();
1584 if (N == 1) {
1585 return query.get(0);
1586 } else if (N > 1) {
1587 // If there is more than one activity with the same priority,
1588 // then let the user decide between them.
1589 ResolveInfo r0 = query.get(0);
1590 ResolveInfo r1 = query.get(1);
1591 if (false) {
1592 System.out.println(r0.activityInfo.name +
1593 "=" + r0.priority + " vs " +
1594 r1.activityInfo.name +
1595 "=" + r1.priority);
1596 }
1597 // If the first activity has a higher priority, or a different
1598 // default, then it is always desireable to pick it.
1599 if (r0.priority != r1.priority
1600 || r0.preferredOrder != r1.preferredOrder
1601 || r0.isDefault != r1.isDefault) {
1602 return query.get(0);
1603 }
1604 // If we have saved a preference for a preferred activity for
1605 // this Intent, use that.
1606 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1607 flags, query, r0.priority);
1608 if (ri != null) {
1609 return ri;
1610 }
1611 return mResolveInfo;
1612 }
1613 }
1614 return null;
1615 }
1616
1617 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1618 int flags, List<ResolveInfo> query, int priority) {
1619 synchronized (mPackages) {
1620 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1621 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001622 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1624 if (prefs != null && prefs.size() > 0) {
1625 // First figure out how good the original match set is.
1626 // We will only allow preferred activities that came
1627 // from the same match quality.
1628 int match = 0;
1629 final int N = query.size();
1630 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1631 for (int j=0; j<N; j++) {
1632 ResolveInfo ri = query.get(j);
1633 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1634 + ": 0x" + Integer.toHexString(match));
1635 if (ri.match > match) match = ri.match;
1636 }
1637 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1638 + Integer.toHexString(match));
1639 match &= IntentFilter.MATCH_CATEGORY_MASK;
1640 final int M = prefs.size();
1641 for (int i=0; i<M; i++) {
1642 PreferredActivity pa = prefs.get(i);
1643 if (pa.mMatch != match) {
1644 continue;
1645 }
1646 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1647 if (DEBUG_PREFERRED) {
1648 Log.v(TAG, "Got preferred activity:");
1649 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1650 }
1651 if (ai != null) {
1652 for (int j=0; j<N; j++) {
1653 ResolveInfo ri = query.get(j);
1654 if (!ri.activityInfo.applicationInfo.packageName
1655 .equals(ai.applicationInfo.packageName)) {
1656 continue;
1657 }
1658 if (!ri.activityInfo.name.equals(ai.name)) {
1659 continue;
1660 }
1661
1662 // Okay we found a previously set preferred app.
1663 // If the result set is different from when this
1664 // was created, we need to clear it and re-ask the
1665 // user their preference.
1666 if (!pa.sameSet(query, priority)) {
1667 Log.i(TAG, "Result set changed, dropping preferred activity for "
1668 + intent + " type " + resolvedType);
1669 mSettings.mPreferredActivities.removeFilter(pa);
1670 return null;
1671 }
1672
1673 // Yay!
1674 return ri;
1675 }
1676 }
1677 }
1678 }
1679 }
1680 return null;
1681 }
1682
1683 public List<ResolveInfo> queryIntentActivities(Intent intent,
1684 String resolvedType, int flags) {
1685 ComponentName comp = intent.getComponent();
1686 if (comp != null) {
1687 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1688 ActivityInfo ai = getActivityInfo(comp, flags);
1689 if (ai != null) {
1690 ResolveInfo ri = new ResolveInfo();
1691 ri.activityInfo = ai;
1692 list.add(ri);
1693 }
1694 return list;
1695 }
1696
1697 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001698 String pkgName = intent.getPackage();
1699 if (pkgName == null) {
1700 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1701 resolvedType, flags);
1702 }
1703 PackageParser.Package pkg = mPackages.get(pkgName);
1704 if (pkg != null) {
1705 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1706 resolvedType, flags, pkg.activities);
1707 }
1708 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
1710 }
1711
1712 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1713 Intent[] specifics, String[] specificTypes, Intent intent,
1714 String resolvedType, int flags) {
1715 final String resultsAction = intent.getAction();
1716
1717 List<ResolveInfo> results = queryIntentActivities(
1718 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1719 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1720
1721 int specificsPos = 0;
1722 int N;
1723
1724 // todo: note that the algorithm used here is O(N^2). This
1725 // isn't a problem in our current environment, but if we start running
1726 // into situations where we have more than 5 or 10 matches then this
1727 // should probably be changed to something smarter...
1728
1729 // First we go through and resolve each of the specific items
1730 // that were supplied, taking care of removing any corresponding
1731 // duplicate items in the generic resolve list.
1732 if (specifics != null) {
1733 for (int i=0; i<specifics.length; i++) {
1734 final Intent sintent = specifics[i];
1735 if (sintent == null) {
1736 continue;
1737 }
1738
1739 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1740 String action = sintent.getAction();
1741 if (resultsAction != null && resultsAction.equals(action)) {
1742 // If this action was explicitly requested, then don't
1743 // remove things that have it.
1744 action = null;
1745 }
1746 ComponentName comp = sintent.getComponent();
1747 ResolveInfo ri = null;
1748 ActivityInfo ai = null;
1749 if (comp == null) {
1750 ri = resolveIntent(
1751 sintent,
1752 specificTypes != null ? specificTypes[i] : null,
1753 flags);
1754 if (ri == null) {
1755 continue;
1756 }
1757 if (ri == mResolveInfo) {
1758 // ACK! Must do something better with this.
1759 }
1760 ai = ri.activityInfo;
1761 comp = new ComponentName(ai.applicationInfo.packageName,
1762 ai.name);
1763 } else {
1764 ai = getActivityInfo(comp, flags);
1765 if (ai == null) {
1766 continue;
1767 }
1768 }
1769
1770 // Look for any generic query activities that are duplicates
1771 // of this specific one, and remove them from the results.
1772 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1773 N = results.size();
1774 int j;
1775 for (j=specificsPos; j<N; j++) {
1776 ResolveInfo sri = results.get(j);
1777 if ((sri.activityInfo.name.equals(comp.getClassName())
1778 && sri.activityInfo.applicationInfo.packageName.equals(
1779 comp.getPackageName()))
1780 || (action != null && sri.filter.matchAction(action))) {
1781 results.remove(j);
1782 if (Config.LOGV) Log.v(
1783 TAG, "Removing duplicate item from " + j
1784 + " due to specific " + specificsPos);
1785 if (ri == null) {
1786 ri = sri;
1787 }
1788 j--;
1789 N--;
1790 }
1791 }
1792
1793 // Add this specific item to its proper place.
1794 if (ri == null) {
1795 ri = new ResolveInfo();
1796 ri.activityInfo = ai;
1797 }
1798 results.add(specificsPos, ri);
1799 ri.specificIndex = i;
1800 specificsPos++;
1801 }
1802 }
1803
1804 // Now we go through the remaining generic results and remove any
1805 // duplicate actions that are found here.
1806 N = results.size();
1807 for (int i=specificsPos; i<N-1; i++) {
1808 final ResolveInfo rii = results.get(i);
1809 if (rii.filter == null) {
1810 continue;
1811 }
1812
1813 // Iterate over all of the actions of this result's intent
1814 // filter... typically this should be just one.
1815 final Iterator<String> it = rii.filter.actionsIterator();
1816 if (it == null) {
1817 continue;
1818 }
1819 while (it.hasNext()) {
1820 final String action = it.next();
1821 if (resultsAction != null && resultsAction.equals(action)) {
1822 // If this action was explicitly requested, then don't
1823 // remove things that have it.
1824 continue;
1825 }
1826 for (int j=i+1; j<N; j++) {
1827 final ResolveInfo rij = results.get(j);
1828 if (rij.filter != null && rij.filter.hasAction(action)) {
1829 results.remove(j);
1830 if (Config.LOGV) Log.v(
1831 TAG, "Removing duplicate item from " + j
1832 + " due to action " + action + " at " + i);
1833 j--;
1834 N--;
1835 }
1836 }
1837 }
1838
1839 // If the caller didn't request filter information, drop it now
1840 // so we don't have to marshall/unmarshall it.
1841 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1842 rii.filter = null;
1843 }
1844 }
1845
1846 // Filter out the caller activity if so requested.
1847 if (caller != null) {
1848 N = results.size();
1849 for (int i=0; i<N; i++) {
1850 ActivityInfo ainfo = results.get(i).activityInfo;
1851 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1852 && caller.getClassName().equals(ainfo.name)) {
1853 results.remove(i);
1854 break;
1855 }
1856 }
1857 }
1858
1859 // If the caller didn't request filter information,
1860 // drop them now so we don't have to
1861 // marshall/unmarshall it.
1862 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1863 N = results.size();
1864 for (int i=0; i<N; i++) {
1865 results.get(i).filter = null;
1866 }
1867 }
1868
1869 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1870 return results;
1871 }
1872
1873 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1874 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001875 ComponentName comp = intent.getComponent();
1876 if (comp != null) {
1877 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1878 ActivityInfo ai = getReceiverInfo(comp, flags);
1879 if (ai != null) {
1880 ResolveInfo ri = new ResolveInfo();
1881 ri.activityInfo = ai;
1882 list.add(ri);
1883 }
1884 return list;
1885 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001888 String pkgName = intent.getPackage();
1889 if (pkgName == null) {
1890 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1891 resolvedType, flags);
1892 }
1893 PackageParser.Package pkg = mPackages.get(pkgName);
1894 if (pkg != null) {
1895 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1896 resolvedType, flags, pkg.receivers);
1897 }
1898 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
1900 }
1901
1902 public ResolveInfo resolveService(Intent intent, String resolvedType,
1903 int flags) {
1904 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1905 flags);
1906 if (query != null) {
1907 if (query.size() >= 1) {
1908 // If there is more than one service with the same priority,
1909 // just arbitrarily pick the first one.
1910 return query.get(0);
1911 }
1912 }
1913 return null;
1914 }
1915
1916 public List<ResolveInfo> queryIntentServices(Intent intent,
1917 String resolvedType, int flags) {
1918 ComponentName comp = intent.getComponent();
1919 if (comp != null) {
1920 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1921 ServiceInfo si = getServiceInfo(comp, flags);
1922 if (si != null) {
1923 ResolveInfo ri = new ResolveInfo();
1924 ri.serviceInfo = si;
1925 list.add(ri);
1926 }
1927 return list;
1928 }
1929
1930 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001931 String pkgName = intent.getPackage();
1932 if (pkgName == null) {
1933 return (List<ResolveInfo>)mServices.queryIntent(intent,
1934 resolvedType, flags);
1935 }
1936 PackageParser.Package pkg = mPackages.get(pkgName);
1937 if (pkg != null) {
1938 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1939 resolvedType, flags, pkg.services);
1940 }
1941 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 }
1943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 public List<PackageInfo> getInstalledPackages(int flags) {
1946 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1947
1948 synchronized (mPackages) {
1949 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1950 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1951 while (i.hasNext()) {
1952 final PackageSetting ps = i.next();
1953 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1954 if(psPkg != null) {
1955 finalList.add(psPkg);
1956 }
1957 }
1958 }
1959 else {
1960 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1961 while (i.hasNext()) {
1962 final PackageParser.Package p = i.next();
1963 if (p.applicationInfo != null) {
1964 PackageInfo pi = generatePackageInfo(p, flags);
1965 if(pi != null) {
1966 finalList.add(pi);
1967 }
1968 }
1969 }
1970 }
1971 }
1972 return finalList;
1973 }
1974
1975 public List<ApplicationInfo> getInstalledApplications(int flags) {
1976 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1977 synchronized(mPackages) {
1978 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1979 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1980 while (i.hasNext()) {
1981 final PackageSetting ps = i.next();
1982 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1983 if(ai != null) {
1984 finalList.add(ai);
1985 }
1986 }
1987 }
1988 else {
1989 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1990 while (i.hasNext()) {
1991 final PackageParser.Package p = i.next();
1992 if (p.applicationInfo != null) {
1993 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1994 if(ai != null) {
1995 finalList.add(ai);
1996 }
1997 }
1998 }
1999 }
2000 }
2001 return finalList;
2002 }
2003
2004 public List<ApplicationInfo> getPersistentApplications(int flags) {
2005 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2006
2007 synchronized (mPackages) {
2008 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2009 while (i.hasNext()) {
2010 PackageParser.Package p = i.next();
2011 if (p.applicationInfo != null
2012 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2013 && (!mSafeMode || (p.applicationInfo.flags
2014 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2015 finalList.add(p.applicationInfo);
2016 }
2017 }
2018 }
2019
2020 return finalList;
2021 }
2022
2023 public ProviderInfo resolveContentProvider(String name, int flags) {
2024 synchronized (mPackages) {
2025 final PackageParser.Provider provider = mProviders.get(name);
2026 return provider != null
2027 && mSettings.isEnabledLP(provider.info, flags)
2028 && (!mSafeMode || (provider.info.applicationInfo.flags
2029 &ApplicationInfo.FLAG_SYSTEM) != 0)
2030 ? PackageParser.generateProviderInfo(provider, flags)
2031 : null;
2032 }
2033 }
2034
Fred Quintana718d8a22009-04-29 17:53:20 -07002035 /**
2036 * @deprecated
2037 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 public void querySyncProviders(List outNames, List outInfo) {
2039 synchronized (mPackages) {
2040 Iterator<Map.Entry<String, PackageParser.Provider>> i
2041 = mProviders.entrySet().iterator();
2042
2043 while (i.hasNext()) {
2044 Map.Entry<String, PackageParser.Provider> entry = i.next();
2045 PackageParser.Provider p = entry.getValue();
2046
2047 if (p.syncable
2048 && (!mSafeMode || (p.info.applicationInfo.flags
2049 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2050 outNames.add(entry.getKey());
2051 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2052 }
2053 }
2054 }
2055 }
2056
2057 public List<ProviderInfo> queryContentProviders(String processName,
2058 int uid, int flags) {
2059 ArrayList<ProviderInfo> finalList = null;
2060
2061 synchronized (mPackages) {
2062 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2063 while (i.hasNext()) {
2064 PackageParser.Provider p = i.next();
2065 if (p.info.authority != null
2066 && (processName == null ||
2067 (p.info.processName.equals(processName)
2068 && p.info.applicationInfo.uid == uid))
2069 && mSettings.isEnabledLP(p.info, flags)
2070 && (!mSafeMode || (p.info.applicationInfo.flags
2071 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2072 if (finalList == null) {
2073 finalList = new ArrayList<ProviderInfo>(3);
2074 }
2075 finalList.add(PackageParser.generateProviderInfo(p,
2076 flags));
2077 }
2078 }
2079 }
2080
2081 if (finalList != null) {
2082 Collections.sort(finalList, mProviderInitOrderSorter);
2083 }
2084
2085 return finalList;
2086 }
2087
2088 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2089 int flags) {
2090 synchronized (mPackages) {
2091 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2092 return PackageParser.generateInstrumentationInfo(i, flags);
2093 }
2094 }
2095
2096 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2097 int flags) {
2098 ArrayList<InstrumentationInfo> finalList =
2099 new ArrayList<InstrumentationInfo>();
2100
2101 synchronized (mPackages) {
2102 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2103 while (i.hasNext()) {
2104 PackageParser.Instrumentation p = i.next();
2105 if (targetPackage == null
2106 || targetPackage.equals(p.info.targetPackage)) {
2107 finalList.add(PackageParser.generateInstrumentationInfo(p,
2108 flags));
2109 }
2110 }
2111 }
2112
2113 return finalList;
2114 }
2115
2116 private void scanDirLI(File dir, int flags, int scanMode) {
2117 Log.d(TAG, "Scanning app dir " + dir);
2118
2119 String[] files = dir.list();
2120
2121 int i;
2122 for (i=0; i<files.length; i++) {
2123 File file = new File(dir, files[i]);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002124 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002126 // Don't mess around with apps in system partition.
2127 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0) {
2128 // Delete the apk
2129 Log.w(TAG, "Cleaning up failed install of " + file);
2130 file.delete();
2131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 }
2133 }
2134
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002135 private static File getSettingsProblemFile() {
2136 File dataDir = Environment.getDataDirectory();
2137 File systemDir = new File(dataDir, "system");
2138 File fname = new File(systemDir, "uiderrors.txt");
2139 return fname;
2140 }
2141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 private static void reportSettingsProblem(int priority, String msg) {
2143 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002144 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 FileOutputStream out = new FileOutputStream(fname, true);
2146 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002147 SimpleDateFormat formatter = new SimpleDateFormat();
2148 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2149 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 pw.close();
2151 FileUtils.setPermissions(
2152 fname.toString(),
2153 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2154 -1, -1);
2155 } catch (java.io.IOException e) {
2156 }
2157 Log.println(priority, TAG, msg);
2158 }
2159
2160 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2161 PackageParser.Package pkg, File srcFile, int parseFlags) {
2162 if (GET_CERTIFICATES) {
2163 if (ps == null || !ps.codePath.equals(srcFile)
2164 || ps.getTimeStamp() != srcFile.lastModified()) {
2165 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2166 if (!pp.collectCertificates(pkg, parseFlags)) {
2167 mLastScanError = pp.getParseError();
2168 return false;
2169 }
2170 }
2171 }
2172 return true;
2173 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 /*
2176 * Scan a package and return the newly parsed package.
2177 * Returns null in case of errors and the error code is stored in mLastScanError
2178 */
2179 private PackageParser.Package scanPackageLI(File scanFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002180 int parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 int scanMode) {
2182 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002183 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002185 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002188 scanPath,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002189 mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 if (pkg == null) {
2191 mLastScanError = pp.getParseError();
2192 return null;
2193 }
2194 PackageSetting ps;
2195 PackageSetting updatedPkg;
2196 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002197 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
2199 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002200 // Verify certificates first
2201 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2202 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2203 return null;
2204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 if (updatedPkg != null) {
2206 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2207 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2208 }
2209 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2210 // Check for updated system applications here
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002211 if ((ps != null) && (!ps.codePath.equals(scanFile))) {
2212 if (pkg.mVersionCode < ps.versionCode) {
2213 // The system package has been updated and the code path does not match
2214 // Ignore entry. Just return
2215 Log.w(TAG, "Package:" + pkg.packageName +
2216 " has been updated. Ignoring the one from path:"+scanFile);
2217 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2218 return null;
2219 } else {
2220 // Delete the older apk pointed to by ps
2221 // At this point, its safely assumed that package installation for
2222 // apps in system partition will go through. If not there won't be a working
2223 // version of the app
2224 synchronized (mPackages) {
2225 // Just remove the loaded entries from package lists.
2226 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002227 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002228 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2229 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002230 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 }
2233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 // The apk is forward locked (not public) if its code and resources
2235 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002236 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002238 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002239 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002240
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002241 String codePath = null;
2242 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002243 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2244 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002245 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002246 } else {
2247 // Should not happen at all. Just log an error.
2248 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2249 }
2250 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002251 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002252 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002253 codePath = pkg.mScanPath;
2254 // Set application objects path explicitly.
2255 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002257 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 }
2259
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002260 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2261 String destCodePath, String destResPath) {
2262 pkg.mPath = pkg.mScanPath = destCodePath;
2263 pkg.applicationInfo.sourceDir = destCodePath;
2264 pkg.applicationInfo.publicSourceDir = destResPath;
2265 }
2266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 private static String fixProcessName(String defProcessName,
2268 String processName, int uid) {
2269 if (processName == null) {
2270 return defProcessName;
2271 }
2272 return processName;
2273 }
2274
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002275 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2277 if (pkg.mSignatures != null) {
2278 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2279 updateSignature)) {
2280 Log.e(TAG, "Package " + pkg.packageName
2281 + " signatures do not match the previously installed version; ignoring!");
2282 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2283 return false;
2284 }
2285
2286 if (pkgSetting.sharedUser != null) {
2287 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2288 pkg.mSignatures, updateSignature)) {
2289 Log.e(TAG, "Package " + pkg.packageName
2290 + " has no signatures that match those in shared user "
2291 + pkgSetting.sharedUser.name + "; ignoring!");
2292 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2293 return false;
2294 }
2295 }
2296 } else {
2297 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2298 }
2299 return true;
2300 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002301
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002302 public boolean performDexOpt(String packageName) {
2303 if (!mNoDexOpt) {
2304 return false;
2305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002306
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002307 PackageParser.Package p;
2308 synchronized (mPackages) {
2309 p = mPackages.get(packageName);
2310 if (p == null || p.mDidDexOpt) {
2311 return false;
2312 }
2313 }
2314 synchronized (mInstallLock) {
2315 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2316 }
2317 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002318
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002319 static final int DEX_OPT_SKIPPED = 0;
2320 static final int DEX_OPT_PERFORMED = 1;
2321 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002322
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002323 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2324 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002325 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002326 String path = pkg.mScanPath;
2327 int ret = 0;
2328 try {
2329 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002330 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002331 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002332 pkg.mDidDexOpt = true;
2333 performed = true;
2334 }
2335 } catch (FileNotFoundException e) {
2336 Log.w(TAG, "Apk not found for dexopt: " + path);
2337 ret = -1;
2338 } catch (IOException e) {
2339 Log.w(TAG, "Exception reading apk: " + path, e);
2340 ret = -1;
2341 }
2342 if (ret < 0) {
2343 //error from installer
2344 return DEX_OPT_FAILED;
2345 }
2346 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002347
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002348 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2349 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002350
2351 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2352 return Environment.isEncryptedFilesystemEnabled() &&
2353 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2354 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002355
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002356 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2357 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2358 Log.w(TAG, "Unable to update from " + oldPkg.name
2359 + " to " + newPkg.packageName
2360 + ": old package not in system partition");
2361 return false;
2362 } else if (mPackages.get(oldPkg.name) != null) {
2363 Log.w(TAG, "Unable to update from " + oldPkg.name
2364 + " to " + newPkg.packageName
2365 + ": old package still exists");
2366 return false;
2367 }
2368 return true;
2369 }
2370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 private PackageParser.Package scanPackageLI(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 PackageParser.Package pkg, int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002373 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002374 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2375 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002376 // Bail out. The resource and code paths haven't been set.
2377 Log.w(TAG, " Code and resource paths haven't been set correctly");
2378 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2379 return null;
2380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 mScanningPath = scanFile;
2382 if (pkg == null) {
2383 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2384 return null;
2385 }
2386
2387 final String pkgName = pkg.applicationInfo.packageName;
2388 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2389 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2390 }
2391
2392 if (pkgName.equals("android")) {
2393 synchronized (mPackages) {
2394 if (mAndroidApplication != null) {
2395 Log.w(TAG, "*************************************************");
2396 Log.w(TAG, "Core android package being redefined. Skipping.");
2397 Log.w(TAG, " file=" + mScanningPath);
2398 Log.w(TAG, "*************************************************");
2399 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2400 return null;
2401 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 // Set up information for our fall-back user intent resolution
2404 // activity.
2405 mPlatformPackage = pkg;
2406 pkg.mVersionCode = mSdkVersion;
2407 mAndroidApplication = pkg.applicationInfo;
2408 mResolveActivity.applicationInfo = mAndroidApplication;
2409 mResolveActivity.name = ResolverActivity.class.getName();
2410 mResolveActivity.packageName = mAndroidApplication.packageName;
2411 mResolveActivity.processName = mAndroidApplication.processName;
2412 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2413 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2414 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2415 mResolveActivity.exported = true;
2416 mResolveActivity.enabled = true;
2417 mResolveInfo.activityInfo = mResolveActivity;
2418 mResolveInfo.priority = 0;
2419 mResolveInfo.preferredOrder = 0;
2420 mResolveInfo.match = 0;
2421 mResolveComponentName = new ComponentName(
2422 mAndroidApplication.packageName, mResolveActivity.name);
2423 }
2424 }
2425
2426 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2427 TAG, "Scanning package " + pkgName);
2428 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2429 Log.w(TAG, "*************************************************");
2430 Log.w(TAG, "Application package " + pkgName
2431 + " already installed. Skipping duplicate.");
2432 Log.w(TAG, "*************************************************");
2433 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2434 return null;
2435 }
2436
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002437 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002438 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2439 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 SharedUserSetting suid = null;
2442 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 synchronized (mPackages) {
2447 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002448 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2449 if (mTmpSharedLibraries == null ||
2450 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2451 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2452 }
2453 int num = 0;
2454 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2455 for (int i=0; i<N; i++) {
2456 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 if (file == null) {
2458 Log.e(TAG, "Package " + pkg.packageName
2459 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002460 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2462 return null;
2463 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002464 mTmpSharedLibraries[num] = file;
2465 num++;
2466 }
2467 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2468 for (int i=0; i<N; i++) {
2469 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2470 if (file == null) {
2471 Log.w(TAG, "Package " + pkg.packageName
2472 + " desires unavailable shared library "
2473 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2474 } else {
2475 mTmpSharedLibraries[num] = file;
2476 num++;
2477 }
2478 }
2479 if (num > 0) {
2480 pkg.usesLibraryFiles = new String[num];
2481 System.arraycopy(mTmpSharedLibraries, 0,
2482 pkg.usesLibraryFiles, 0, num);
2483 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002484
Dianne Hackborn49237342009-08-27 20:08:01 -07002485 if (pkg.reqFeatures != null) {
2486 N = pkg.reqFeatures.size();
2487 for (int i=0; i<N; i++) {
2488 FeatureInfo fi = pkg.reqFeatures.get(i);
2489 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2490 // Don't care.
2491 continue;
2492 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002493
Dianne Hackborn49237342009-08-27 20:08:01 -07002494 if (fi.name != null) {
2495 if (mAvailableFeatures.get(fi.name) == null) {
2496 Log.e(TAG, "Package " + pkg.packageName
2497 + " requires unavailable feature "
2498 + fi.name + "; failing!");
2499 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2500 return null;
2501 }
2502 }
2503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 }
2505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 if (pkg.mSharedUserId != null) {
2508 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2509 pkg.applicationInfo.flags, true);
2510 if (suid == null) {
2511 Log.w(TAG, "Creating application package " + pkgName
2512 + " for shared user failed");
2513 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2514 return null;
2515 }
2516 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2517 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2518 + suid.userId + "): packages=" + suid.packages);
2519 }
2520 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002521
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002522 // Check if we are renaming from an original package name.
2523 PackageSetting origPackage = null;
2524 if (pkg.mOriginalPackage != null) {
2525 // We will only retrieve the setting for it if it already
2526 // exists; otherwise we need to make a new one later.
2527 origPackage = mSettings.peekPackageLP(pkg.mOriginalPackage);
2528 if (origPackage != null) {
2529 if (!verifyPackageUpdate(origPackage, pkg)) {
2530 origPackage = null;
2531 } else if (origPackage.sharedUser != null) {
2532 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2533 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2534 + " to " + pkg.packageName + ": old uid "
2535 + origPackage.sharedUser.name
2536 + " differs from " + pkg.mSharedUserId);
2537 origPackage = null;
2538 }
2539 } else {
2540 if (DEBUG_UPGRADE) Log.v(TAG, "Migrating data from "
2541 + origPackage.name + " to " + pkg.packageName);
2542 }
2543 }
2544 }
2545
2546 if (mTransferedPackages.contains(pkg.packageName)) {
2547 Log.w(TAG, "Package " + pkg.packageName
2548 + " was transferred to another, but its .apk remains");
2549 }
2550
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002551 // Just create the setting, don't add it yet. For already existing packages
2552 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002553 pkgSetting = mSettings.getPackageLP(pkg, origPackage, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 destResourceFile, pkg.applicationInfo.flags, true, false);
2555 if (pkgSetting == null) {
2556 Log.w(TAG, "Creating application package " + pkgName + " failed");
2557 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2558 return null;
2559 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002560 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2562 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 pkg.applicationInfo.uid = pkgSetting.userId;
2565 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002566
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002567 if (pkg.mAdoptPermissions != null) {
2568 // This package wants to adopt ownership of permissions from
2569 // another package.
2570 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2571 String origName = pkg.mAdoptPermissions.get(i);
2572 PackageSetting orig = mSettings.peekPackageLP(origName);
2573 if (orig != null) {
2574 if (verifyPackageUpdate(orig, pkg)) {
2575 if (DEBUG_UPGRADE) Log.v(TAG, "Adopting permissions from "
2576 + origName + " to " + pkg.packageName);
2577 mSettings.transferPermissions(origName, pkg.packageName);
2578 }
2579 }
2580 }
2581 }
2582
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002583 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2585 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2586 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2587 return null;
2588 }
2589 // The signature has changed, but this package is in the system
2590 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002591 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 // However... if this package is part of a shared user, but it
2593 // doesn't match the signature of the shared user, let's fail.
2594 // What this means is that you can't change the signatures
2595 // associated with an overall shared user, which doesn't seem all
2596 // that unreasonable.
2597 if (pkgSetting.sharedUser != null) {
2598 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2599 pkg.mSignatures, false)) {
2600 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2601 return null;
2602 }
2603 }
2604 removeExisting = true;
2605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002606
The Android Open Source Project10592532009-03-18 17:39:46 -07002607 // Verify that this new package doesn't have any content providers
2608 // that conflict with existing packages. Only do this if the
2609 // package isn't already installed, since we don't want to break
2610 // things that are installed.
2611 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2612 int N = pkg.providers.size();
2613 int i;
2614 for (i=0; i<N; i++) {
2615 PackageParser.Provider p = pkg.providers.get(i);
2616 String names[] = p.info.authority.split(";");
2617 for (int j = 0; j < names.length; j++) {
2618 if (mProviders.containsKey(names[j])) {
2619 PackageParser.Provider other = mProviders.get(names[j]);
2620 Log.w(TAG, "Can't install because provider name " + names[j] +
2621 " (in package " + pkg.applicationInfo.packageName +
2622 ") is already used by "
2623 + ((other != null && other.component != null)
2624 ? other.component.getPackageName() : "?"));
2625 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2626 return null;
2627 }
2628 }
2629 }
2630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 }
2632
2633 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002634 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002636 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 if (ret != 0) {
2638 String msg = "System package " + pkg.packageName
2639 + " could not have data directory erased after signature change.";
2640 reportSettingsProblem(Log.WARN, msg);
2641 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2642 return null;
2643 }
2644 }
2645 Log.w(TAG, "System package " + pkg.packageName
2646 + " signature changed: existing data removed.");
2647 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2648 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 long scanFileTime = scanFile.lastModified();
2651 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2652 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2653 pkg.applicationInfo.processName = fixProcessName(
2654 pkg.applicationInfo.packageName,
2655 pkg.applicationInfo.processName,
2656 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657
2658 File dataPath;
2659 if (mPlatformPackage == pkg) {
2660 // The system package is special.
2661 dataPath = new File (Environment.getDataDirectory(), "system");
2662 pkg.applicationInfo.dataDir = dataPath.getPath();
2663 } else {
2664 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002665 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2666 if (useEncryptedFSDir) {
2667 dataPath = new File(mSecureAppDataDir, pkgName);
2668 } else {
2669 dataPath = new File(mAppDataDir, pkgName);
2670 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002671
2672 boolean uidError = false;
2673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 if (dataPath.exists()) {
2675 mOutPermissions[1] = 0;
2676 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2677 if (mOutPermissions[1] == pkg.applicationInfo.uid
2678 || !Process.supportsProcesses()) {
2679 pkg.applicationInfo.dataDir = dataPath.getPath();
2680 } else {
2681 boolean recovered = false;
2682 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2683 // If this is a system app, we can at least delete its
2684 // current data so the application will still work.
2685 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002686 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002687 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 // Old data gone!
2689 String msg = "System package " + pkg.packageName
2690 + " has changed from uid: "
2691 + mOutPermissions[1] + " to "
2692 + pkg.applicationInfo.uid + "; old data erased";
2693 reportSettingsProblem(Log.WARN, msg);
2694 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002697 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 pkg.applicationInfo.uid);
2699 if (ret == -1) {
2700 // Ack should not happen!
2701 msg = "System package " + pkg.packageName
2702 + " could not have data directory re-created after delete.";
2703 reportSettingsProblem(Log.WARN, msg);
2704 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2705 return null;
2706 }
2707 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 if (!recovered) {
2710 mHasSystemUidErrors = true;
2711 }
2712 }
2713 if (!recovered) {
2714 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2715 + pkg.applicationInfo.uid + "/fs_"
2716 + mOutPermissions[1];
2717 String msg = "Package " + pkg.packageName
2718 + " has mismatched uid: "
2719 + mOutPermissions[1] + " on disk, "
2720 + pkg.applicationInfo.uid + " in settings";
2721 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002722 mSettings.mReadMessages.append(msg);
2723 mSettings.mReadMessages.append('\n');
2724 uidError = true;
2725 if (!pkgSetting.uidError) {
2726 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 }
2729 }
2730 }
2731 pkg.applicationInfo.dataDir = dataPath.getPath();
2732 } else {
2733 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2734 Log.v(TAG, "Want this data dir: " + dataPath);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002735 if (pkgSetting.origPackage != null) {
2736 synchronized (mPackages) {
2737 // This package is being update from another; rename the
2738 // old one's data dir.
2739 String msg = "Transfering data from old package "
2740 + pkgSetting.origPackage.name + " to new package "
2741 + pkgSetting.name;
2742 reportSettingsProblem(Log.WARN, msg);
2743 if (mInstaller != null) {
2744 int ret = mInstaller.rename(pkgSetting.origPackage.name,
2745 pkgName, useEncryptedFSDir);
2746 if(ret < 0) {
2747 msg = "Error transfering data from old package "
2748 + pkgSetting.origPackage.name + " to new package "
2749 + pkgSetting.name;
2750 reportSettingsProblem(Log.WARN, msg);
2751 }
2752 }
2753 // And now uninstall the old package.
2754 mInstaller.remove(pkgSetting.origPackage.name, useEncryptedFSDir);
2755 mSettings.removePackageLP(pkgSetting.origPackage.name);
2756 }
2757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 //invoke installer to do the actual installation
2759 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002760 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 pkg.applicationInfo.uid);
2762 if(ret < 0) {
2763 // Error from installer
2764 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2765 return null;
2766 }
2767 } else {
2768 dataPath.mkdirs();
2769 if (dataPath.exists()) {
2770 FileUtils.setPermissions(
2771 dataPath.toString(),
2772 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2773 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2774 }
2775 }
2776 if (dataPath.exists()) {
2777 pkg.applicationInfo.dataDir = dataPath.getPath();
2778 } else {
2779 Log.w(TAG, "Unable to create data directory: " + dataPath);
2780 pkg.applicationInfo.dataDir = null;
2781 }
2782 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002783
2784 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 }
2786
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002787 // No longer need to retain this.
2788 if (pkgSetting.origPackage != null) {
2789 mTransferedPackages.add(pkgSetting.origPackage.name);
2790 pkgSetting.origPackage = null;
2791 }
2792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 // Perform shared library installation and dex validation and
2794 // optimization, if this is not a system app.
2795 if (mInstaller != null) {
2796 String path = scanFile.getPath();
2797 if (scanFileNewer) {
2798 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002799 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2800 if (err != PackageManager.INSTALL_SUCCEEDED) {
2801 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 return null;
2803 }
2804 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002805 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002806
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002807 if ((scanMode&SCAN_NO_DEX) == 0) {
2808 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2810 return null;
2811 }
2812 }
2813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 if (mFactoryTest && pkg.requestedPermissions.contains(
2816 android.Manifest.permission.FACTORY_TEST)) {
2817 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2818 }
2819
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002820 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 if ((scanMode&SCAN_MONITOR) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 mAppDirs.put(pkg.mPath, pkg);
2823 }
2824
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002825 // Request the ActivityManager to kill the process(only for existing packages)
2826 // so that we do not end up in a confused state while the user is still using the older
2827 // version of the application while the new one gets installed.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002828 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0) {
2829 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002830 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002831 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002835 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002837 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08002838 // Make sure we don't accidentally delete its data.
2839 mSettings.mPackagesToBeCleaned.remove(pkgName);
2840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 int N = pkg.providers.size();
2842 StringBuilder r = null;
2843 int i;
2844 for (i=0; i<N; i++) {
2845 PackageParser.Provider p = pkg.providers.get(i);
2846 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2847 p.info.processName, pkg.applicationInfo.uid);
2848 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2849 p.info.name), p);
2850 p.syncable = p.info.isSyncable;
2851 String names[] = p.info.authority.split(";");
2852 p.info.authority = null;
2853 for (int j = 0; j < names.length; j++) {
2854 if (j == 1 && p.syncable) {
2855 // We only want the first authority for a provider to possibly be
2856 // syncable, so if we already added this provider using a different
2857 // authority clear the syncable flag. We copy the provider before
2858 // changing it because the mProviders object contains a reference
2859 // to a provider that we don't want to change.
2860 // Only do this for the second authority since the resulting provider
2861 // object can be the same for all future authorities for this provider.
2862 p = new PackageParser.Provider(p);
2863 p.syncable = false;
2864 }
2865 if (!mProviders.containsKey(names[j])) {
2866 mProviders.put(names[j], p);
2867 if (p.info.authority == null) {
2868 p.info.authority = names[j];
2869 } else {
2870 p.info.authority = p.info.authority + ";" + names[j];
2871 }
2872 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2873 Log.d(TAG, "Registered content provider: " + names[j] +
2874 ", className = " + p.info.name +
2875 ", isSyncable = " + p.info.isSyncable);
2876 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002877 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 Log.w(TAG, "Skipping provider name " + names[j] +
2879 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002880 "): name already used by "
2881 + ((other != null && other.component != null)
2882 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 }
2884 }
2885 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2886 if (r == null) {
2887 r = new StringBuilder(256);
2888 } else {
2889 r.append(' ');
2890 }
2891 r.append(p.info.name);
2892 }
2893 }
2894 if (r != null) {
2895 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 N = pkg.services.size();
2899 r = null;
2900 for (i=0; i<N; i++) {
2901 PackageParser.Service s = pkg.services.get(i);
2902 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2903 s.info.processName, pkg.applicationInfo.uid);
2904 mServices.addService(s);
2905 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2906 if (r == null) {
2907 r = new StringBuilder(256);
2908 } else {
2909 r.append(' ');
2910 }
2911 r.append(s.info.name);
2912 }
2913 }
2914 if (r != null) {
2915 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 N = pkg.receivers.size();
2919 r = null;
2920 for (i=0; i<N; i++) {
2921 PackageParser.Activity a = pkg.receivers.get(i);
2922 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2923 a.info.processName, pkg.applicationInfo.uid);
2924 mReceivers.addActivity(a, "receiver");
2925 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2926 if (r == null) {
2927 r = new StringBuilder(256);
2928 } else {
2929 r.append(' ');
2930 }
2931 r.append(a.info.name);
2932 }
2933 }
2934 if (r != null) {
2935 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2936 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 N = pkg.activities.size();
2939 r = null;
2940 for (i=0; i<N; i++) {
2941 PackageParser.Activity a = pkg.activities.get(i);
2942 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2943 a.info.processName, pkg.applicationInfo.uid);
2944 mActivities.addActivity(a, "activity");
2945 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2946 if (r == null) {
2947 r = new StringBuilder(256);
2948 } else {
2949 r.append(' ');
2950 }
2951 r.append(a.info.name);
2952 }
2953 }
2954 if (r != null) {
2955 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2956 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 N = pkg.permissionGroups.size();
2959 r = null;
2960 for (i=0; i<N; i++) {
2961 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2962 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2963 if (cur == null) {
2964 mPermissionGroups.put(pg.info.name, pg);
2965 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2966 if (r == null) {
2967 r = new StringBuilder(256);
2968 } else {
2969 r.append(' ');
2970 }
2971 r.append(pg.info.name);
2972 }
2973 } else {
2974 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2975 + pg.info.packageName + " ignored: original from "
2976 + cur.info.packageName);
2977 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2978 if (r == null) {
2979 r = new StringBuilder(256);
2980 } else {
2981 r.append(' ');
2982 }
2983 r.append("DUP:");
2984 r.append(pg.info.name);
2985 }
2986 }
2987 }
2988 if (r != null) {
2989 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2990 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 N = pkg.permissions.size();
2993 r = null;
2994 for (i=0; i<N; i++) {
2995 PackageParser.Permission p = pkg.permissions.get(i);
2996 HashMap<String, BasePermission> permissionMap =
2997 p.tree ? mSettings.mPermissionTrees
2998 : mSettings.mPermissions;
2999 p.group = mPermissionGroups.get(p.info.group);
3000 if (p.info.group == null || p.group != null) {
3001 BasePermission bp = permissionMap.get(p.info.name);
3002 if (bp == null) {
3003 bp = new BasePermission(p.info.name, p.info.packageName,
3004 BasePermission.TYPE_NORMAL);
3005 permissionMap.put(p.info.name, bp);
3006 }
3007 if (bp.perm == null) {
3008 if (bp.sourcePackage == null
3009 || bp.sourcePackage.equals(p.info.packageName)) {
3010 BasePermission tree = findPermissionTreeLP(p.info.name);
3011 if (tree == null
3012 || tree.sourcePackage.equals(p.info.packageName)) {
3013 bp.perm = p;
3014 bp.uid = pkg.applicationInfo.uid;
3015 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3016 if (r == null) {
3017 r = new StringBuilder(256);
3018 } else {
3019 r.append(' ');
3020 }
3021 r.append(p.info.name);
3022 }
3023 } else {
3024 Log.w(TAG, "Permission " + p.info.name + " from package "
3025 + p.info.packageName + " ignored: base tree "
3026 + tree.name + " is from package "
3027 + tree.sourcePackage);
3028 }
3029 } else {
3030 Log.w(TAG, "Permission " + p.info.name + " from package "
3031 + p.info.packageName + " ignored: original from "
3032 + bp.sourcePackage);
3033 }
3034 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3035 if (r == null) {
3036 r = new StringBuilder(256);
3037 } else {
3038 r.append(' ');
3039 }
3040 r.append("DUP:");
3041 r.append(p.info.name);
3042 }
3043 } else {
3044 Log.w(TAG, "Permission " + p.info.name + " from package "
3045 + p.info.packageName + " ignored: no group "
3046 + p.group);
3047 }
3048 }
3049 if (r != null) {
3050 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 N = pkg.instrumentation.size();
3054 r = null;
3055 for (i=0; i<N; i++) {
3056 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3057 a.info.packageName = pkg.applicationInfo.packageName;
3058 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3059 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3060 a.info.dataDir = pkg.applicationInfo.dataDir;
3061 mInstrumentation.put(a.component, a);
3062 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3063 if (r == null) {
3064 r = new StringBuilder(256);
3065 } else {
3066 r.append(' ');
3067 }
3068 r.append(a.info.name);
3069 }
3070 }
3071 if (r != null) {
3072 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3073 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003074
Dianne Hackborn854060af2009-07-09 18:14:31 -07003075 if (pkg.protectedBroadcasts != null) {
3076 N = pkg.protectedBroadcasts.size();
3077 for (i=0; i<N; i++) {
3078 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3079 }
3080 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 pkgSetting.setTimeStamp(scanFileTime);
3083 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 return pkg;
3086 }
3087
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003088 private void killApplication(String pkgName, int uid) {
3089 // Request the ActivityManager to kill the process(only for existing packages)
3090 // so that we do not end up in a confused state while the user is still using the older
3091 // version of the application while the new one gets installed.
3092 IActivityManager am = ActivityManagerNative.getDefault();
3093 if (am != null) {
3094 try {
3095 am.killApplicationWithUid(pkgName, uid);
3096 } catch (RemoteException e) {
3097 }
3098 }
3099 }
3100
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003101 // The following constants are returned by cachePackageSharedLibsForAbiLI
3102 // to indicate if native shared libraries were found in the package.
3103 // Values are:
3104 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3105 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3106 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3107 // in package (and not installed)
3108 //
3109 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3110 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3111 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003113 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3114 // and automatically copy them to /data/data/<appname>/lib if present.
3115 //
3116 // NOTE: this method may throw an IOException if the library cannot
3117 // be copied to its final destination, e.g. if there isn't enough
3118 // room left on the data partition, or a ZipException if the package
3119 // file is malformed.
3120 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003121 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3122 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003123 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3124 final String apkLib = "lib/";
3125 final int apkLibLen = apkLib.length();
3126 final int cpuAbiLen = cpuAbi.length();
3127 final String libPrefix = "lib";
3128 final int libPrefixLen = libPrefix.length();
3129 final String libSuffix = ".so";
3130 final int libSuffixLen = libSuffix.length();
3131 boolean hasNativeLibraries = false;
3132 boolean installedNativeLibraries = false;
3133
3134 // the minimum length of a valid native shared library of the form
3135 // lib/<something>/lib<name>.so.
3136 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3137
3138 ZipFile zipFile = new ZipFile(scanFile);
3139 Enumeration<ZipEntry> entries =
3140 (Enumeration<ZipEntry>) zipFile.entries();
3141
3142 while (entries.hasMoreElements()) {
3143 ZipEntry entry = entries.nextElement();
3144 // skip directories
3145 if (entry.isDirectory()) {
3146 continue;
3147 }
3148 String entryName = entry.getName();
3149
3150 // check that the entry looks like lib/<something>/lib<name>.so
3151 // here, but don't check the ABI just yet.
3152 //
3153 // - must be sufficiently long
3154 // - must end with libSuffix, i.e. ".so"
3155 // - must start with apkLib, i.e. "lib/"
3156 if (entryName.length() < minEntryLen ||
3157 !entryName.endsWith(libSuffix) ||
3158 !entryName.startsWith(apkLib) ) {
3159 continue;
3160 }
3161
3162 // file name must start with libPrefix, i.e. "lib"
3163 int lastSlash = entryName.lastIndexOf('/');
3164
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003165 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003166 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3167 continue;
3168 }
3169
3170 hasNativeLibraries = true;
3171
3172 // check the cpuAbi now, between lib/ and /lib<name>.so
3173 //
3174 if (lastSlash != apkLibLen + cpuAbiLen ||
3175 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3176 continue;
3177
3178 // extract the library file name, ensure it doesn't contain
3179 // weird characters. we're guaranteed here that it doesn't contain
3180 // a directory separator though.
3181 String libFileName = entryName.substring(lastSlash+1);
3182 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3183 continue;
3184 }
3185
3186 installedNativeLibraries = true;
3187
3188 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3189 File.separator + libFileName;
3190 File sharedLibraryFile = new File(sharedLibraryFilePath);
3191 if (! sharedLibraryFile.exists() ||
3192 sharedLibraryFile.length() != entry.getSize() ||
3193 sharedLibraryFile.lastModified() != entry.getTime()) {
3194 if (Config.LOGD) {
3195 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003197 if (mInstaller == null) {
3198 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003199 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003200 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003201 sharedLibraryFile);
3202 }
3203 }
3204 if (!hasNativeLibraries)
3205 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3206
3207 if (!installedNativeLibraries)
3208 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3209
3210 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3211 }
3212
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003213 // Find the gdbserver executable program in a package at
3214 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3215 //
3216 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3217 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3218 //
3219 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3220 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3221 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3222 final String GDBSERVER = "gdbserver";
3223 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3224
3225 ZipFile zipFile = new ZipFile(scanFile);
3226 Enumeration<ZipEntry> entries =
3227 (Enumeration<ZipEntry>) zipFile.entries();
3228
3229 while (entries.hasMoreElements()) {
3230 ZipEntry entry = entries.nextElement();
3231 // skip directories
3232 if (entry.isDirectory()) {
3233 continue;
3234 }
3235 String entryName = entry.getName();
3236
3237 if (!entryName.equals(apkGdbServerPath)) {
3238 continue;
3239 }
3240
3241 String installGdbServerPath = installGdbServerDir.getPath() +
3242 "/" + GDBSERVER;
3243 File installGdbServerFile = new File(installGdbServerPath);
3244 if (! installGdbServerFile.exists() ||
3245 installGdbServerFile.length() != entry.getSize() ||
3246 installGdbServerFile.lastModified() != entry.getTime()) {
3247 if (Config.LOGD) {
3248 Log.d(TAG, "Caching gdbserver " + entry.getName());
3249 }
3250 if (mInstaller == null) {
3251 installGdbServerDir.mkdir();
3252 }
3253 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3254 installGdbServerFile);
3255 }
3256 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3257 }
3258 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3259 }
3260
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003261 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3262 // and copy them to /data/data/<appname>/lib.
3263 //
3264 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3265 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3266 // one if ro.product.cpu.abi2 is defined.
3267 //
3268 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3269 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003270 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003271 try {
3272 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3273
3274 // some architectures are capable of supporting several CPU ABIs
3275 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3276 // this is indicated by the definition of the ro.product.cpu.abi2
3277 // system property.
3278 //
3279 // only scan the package twice in case of ABI mismatch
3280 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003281 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003282 if (cpuAbi2 != null) {
3283 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003285
3286 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3287 Log.w(TAG,"Native ABI mismatch from package file");
3288 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003290
3291 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3292 cpuAbi = cpuAbi2;
3293 }
3294 }
3295
3296 // for debuggable packages, also extract gdbserver from lib/<abi>
3297 // into /data/data/<appname>/lib too.
3298 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3299 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3300 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3301 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3302 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003305 } catch (ZipException e) {
3306 Log.w(TAG, "Failed to extract data from package file", e);
3307 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003309 Log.w(TAG, "Failed to cache package shared libs", e);
3310 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003312 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 }
3314
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003315 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003317 File binaryDir,
3318 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 InputStream inputStream = zipFile.getInputStream(entry);
3320 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003321 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003323 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 // now need to be left as world readable and owned by the system.
3325 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3326 ! tempFile.setLastModified(entry.getTime()) ||
3327 FileUtils.setPermissions(tempFilePath,
3328 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003329 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003331 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 // Failed to properly write file.
3333 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003334 throw new IOException("Couldn't create cached binary "
3335 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 }
3337 } finally {
3338 inputStream.close();
3339 }
3340 }
3341
3342 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3343 if (chatty && Config.LOGD) Log.d(
3344 TAG, "Removing package " + pkg.applicationInfo.packageName );
3345
3346 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 mPackages.remove(pkg.applicationInfo.packageName);
3350 if (pkg.mPath != null) {
3351 mAppDirs.remove(pkg.mPath);
3352 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 PackageSetting ps = (PackageSetting)pkg.mExtras;
3355 if (ps != null && ps.sharedUser != null) {
3356 // XXX don't do this until the data is removed.
3357 if (false) {
3358 ps.sharedUser.packages.remove(ps);
3359 if (ps.sharedUser.packages.size() == 0) {
3360 // Remove.
3361 }
3362 }
3363 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 int N = pkg.providers.size();
3366 StringBuilder r = null;
3367 int i;
3368 for (i=0; i<N; i++) {
3369 PackageParser.Provider p = pkg.providers.get(i);
3370 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3371 p.info.name));
3372 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 /* The is another ContentProvider with this authority when
3375 * this app was installed so this authority is null,
3376 * Ignore it as we don't have to unregister the provider.
3377 */
3378 continue;
3379 }
3380 String names[] = p.info.authority.split(";");
3381 for (int j = 0; j < names.length; j++) {
3382 if (mProviders.get(names[j]) == p) {
3383 mProviders.remove(names[j]);
3384 if (chatty && Config.LOGD) Log.d(
3385 TAG, "Unregistered content provider: " + names[j] +
3386 ", className = " + p.info.name +
3387 ", isSyncable = " + p.info.isSyncable);
3388 }
3389 }
3390 if (chatty) {
3391 if (r == null) {
3392 r = new StringBuilder(256);
3393 } else {
3394 r.append(' ');
3395 }
3396 r.append(p.info.name);
3397 }
3398 }
3399 if (r != null) {
3400 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3401 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 N = pkg.services.size();
3404 r = null;
3405 for (i=0; i<N; i++) {
3406 PackageParser.Service s = pkg.services.get(i);
3407 mServices.removeService(s);
3408 if (chatty) {
3409 if (r == null) {
3410 r = new StringBuilder(256);
3411 } else {
3412 r.append(' ');
3413 }
3414 r.append(s.info.name);
3415 }
3416 }
3417 if (r != null) {
3418 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3419 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 N = pkg.receivers.size();
3422 r = null;
3423 for (i=0; i<N; i++) {
3424 PackageParser.Activity a = pkg.receivers.get(i);
3425 mReceivers.removeActivity(a, "receiver");
3426 if (chatty) {
3427 if (r == null) {
3428 r = new StringBuilder(256);
3429 } else {
3430 r.append(' ');
3431 }
3432 r.append(a.info.name);
3433 }
3434 }
3435 if (r != null) {
3436 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3437 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 N = pkg.activities.size();
3440 r = null;
3441 for (i=0; i<N; i++) {
3442 PackageParser.Activity a = pkg.activities.get(i);
3443 mActivities.removeActivity(a, "activity");
3444 if (chatty) {
3445 if (r == null) {
3446 r = new StringBuilder(256);
3447 } else {
3448 r.append(' ');
3449 }
3450 r.append(a.info.name);
3451 }
3452 }
3453 if (r != null) {
3454 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3455 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 N = pkg.permissions.size();
3458 r = null;
3459 for (i=0; i<N; i++) {
3460 PackageParser.Permission p = pkg.permissions.get(i);
3461 boolean tree = false;
3462 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3463 if (bp == null) {
3464 tree = true;
3465 bp = mSettings.mPermissionTrees.get(p.info.name);
3466 }
3467 if (bp != null && bp.perm == p) {
3468 if (bp.type != BasePermission.TYPE_BUILTIN) {
3469 if (tree) {
3470 mSettings.mPermissionTrees.remove(p.info.name);
3471 } else {
3472 mSettings.mPermissions.remove(p.info.name);
3473 }
3474 } else {
3475 bp.perm = null;
3476 }
3477 if (chatty) {
3478 if (r == null) {
3479 r = new StringBuilder(256);
3480 } else {
3481 r.append(' ');
3482 }
3483 r.append(p.info.name);
3484 }
3485 }
3486 }
3487 if (r != null) {
3488 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3489 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 N = pkg.instrumentation.size();
3492 r = null;
3493 for (i=0; i<N; i++) {
3494 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3495 mInstrumentation.remove(a.component);
3496 if (chatty) {
3497 if (r == null) {
3498 r = new StringBuilder(256);
3499 } else {
3500 r.append(' ');
3501 }
3502 r.append(a.info.name);
3503 }
3504 }
3505 if (r != null) {
3506 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3507 }
3508 }
3509 }
3510
3511 private static final boolean isPackageFilename(String name) {
3512 return name != null && name.endsWith(".apk");
3513 }
3514
3515 private void updatePermissionsLP() {
3516 // Make sure there are no dangling permission trees.
3517 Iterator<BasePermission> it = mSettings.mPermissionTrees
3518 .values().iterator();
3519 while (it.hasNext()) {
3520 BasePermission bp = it.next();
3521 if (bp.perm == null) {
3522 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3523 + " from package " + bp.sourcePackage);
3524 it.remove();
3525 }
3526 }
3527
3528 // Make sure all dynamic permissions have been assigned to a package,
3529 // and make sure there are no dangling permissions.
3530 it = mSettings.mPermissions.values().iterator();
3531 while (it.hasNext()) {
3532 BasePermission bp = it.next();
3533 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3534 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3535 + bp.name + " pkg=" + bp.sourcePackage
3536 + " info=" + bp.pendingInfo);
3537 if (bp.perm == null && bp.pendingInfo != null) {
3538 BasePermission tree = findPermissionTreeLP(bp.name);
3539 if (tree != null) {
3540 bp.perm = new PackageParser.Permission(tree.perm.owner,
3541 new PermissionInfo(bp.pendingInfo));
3542 bp.perm.info.packageName = tree.perm.info.packageName;
3543 bp.perm.info.name = bp.name;
3544 bp.uid = tree.uid;
3545 }
3546 }
3547 }
3548 if (bp.perm == null) {
3549 Log.w(TAG, "Removing dangling permission: " + bp.name
3550 + " from package " + bp.sourcePackage);
3551 it.remove();
3552 }
3553 }
3554
3555 // Now update the permissions for all packages, in particular
3556 // replace the granted permissions of the system packages.
3557 for (PackageParser.Package pkg : mPackages.values()) {
3558 grantPermissionsLP(pkg, false);
3559 }
3560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3563 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3564 if (ps == null) {
3565 return;
3566 }
3567 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3568 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 if (replace) {
3571 ps.permissionsFixed = false;
3572 if (gp == ps) {
3573 gp.grantedPermissions.clear();
3574 gp.gids = mGlobalGids;
3575 }
3576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 if (gp.gids == null) {
3579 gp.gids = mGlobalGids;
3580 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 final int N = pkg.requestedPermissions.size();
3583 for (int i=0; i<N; i++) {
3584 String name = pkg.requestedPermissions.get(i);
3585 BasePermission bp = mSettings.mPermissions.get(name);
3586 PackageParser.Permission p = bp != null ? bp.perm : null;
3587 if (false) {
3588 if (gp != ps) {
3589 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3590 + ": " + p);
3591 }
3592 }
3593 if (p != null) {
3594 final String perm = p.info.name;
3595 boolean allowed;
3596 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3597 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3598 allowed = true;
3599 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3600 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003601 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003603 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 == PackageManager.SIGNATURE_MATCH);
3605 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3606 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3607 // For updated system applications, the signatureOrSystem permission
3608 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003609 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3611 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3612 if(sysPs.grantedPermissions.contains(perm)) {
3613 allowed = true;
3614 } else {
3615 allowed = false;
3616 }
3617 } else {
3618 allowed = true;
3619 }
3620 }
3621 }
3622 } else {
3623 allowed = false;
3624 }
3625 if (false) {
3626 if (gp != ps) {
3627 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3628 }
3629 }
3630 if (allowed) {
3631 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3632 && ps.permissionsFixed) {
3633 // If this is an existing, non-system package, then
3634 // we can't add any new permissions to it.
3635 if (!gp.loadedPermissions.contains(perm)) {
3636 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003637 // Except... if this is a permission that was added
3638 // to the platform (note: need to only do this when
3639 // updating the platform).
3640 final int NP = PackageParser.NEW_PERMISSIONS.length;
3641 for (int ip=0; ip<NP; ip++) {
3642 final PackageParser.NewPermissionInfo npi
3643 = PackageParser.NEW_PERMISSIONS[ip];
3644 if (npi.name.equals(perm)
3645 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3646 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003647 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003648 + pkg.packageName);
3649 break;
3650 }
3651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 }
3653 }
3654 if (allowed) {
3655 if (!gp.grantedPermissions.contains(perm)) {
3656 addedPermission = true;
3657 gp.grantedPermissions.add(perm);
3658 gp.gids = appendInts(gp.gids, bp.gids);
3659 }
3660 } else {
3661 Log.w(TAG, "Not granting permission " + perm
3662 + " to package " + pkg.packageName
3663 + " because it was previously installed without");
3664 }
3665 } else {
3666 Log.w(TAG, "Not granting permission " + perm
3667 + " to package " + pkg.packageName
3668 + " (protectionLevel=" + p.info.protectionLevel
3669 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3670 + ")");
3671 }
3672 } else {
3673 Log.w(TAG, "Unknown permission " + name
3674 + " in package " + pkg.packageName);
3675 }
3676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003679 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3680 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 // This is the first that we have heard about this package, so the
3682 // permissions we have now selected are fixed until explicitly
3683 // changed.
3684 ps.permissionsFixed = true;
3685 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3686 }
3687 }
3688
3689 private final class ActivityIntentResolver
3690 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003691 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003693 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 }
3695
Mihai Preda074edef2009-05-18 17:13:31 +02003696 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003698 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3700 }
3701
Mihai Predaeae850c2009-05-13 10:13:48 +02003702 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3703 ArrayList<PackageParser.Activity> packageActivities) {
3704 if (packageActivities == null) {
3705 return null;
3706 }
3707 mFlags = flags;
3708 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3709 int N = packageActivities.size();
3710 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3711 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003712
3713 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003714 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003715 intentFilters = packageActivities.get(i).intents;
3716 if (intentFilters != null && intentFilters.size() > 0) {
3717 listCut.add(intentFilters);
3718 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003719 }
3720 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3721 }
3722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 public final void addActivity(PackageParser.Activity a, String type) {
3724 mActivities.put(a.component, a);
3725 if (SHOW_INFO || Config.LOGV) Log.v(
3726 TAG, " " + type + " " +
3727 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3728 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3729 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003730 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3732 if (SHOW_INFO || Config.LOGV) {
3733 Log.v(TAG, " IntentFilter:");
3734 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3735 }
3736 if (!intent.debugCheck()) {
3737 Log.w(TAG, "==> For Activity " + a.info.name);
3738 }
3739 addFilter(intent);
3740 }
3741 }
3742
3743 public final void removeActivity(PackageParser.Activity a, String type) {
3744 mActivities.remove(a.component);
3745 if (SHOW_INFO || Config.LOGV) Log.v(
3746 TAG, " " + type + " " +
3747 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3748 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3749 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003750 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3752 if (SHOW_INFO || Config.LOGV) {
3753 Log.v(TAG, " IntentFilter:");
3754 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3755 }
3756 removeFilter(intent);
3757 }
3758 }
3759
3760 @Override
3761 protected boolean allowFilterResult(
3762 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3763 ActivityInfo filterAi = filter.activity.info;
3764 for (int i=dest.size()-1; i>=0; i--) {
3765 ActivityInfo destAi = dest.get(i).activityInfo;
3766 if (destAi.name == filterAi.name
3767 && destAi.packageName == filterAi.packageName) {
3768 return false;
3769 }
3770 }
3771 return true;
3772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003774 @Override
3775 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3776 int match) {
3777 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3778 return null;
3779 }
3780 final PackageParser.Activity activity = info.activity;
3781 if (mSafeMode && (activity.info.applicationInfo.flags
3782 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3783 return null;
3784 }
3785 final ResolveInfo res = new ResolveInfo();
3786 res.activityInfo = PackageParser.generateActivityInfo(activity,
3787 mFlags);
3788 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3789 res.filter = info;
3790 }
3791 res.priority = info.getPriority();
3792 res.preferredOrder = activity.owner.mPreferredOrder;
3793 //System.out.println("Result: " + res.activityInfo.className +
3794 // " = " + res.priority);
3795 res.match = match;
3796 res.isDefault = info.hasDefault;
3797 res.labelRes = info.labelRes;
3798 res.nonLocalizedLabel = info.nonLocalizedLabel;
3799 res.icon = info.icon;
3800 return res;
3801 }
3802
3803 @Override
3804 protected void sortResults(List<ResolveInfo> results) {
3805 Collections.sort(results, mResolvePrioritySorter);
3806 }
3807
3808 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003809 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003811 out.print(prefix); out.print(
3812 Integer.toHexString(System.identityHashCode(filter.activity)));
3813 out.print(' ');
3814 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 }
3816
3817// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3818// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3819// final List<ResolveInfo> retList = Lists.newArrayList();
3820// while (i.hasNext()) {
3821// final ResolveInfo resolveInfo = i.next();
3822// if (isEnabledLP(resolveInfo.activityInfo)) {
3823// retList.add(resolveInfo);
3824// }
3825// }
3826// return retList;
3827// }
3828
3829 // Keys are String (activity class name), values are Activity.
3830 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3831 = new HashMap<ComponentName, PackageParser.Activity>();
3832 private int mFlags;
3833 }
3834
3835 private final class ServiceIntentResolver
3836 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003837 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003839 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 }
3841
Mihai Preda074edef2009-05-18 17:13:31 +02003842 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003844 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3846 }
3847
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003848 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3849 ArrayList<PackageParser.Service> packageServices) {
3850 if (packageServices == null) {
3851 return null;
3852 }
3853 mFlags = flags;
3854 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3855 int N = packageServices.size();
3856 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3857 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3858
3859 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3860 for (int i = 0; i < N; ++i) {
3861 intentFilters = packageServices.get(i).intents;
3862 if (intentFilters != null && intentFilters.size() > 0) {
3863 listCut.add(intentFilters);
3864 }
3865 }
3866 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3867 }
3868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 public final void addService(PackageParser.Service s) {
3870 mServices.put(s.component, s);
3871 if (SHOW_INFO || Config.LOGV) Log.v(
3872 TAG, " " + (s.info.nonLocalizedLabel != null
3873 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3874 if (SHOW_INFO || Config.LOGV) Log.v(
3875 TAG, " Class=" + s.info.name);
3876 int NI = s.intents.size();
3877 int j;
3878 for (j=0; j<NI; j++) {
3879 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3880 if (SHOW_INFO || Config.LOGV) {
3881 Log.v(TAG, " IntentFilter:");
3882 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3883 }
3884 if (!intent.debugCheck()) {
3885 Log.w(TAG, "==> For Service " + s.info.name);
3886 }
3887 addFilter(intent);
3888 }
3889 }
3890
3891 public final void removeService(PackageParser.Service s) {
3892 mServices.remove(s.component);
3893 if (SHOW_INFO || Config.LOGV) Log.v(
3894 TAG, " " + (s.info.nonLocalizedLabel != null
3895 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3896 if (SHOW_INFO || Config.LOGV) Log.v(
3897 TAG, " Class=" + s.info.name);
3898 int NI = s.intents.size();
3899 int j;
3900 for (j=0; j<NI; j++) {
3901 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3902 if (SHOW_INFO || Config.LOGV) {
3903 Log.v(TAG, " IntentFilter:");
3904 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3905 }
3906 removeFilter(intent);
3907 }
3908 }
3909
3910 @Override
3911 protected boolean allowFilterResult(
3912 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3913 ServiceInfo filterSi = filter.service.info;
3914 for (int i=dest.size()-1; i>=0; i--) {
3915 ServiceInfo destAi = dest.get(i).serviceInfo;
3916 if (destAi.name == filterSi.name
3917 && destAi.packageName == filterSi.packageName) {
3918 return false;
3919 }
3920 }
3921 return true;
3922 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 @Override
3925 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3926 int match) {
3927 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3928 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3929 return null;
3930 }
3931 final PackageParser.Service service = info.service;
3932 if (mSafeMode && (service.info.applicationInfo.flags
3933 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3934 return null;
3935 }
3936 final ResolveInfo res = new ResolveInfo();
3937 res.serviceInfo = PackageParser.generateServiceInfo(service,
3938 mFlags);
3939 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3940 res.filter = filter;
3941 }
3942 res.priority = info.getPriority();
3943 res.preferredOrder = service.owner.mPreferredOrder;
3944 //System.out.println("Result: " + res.activityInfo.className +
3945 // " = " + res.priority);
3946 res.match = match;
3947 res.isDefault = info.hasDefault;
3948 res.labelRes = info.labelRes;
3949 res.nonLocalizedLabel = info.nonLocalizedLabel;
3950 res.icon = info.icon;
3951 return res;
3952 }
3953
3954 @Override
3955 protected void sortResults(List<ResolveInfo> results) {
3956 Collections.sort(results, mResolvePrioritySorter);
3957 }
3958
3959 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003960 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003962 out.print(prefix); out.print(
3963 Integer.toHexString(System.identityHashCode(filter.service)));
3964 out.print(' ');
3965 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 }
3967
3968// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3969// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3970// final List<ResolveInfo> retList = Lists.newArrayList();
3971// while (i.hasNext()) {
3972// final ResolveInfo resolveInfo = (ResolveInfo) i;
3973// if (isEnabledLP(resolveInfo.serviceInfo)) {
3974// retList.add(resolveInfo);
3975// }
3976// }
3977// return retList;
3978// }
3979
3980 // Keys are String (activity class name), values are Activity.
3981 private final HashMap<ComponentName, PackageParser.Service> mServices
3982 = new HashMap<ComponentName, PackageParser.Service>();
3983 private int mFlags;
3984 };
3985
3986 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3987 new Comparator<ResolveInfo>() {
3988 public int compare(ResolveInfo r1, ResolveInfo r2) {
3989 int v1 = r1.priority;
3990 int v2 = r2.priority;
3991 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3992 if (v1 != v2) {
3993 return (v1 > v2) ? -1 : 1;
3994 }
3995 v1 = r1.preferredOrder;
3996 v2 = r2.preferredOrder;
3997 if (v1 != v2) {
3998 return (v1 > v2) ? -1 : 1;
3999 }
4000 if (r1.isDefault != r2.isDefault) {
4001 return r1.isDefault ? -1 : 1;
4002 }
4003 v1 = r1.match;
4004 v2 = r2.match;
4005 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4006 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4007 }
4008 };
4009
4010 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4011 new Comparator<ProviderInfo>() {
4012 public int compare(ProviderInfo p1, ProviderInfo p2) {
4013 final int v1 = p1.initOrder;
4014 final int v2 = p2.initOrder;
4015 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4016 }
4017 };
4018
4019 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4020 IActivityManager am = ActivityManagerNative.getDefault();
4021 if (am != null) {
4022 try {
4023 final Intent intent = new Intent(action,
4024 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4025 if (extras != null) {
4026 intent.putExtras(extras);
4027 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004028 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 am.broadcastIntent(
4030 null, intent,
4031 null, null, 0, null, null, null, false, false);
4032 } catch (RemoteException ex) {
4033 }
4034 }
4035 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004036
4037 public String nextPackageToClean(String lastPackage) {
4038 synchronized (mPackages) {
4039 if (!mMediaMounted) {
4040 // If the external storage is no longer mounted at this point,
4041 // the caller may not have been able to delete all of this
4042 // packages files and can not delete any more. Bail.
4043 return null;
4044 }
4045 if (lastPackage != null) {
4046 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4047 }
4048 return mSettings.mPackagesToBeCleaned.size() > 0
4049 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4050 }
4051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004053 void schedulePackageCleaning(String packageName) {
4054 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4055 }
4056
4057 void startCleaningPackages() {
4058 synchronized (mPackages) {
4059 if (!mMediaMounted) {
4060 return;
4061 }
4062 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4063 return;
4064 }
4065 }
4066 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4067 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4068 IActivityManager am = ActivityManagerNative.getDefault();
4069 if (am != null) {
4070 try {
4071 am.startService(null, intent, null);
4072 } catch (RemoteException e) {
4073 }
4074 }
4075 }
4076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 private final class AppDirObserver extends FileObserver {
4078 public AppDirObserver(String path, int mask, boolean isrom) {
4079 super(path, mask);
4080 mRootDir = path;
4081 mIsRom = isrom;
4082 }
4083
4084 public void onEvent(int event, String path) {
4085 String removedPackage = null;
4086 int removedUid = -1;
4087 String addedPackage = null;
4088 int addedUid = -1;
4089
4090 synchronized (mInstallLock) {
4091 String fullPathStr = null;
4092 File fullPath = null;
4093 if (path != null) {
4094 fullPath = new File(mRootDir, path);
4095 fullPathStr = fullPath.getPath();
4096 }
4097
4098 if (Config.LOGV) Log.v(
4099 TAG, "File " + fullPathStr + " changed: "
4100 + Integer.toHexString(event));
4101
4102 if (!isPackageFilename(path)) {
4103 if (Config.LOGV) Log.v(
4104 TAG, "Ignoring change of non-package file: " + fullPathStr);
4105 return;
4106 }
4107
4108 if ((event&REMOVE_EVENTS) != 0) {
4109 synchronized (mInstallLock) {
4110 PackageParser.Package p = mAppDirs.get(fullPathStr);
4111 if (p != null) {
4112 removePackageLI(p, true);
4113 removedPackage = p.applicationInfo.packageName;
4114 removedUid = p.applicationInfo.uid;
4115 }
4116 }
4117 }
4118
4119 if ((event&ADD_EVENTS) != 0) {
4120 PackageParser.Package p = mAppDirs.get(fullPathStr);
4121 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004122 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4124 PackageParser.PARSE_CHATTY |
4125 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004126 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 if (p != null) {
4128 synchronized (mPackages) {
4129 grantPermissionsLP(p, false);
4130 }
4131 addedPackage = p.applicationInfo.packageName;
4132 addedUid = p.applicationInfo.uid;
4133 }
4134 }
4135 }
4136
4137 synchronized (mPackages) {
4138 mSettings.writeLP();
4139 }
4140 }
4141
4142 if (removedPackage != null) {
4143 Bundle extras = new Bundle(1);
4144 extras.putInt(Intent.EXTRA_UID, removedUid);
4145 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4146 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4147 }
4148 if (addedPackage != null) {
4149 Bundle extras = new Bundle(1);
4150 extras.putInt(Intent.EXTRA_UID, addedUid);
4151 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4152 }
4153 }
4154
4155 private final String mRootDir;
4156 private final boolean mIsRom;
4157 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 /* Called when a downloaded package installation has been confirmed by the user */
4160 public void installPackage(
4161 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004162 installPackage(packageURI, observer, flags, null);
4163 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004164
Jacek Surazski65e13172009-04-28 15:26:38 +02004165 /* Called when a downloaded package installation has been confirmed by the user */
4166 public void installPackage(
4167 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4168 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 mContext.enforceCallingOrSelfPermission(
4170 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004171
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004172 Message msg = mHandler.obtainMessage(INIT_COPY);
4173 msg.obj = createInstallArgs(packageURI, observer, flags, installerPackageName);
4174 mHandler.sendMessage(msg);
4175 }
4176
4177 private InstallArgs createInstallArgs(Uri packageURI, IPackageInstallObserver observer,
4178 int flags, String installerPackageName) {
4179 if (installOnSd(flags)) {
4180 return new SdInstallArgs(packageURI, observer, flags,
4181 installerPackageName);
4182 } else {
4183 return new FileInstallArgs(packageURI, observer, flags,
4184 installerPackageName);
4185 }
4186 }
4187
4188 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4189 if (installOnSd(flags)) {
4190 return new SdInstallArgs(fullCodePath, fullResourcePath);
4191 } else {
4192 return new FileInstallArgs(fullCodePath, fullResourcePath);
4193 }
4194 }
4195
4196 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 // Queue up an async operation since the package installation may take a little while.
4198 mHandler.post(new Runnable() {
4199 public void run() {
4200 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004201 // Result object to be returned
4202 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004203 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004204 res.uid = -1;
4205 res.pkg = null;
4206 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004207 args.doPreInstall(res.returnCode);
4208 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004209 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004210 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004211 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004212 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004214 if (args.observer != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004216 args.observer.packageInstalled(res.name, res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 } catch (RemoteException e) {
4218 Log.i(TAG, "Observer no longer exists.");
4219 }
4220 }
4221 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
4222 // call appears in the synchronized block above.
4223 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4224 res.removedInfo.sendBroadcast(false, true);
4225 Bundle extras = new Bundle(1);
4226 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004227 final boolean update = res.removedInfo.removedPackage != null;
4228 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4230 }
4231 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
4232 res.pkg.applicationInfo.packageName,
4233 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004234 if (update) {
4235 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
4236 res.pkg.applicationInfo.packageName,
4237 extras);
4238 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004239 if (res.removedInfo.args != null) {
4240 // Remove the replaced package's older resources safely now
4241 synchronized (mInstallLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004242 res.removedInfo.args.doPostDeleteLI(true);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004243 }
4244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 }
4246 Runtime.getRuntime().gc();
4247 }
4248 });
4249 }
4250
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004251 static abstract class InstallArgs {
4252 final IPackageInstallObserver observer;
4253 final int flags;
4254 final Uri packageURI;
4255 final String installerPackageName;
4256
4257 InstallArgs(Uri packageURI,
4258 IPackageInstallObserver observer, int flags,
4259 String installerPackageName) {
4260 this.packageURI = packageURI;
4261 this.flags = flags;
4262 this.observer = observer;
4263 this.installerPackageName = installerPackageName;
4264 }
4265
4266 abstract void createCopyFile();
4267 abstract int copyApk(IMediaContainerService imcs);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004268 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004269 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004270 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004271 abstract String getCodePath();
4272 abstract String getResourcePath();
4273 // Need installer lock especially for dex file removal.
4274 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004275 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004276 }
4277
4278 class FileInstallArgs extends InstallArgs {
4279 File installDir;
4280 String codeFileName;
4281 String resourceFileName;
4282
4283 FileInstallArgs(Uri packageURI,
4284 IPackageInstallObserver observer, int flags,
4285 String installerPackageName) {
4286 super(packageURI, observer, flags, installerPackageName);
4287 }
4288
4289 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4290 super(null, null, 0, null);
4291 File codeFile = new File(fullCodePath);
4292 installDir = codeFile.getParentFile();
4293 codeFileName = fullCodePath;
4294 resourceFileName = fullResourcePath;
4295 }
4296
4297 void createCopyFile() {
4298 boolean fwdLocked = isFwdLocked(flags);
4299 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4300 codeFileName = createTempPackageFile(installDir).getPath();
4301 resourceFileName = getResourcePathFromCodePath();
4302 }
4303
4304 String getCodePath() {
4305 return codeFileName;
4306 }
4307
4308 int copyApk(IMediaContainerService imcs) {
4309 // Get a ParcelFileDescriptor to write to the output file
4310 File codeFile = new File(codeFileName);
4311 ParcelFileDescriptor out = null;
4312 try {
4313 out = ParcelFileDescriptor.open(codeFile,
4314 ParcelFileDescriptor.MODE_READ_WRITE);
4315 } catch (FileNotFoundException e) {
4316 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4317 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4318 }
4319 // Copy the resource now
4320 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4321 try {
4322 if (imcs.copyResource(packageURI, out)) {
4323 ret = PackageManager.INSTALL_SUCCEEDED;
4324 }
4325 } catch (RemoteException e) {
4326 } finally {
4327 try { if (out != null) out.close(); } catch (IOException e) {}
4328 }
4329 return ret;
4330 }
4331
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004332 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004333 if (status != PackageManager.INSTALL_SUCCEEDED) {
4334 cleanUp();
4335 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004336 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004337 }
4338
4339 boolean doRename(int status, final String pkgName, String oldCodePath) {
4340 if (status != PackageManager.INSTALL_SUCCEEDED) {
4341 cleanUp();
4342 return false;
4343 } else {
4344 // Rename based on packageName
4345 File codeFile = new File(getCodePath());
4346 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4347 File desFile = new File(installDir, apkName + ".apk");
4348 if (!codeFile.renameTo(desFile)) {
4349 return false;
4350 }
4351 // Reset paths since the file has been renamed.
4352 codeFileName = desFile.getPath();
4353 resourceFileName = getResourcePathFromCodePath();
4354 // Set permissions
4355 if (!setPermissions(pkgName)) {
4356 // Failed setting permissions.
4357 return false;
4358 }
4359 return true;
4360 }
4361 }
4362
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004363 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004364 if (status != PackageManager.INSTALL_SUCCEEDED) {
4365 cleanUp();
4366 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004367 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004368 }
4369
4370 String getResourcePath() {
4371 return resourceFileName;
4372 }
4373
4374 String getResourcePathFromCodePath() {
4375 String codePath = getCodePath();
4376 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4377 String apkNameOnly = getApkName(codePath);
4378 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4379 } else {
4380 return codePath;
4381 }
4382 }
4383
4384 private boolean cleanUp() {
4385 boolean ret = true;
4386 String sourceDir = getCodePath();
4387 String publicSourceDir = getResourcePath();
4388 if (sourceDir != null) {
4389 File sourceFile = new File(sourceDir);
4390 if (!sourceFile.exists()) {
4391 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4392 ret = false;
4393 }
4394 // Delete application's code and resources
4395 sourceFile.delete();
4396 }
4397 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4398 final File publicSourceFile = new File(publicSourceDir);
4399 if (!publicSourceFile.exists()) {
4400 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4401 }
4402 if (publicSourceFile.exists()) {
4403 publicSourceFile.delete();
4404 }
4405 }
4406 return ret;
4407 }
4408
4409 void cleanUpResourcesLI() {
4410 String sourceDir = getCodePath();
4411 if (cleanUp() && mInstaller != null) {
4412 int retCode = mInstaller.rmdex(sourceDir);
4413 if (retCode < 0) {
4414 Log.w(TAG, "Couldn't remove dex file for package: "
4415 + " at location "
4416 + sourceDir + ", retcode=" + retCode);
4417 // we don't consider this to be a failure of the core package deletion
4418 }
4419 }
4420 }
4421
4422 private boolean setPermissions(String pkgName) {
4423 // TODO Do this in a more elegant way later on. for now just a hack
4424 if (!isFwdLocked(flags)) {
4425 final int filePermissions =
4426 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4427 |FileUtils.S_IROTH;
4428 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4429 if (retCode != 0) {
4430 Log.e(TAG, "Couldn't set new package file permissions for " +
4431 getCodePath()
4432 + ". The return code was: " + retCode);
4433 // TODO Define new internal error
4434 return false;
4435 }
4436 return true;
4437 }
4438 return true;
4439 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004440
4441 boolean doPostDeleteLI(boolean delete) {
4442 cleanUpResourcesLI();
4443 return true;
4444 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004445 }
4446
4447 class SdInstallArgs extends InstallArgs {
4448 String cid;
4449 String cachePath;
4450 static final String RES_FILE_NAME = "pkg.apk";
4451
4452 SdInstallArgs(Uri packageURI,
4453 IPackageInstallObserver observer, int flags,
4454 String installerPackageName) {
4455 super(packageURI, observer, flags, installerPackageName);
4456 }
4457
4458 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004459 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004460 // Extract cid from fullCodePath
4461 int eidx = fullCodePath.lastIndexOf("/");
4462 String subStr1 = fullCodePath.substring(0, eidx);
4463 int sidx = subStr1.lastIndexOf("/");
4464 cid = subStr1.substring(sidx+1, eidx);
4465 cachePath = subStr1;
4466 }
4467
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004468 SdInstallArgs(String cid) {
4469 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
4470 this.cid = cid;
4471 }
4472
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004473 void createCopyFile() {
4474 cid = getTempContainerId();
4475 }
4476
4477 int copyApk(IMediaContainerService imcs) {
4478 try {
4479 cachePath = imcs.copyResourceToContainer(
4480 packageURI, cid,
4481 getEncryptKey(), RES_FILE_NAME);
4482 } catch (RemoteException e) {
4483 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004484 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4485 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004486 }
4487
4488 @Override
4489 String getCodePath() {
4490 return cachePath + "/" + RES_FILE_NAME;
4491 }
4492
4493 @Override
4494 String getResourcePath() {
4495 return cachePath + "/" + RES_FILE_NAME;
4496 }
4497
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004498 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004499 if (status != PackageManager.INSTALL_SUCCEEDED) {
4500 // Destroy container
4501 destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004502 } else {
4503 // STOPSHIP Remove once new api is added in MountService
4504 //boolean mounted = isContainerMounted(cid);
4505 boolean mounted = false;
4506 if (!mounted) {
4507 cachePath = mountSdDir(cid, Process.SYSTEM_UID);
4508 if (cachePath == null) {
4509 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4510 }
4511 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004512 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004513 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004514 }
4515
4516 boolean doRename(int status, final String pkgName,
4517 String oldCodePath) {
4518 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004519 String newCachePath = null;
4520 /*final int RENAME_FAILED = 1;
4521 final int MOUNT_FAILED = 2;
4522 final int DESTROY_FAILED = 3;
4523 final int PASS = 4;
4524 int errCode = RENAME_FAILED;
4525 if (mounted) {
4526 // Unmount the container
4527 if (!unMountSdDir(cid)) {
4528 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
4529 return false;
4530 }
4531 mounted = false;
4532 }
4533 if (renameSdDir(cid, newCacheId)) {
4534 errCode = MOUNT_FAILED;
4535 if ((newCachePath = mountSdDir(newCacheId, Process.SYSTEM_UID)) != null) {
4536 errCode = PASS;
4537 }
4538 }
4539 String errMsg = "";
4540 switch (errCode) {
4541 case RENAME_FAILED:
4542 errMsg = "RENAME_FAILED";
4543 break;
4544 case MOUNT_FAILED:
4545 errMsg = "MOUNT_FAILED";
4546 break;
4547 case DESTROY_FAILED:
4548 errMsg = "DESTROY_FAILED";
4549 break;
4550 default:
4551 errMsg = "PASS";
4552 break;
4553 }
4554 Log.i(TAG, "Status: " + errMsg);
4555 if (errCode != PASS) {
4556 return false;
4557 }
4558 Log.i(TAG, "Succesfully renamed " + cid + " to " +newCacheId +
4559 " at path: " + cachePath + " to new path: " + newCachePath);
4560 cid = newCacheId;
4561 cachePath = newCachePath;
4562 return true;
4563 */
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004564 // STOPSHIP TEMPORARY HACK FOR RENAME
4565 // Create new container at newCachePath
4566 String codePath = getCodePath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004567 final int CREATE_FAILED = 1;
4568 final int COPY_FAILED = 3;
4569 final int FINALIZE_FAILED = 5;
4570 final int PASS = 7;
4571 int errCode = CREATE_FAILED;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004572
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004573 if ((newCachePath = createSdDir(new File(codePath), newCacheId)) != null) {
4574 errCode = COPY_FAILED;
4575 // Copy file from codePath
4576 if (FileUtils.copyFile(new File(codePath), new File(newCachePath, RES_FILE_NAME))) {
4577 errCode = FINALIZE_FAILED;
4578 if (finalizeSdDir(newCacheId)) {
4579 errCode = PASS;
4580 }
4581 }
4582 }
4583 // Print error based on errCode
4584 String errMsg = "";
4585 switch (errCode) {
4586 case CREATE_FAILED:
4587 errMsg = "CREATE_FAILED";
4588 break;
4589 case COPY_FAILED:
4590 errMsg = "COPY_FAILED";
4591 destroySdDir(newCacheId);
4592 break;
4593 case FINALIZE_FAILED:
4594 errMsg = "FINALIZE_FAILED";
4595 destroySdDir(newCacheId);
4596 break;
4597 default:
4598 errMsg = "PASS";
4599 break;
4600 }
4601 // Destroy the temporary container
4602 destroySdDir(cid);
4603 Log.i(TAG, "Status: " + errMsg);
4604 if (errCode != PASS) {
4605 return false;
4606 }
4607 cid = newCacheId;
4608 cachePath = newCachePath;
4609
4610 return true;
4611 }
4612
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004613 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004614 if (status != PackageManager.INSTALL_SUCCEEDED) {
4615 cleanUp();
4616 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004617 // STOP SHIP Change this once new api is added.
4618 //boolean mounted = isContainerMounted(cid);
4619 boolean mounted = false;
4620 if (!mounted) {
4621 mountSdDir(cid, Process.SYSTEM_UID);
4622 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004623 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004624 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004625 }
4626
4627 private void cleanUp() {
4628 // Destroy secure container
4629 destroySdDir(cid);
4630 }
4631
4632 void cleanUpResourcesLI() {
4633 String sourceFile = getCodePath();
4634 // Remove dex file
4635 if (mInstaller != null) {
4636 int retCode = mInstaller.rmdex(sourceFile.toString());
4637 if (retCode < 0) {
4638 Log.w(TAG, "Couldn't remove dex file for package: "
4639 + " at location "
4640 + sourceFile.toString() + ", retcode=" + retCode);
4641 // we don't consider this to be a failure of the core package deletion
4642 }
4643 }
4644 cleanUp();
4645 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004646
4647 boolean matchContainer(String app) {
4648 if (cid.startsWith(app)) {
4649 return true;
4650 }
4651 return false;
4652 }
4653
4654 String getPackageName() {
4655 int idx = cid.lastIndexOf("-");
4656 if (idx == -1) {
4657 return cid;
4658 }
4659 return cid.substring(0, idx);
4660 }
4661
4662 boolean doPostDeleteLI(boolean delete) {
4663 boolean ret = false;
4664 boolean mounted = isContainerMounted(cid);
4665 if (mounted) {
4666 // Unmount first
4667 ret = unMountSdDir(cid);
4668 }
4669 if (ret && delete) {
4670 cleanUpResourcesLI();
4671 }
4672 return ret;
4673 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004674 };
4675
4676 // Utility method used to create code paths based on package name and available index.
4677 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4678 String idxStr = "";
4679 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004680 // Fall back to default value of idx=1 if prefix is not
4681 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004682 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004683 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004684 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004685 if (subStr.endsWith(suffix)) {
4686 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004687 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004688 // If oldCodePath already contains prefix find out the
4689 // ending index to either increment or decrement.
4690 int sidx = subStr.lastIndexOf(prefix);
4691 if (sidx != -1) {
4692 subStr = subStr.substring(sidx + prefix.length());
4693 if (subStr != null) {
4694 if (subStr.startsWith("-")) {
4695 subStr = subStr.substring(1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004696 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004697 try {
4698 idx = Integer.parseInt(subStr);
4699 if (idx <= 1) {
4700 idx++;
4701 } else {
4702 idx--;
4703 }
4704 } catch(NumberFormatException e) {
4705 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004706 }
4707 }
4708 }
4709 idxStr = "-" + Integer.toString(idx);
4710 return prefix + idxStr;
4711 }
4712
4713 // Utility method that returns the relative package path with respect
4714 // to the installation directory. Like say for /data/data/com.test-1.apk
4715 // string com.test-1 is returned.
4716 static String getApkName(String codePath) {
4717 if (codePath == null) {
4718 return null;
4719 }
4720 int sidx = codePath.lastIndexOf("/");
4721 int eidx = codePath.lastIndexOf(".");
4722 if (eidx == -1) {
4723 eidx = codePath.length();
4724 } else if (eidx == 0) {
4725 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
4726 return null;
4727 }
4728 return codePath.substring(sidx+1, eidx);
4729 }
4730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004731 class PackageInstalledInfo {
4732 String name;
4733 int uid;
4734 PackageParser.Package pkg;
4735 int returnCode;
4736 PackageRemovedInfo removedInfo;
4737 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004739 /*
4740 * Install a non-existing package.
4741 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004742 private void installNewPackageLI(PackageParser.Package pkg,
4743 int parseFlags,
4744 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004745 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004746 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08004747 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004748 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08004749
4750 if (useEncryptedFilesystemForPackage(pkg)) {
4751 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
4752 } else {
4753 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
4754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004755 res.name = pkgName;
4756 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004757 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004758 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004759 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 + " without first uninstalling.");
4761 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4762 return;
4763 }
4764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004765 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004766 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004767 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004768 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4770 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4771 }
4772 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004773 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004774 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004775 res);
4776 // delete the partially installed application. the data directory will have to be
4777 // restored if it was already existing
4778 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4779 // remove package from internal structures. Note that we want deletePackageX to
4780 // delete the package data and cache directories that it created in
4781 // scanPackageLocked, unless those directories existed before we even tried to
4782 // install.
4783 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004784 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004785 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
4786 res.removedInfo);
4787 }
4788 }
4789 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004790
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004791 private void replacePackageLI(PackageParser.Package pkg,
4792 int parseFlags,
4793 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004794 String installerPackageName, PackageInstalledInfo res) {
4795
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004796 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004797 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004798 // First find the old package info and check signatures
4799 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004800 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004801 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
4802 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4804 return;
4805 }
4806 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004807 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004808 if(sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004809 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004810 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004811 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 }
4813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004815 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004816 PackageParser.Package pkg,
4817 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004818 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004819 PackageParser.Package newPackage = null;
4820 String pkgName = deletedPackage.packageName;
4821 boolean deletedPkg = true;
4822 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004823
Jacek Surazski65e13172009-04-28 15:26:38 +02004824 String oldInstallerPackageName = null;
4825 synchronized (mPackages) {
4826 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
4827 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004828
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004829 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004830 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004831 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004832 res.removedInfo)) {
4833 // If the existing package was'nt successfully deleted
4834 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4835 deletedPkg = false;
4836 } else {
4837 // Successfully deleted the old package. Now proceed with re-installation
4838 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004839 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004841 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004842 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4843 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08004844 }
4845 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004846 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004847 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 res);
4849 updatedSettings = true;
4850 }
4851 }
4852
4853 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4854 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004855 // were keeping around in case we needed them (see below) can now be deleted.
4856 // This info will be set on the res.removedInfo to clean up later on as post
4857 // install action.
4858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004859 //update signature on the new package setting
4860 //this should always succeed, since we checked the
4861 //signature earlier.
4862 synchronized(mPackages) {
4863 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
4864 parseFlags, true);
4865 }
4866 } else {
4867 // remove package from internal structures. Note that we want deletePackageX to
4868 // delete the package data and cache directories that it created in
4869 // scanPackageLocked, unless those directories existed before we even tried to
4870 // install.
4871 if(updatedSettings) {
4872 deletePackageLI(
4873 pkgName, true,
4874 PackageManager.DONT_DELETE_DATA,
4875 res.removedInfo);
4876 }
4877 // Since we failed to install the new package we need to restore the old
4878 // package that we deleted.
4879 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004880 File restoreFile = new File(deletedPackage.mPath);
4881 if (restoreFile == null) {
4882 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
4883 return;
4884 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004885 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4886 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004887 // Parse old package
4888 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
4889 scanPackageLI(restoreFile, parseFlags, scanMode);
4890 synchronized (mPackages) {
4891 grantPermissionsLP(deletedPackage, false);
4892 mSettings.writeLP();
4893 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004894 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4895 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004897 }
4898 }
4899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004901 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004902 PackageParser.Package pkg,
4903 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004904 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004905 PackageParser.Package newPackage = null;
4906 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004907 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004908 PackageParser.PARSE_IS_SYSTEM;
4909 String packageName = deletedPackage.packageName;
4910 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4911 if (packageName == null) {
4912 Log.w(TAG, "Attempt to delete null packageName.");
4913 return;
4914 }
4915 PackageParser.Package oldPkg;
4916 PackageSetting oldPkgSetting;
4917 synchronized (mPackages) {
4918 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004919 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004920 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4921 (oldPkgSetting == null)) {
4922 Log.w(TAG, "Could'nt find package:"+packageName+" information");
4923 return;
4924 }
4925 }
4926 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4927 res.removedInfo.removedPackage = packageName;
4928 // Remove existing system package
4929 removePackageLI(oldPkg, true);
4930 synchronized (mPackages) {
4931 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4932 }
4933
4934 // Successfully disabled the old package. Now proceed with re-installation
4935 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4936 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004937 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004938 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004939 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004940 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4941 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4942 }
4943 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004944 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004945 updatedSettings = true;
4946 }
4947
4948 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4949 //update signature on the new package setting
4950 //this should always succeed, since we checked the
4951 //signature earlier.
4952 synchronized(mPackages) {
4953 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
4954 parseFlags, true);
4955 }
4956 } else {
4957 // Re installation failed. Restore old information
4958 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07004959 if (newPackage != null) {
4960 removePackageLI(newPackage, true);
4961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004963 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07004965 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004966 // Restore the old system information in Settings
4967 synchronized(mPackages) {
4968 if(updatedSettings) {
4969 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004970 mSettings.setInstallerPackageName(packageName,
4971 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004972 }
4973 mSettings.writeLP();
4974 }
4975 }
4976 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004977
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004978 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004979 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004980 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004981 synchronized (mPackages) {
4982 //write settings. the installStatus will be incomplete at this stage.
4983 //note that the new package setting would have already been
4984 //added to mPackages. It hasn't been persisted yet.
4985 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4986 mSettings.writeLP();
4987 }
4988
4989 int retCode = 0;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004990 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4991 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004992 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004993 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004994 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4995 return;
4996 }
4997 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004998 res.returnCode = setPermissionsLI(newPackage);
4999 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5000 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005002 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005003 }
5004 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5005 if (mInstaller != null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005006 mInstaller.rmdex(newPackage.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007 }
5008 }
5009
5010 synchronized (mPackages) {
5011 grantPermissionsLP(newPackage, true);
5012 res.name = pkgName;
5013 res.uid = newPackage.applicationInfo.uid;
5014 res.pkg = newPackage;
5015 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005016 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005017 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5018 //to update install status
5019 mSettings.writeLP();
5020 }
5021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005022
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005023 private void installPackageLI(InstallArgs args,
5024 boolean newInstall, PackageInstalledInfo res) {
5025 int pFlags = args.flags;
5026 String installerPackageName = args.installerPackageName;
5027 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005028 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
5029 boolean onSd = ((pFlags & PackageManager.INSTALL_ON_SDCARD) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005030 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005031 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5032 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005033 // Result object to be returned
5034 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5035
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005036 // Retrieve PackageSettings and parse package
5037 int parseFlags = PackageParser.PARSE_CHATTY |
5038 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5039 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5040 parseFlags |= mDefParseFlags;
5041 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5042 pp.setSeparateProcesses(mSeparateProcesses);
5043 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5044 null, mMetrics, parseFlags);
5045 if (pkg == null) {
5046 res.returnCode = pp.getParseError();
5047 return;
5048 }
5049 String pkgName = res.name = pkg.packageName;
5050 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5051 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5052 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5053 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005054 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005055 }
5056 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5057 res.returnCode = pp.getParseError();
5058 return;
5059 }
5060 // Some preinstall checks
5061 if (forwardLocked && onSd) {
5062 // Make sure forward locked apps can only be installed
5063 // on internal storage
5064 Log.w(TAG, "Cannot install protected apps on sdcard");
5065 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5066 return;
5067 }
5068 // Get rid of all references to package scan path via parser.
5069 pp = null;
5070 String oldCodePath = null;
5071 boolean systemApp = false;
5072 synchronized (mPackages) {
5073 // Check if installing already existing package
5074 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
5075 && mPackages.containsKey(pkgName)) {
5076 replace = true;
5077 }
5078 PackageSetting ps = mSettings.mPackages.get(pkgName);
5079 if (ps != null) {
5080 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5081 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5082 systemApp = (ps.pkg.applicationInfo.flags &
5083 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005084 }
5085 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005087
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005088 if (systemApp && onSd) {
5089 // Disable updates to system apps on sdcard
5090 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5091 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5092 return;
5093 }
5094 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5095 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5096 return;
5097 }
5098 // Set application objects path explicitly after the rename
5099 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
5100 if(replace) {
5101 replacePackageLI(pkg, parseFlags, scanMode,
5102 installerPackageName, res);
5103 } else {
5104 installNewPackageLI(pkg, parseFlags, scanMode,
5105 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 }
5107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005108
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005109 private int setPermissionsLI(PackageParser.Package newPackage) {
5110 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005111 int retCode = 0;
5112 // TODO Gross hack but fix later. Ideally move this to be a post installation
5113 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005114 if ((newPackage.applicationInfo.flags
5115 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5116 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005117 try {
5118 extractPublicFiles(newPackage, destResourceFile);
5119 } catch (IOException e) {
5120 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5121 " forward-locked app.");
5122 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5123 } finally {
5124 //TODO clean up the extracted public files
5125 }
5126 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005127 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 newPackage.applicationInfo.uid);
5129 } else {
5130 final int filePermissions =
5131 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005132 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005133 newPackage.applicationInfo.uid);
5134 }
5135 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005136 // The permissions on the resource file was set when it was copied for
5137 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005138 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005141 Log.e(TAG, "Couldn't set new package file permissions for " +
5142 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005144 // TODO Define new internal error
5145 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 }
5147 return PackageManager.INSTALL_SUCCEEDED;
5148 }
5149
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005150 private boolean isForwardLocked(PackageParser.Package pkg) {
5151 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005152 }
5153
5154 private void extractPublicFiles(PackageParser.Package newPackage,
5155 File publicZipFile) throws IOException {
5156 final ZipOutputStream publicZipOutStream =
5157 new ZipOutputStream(new FileOutputStream(publicZipFile));
5158 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5159
5160 // Copy manifest, resources.arsc and res directory to public zip
5161
5162 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5163 while (privateZipEntries.hasMoreElements()) {
5164 final ZipEntry zipEntry = privateZipEntries.nextElement();
5165 final String zipEntryName = zipEntry.getName();
5166 if ("AndroidManifest.xml".equals(zipEntryName)
5167 || "resources.arsc".equals(zipEntryName)
5168 || zipEntryName.startsWith("res/")) {
5169 try {
5170 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5171 } catch (IOException e) {
5172 try {
5173 publicZipOutStream.close();
5174 throw e;
5175 } finally {
5176 publicZipFile.delete();
5177 }
5178 }
5179 }
5180 }
5181
5182 publicZipOutStream.close();
5183 FileUtils.setPermissions(
5184 publicZipFile.getAbsolutePath(),
5185 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5186 -1, -1);
5187 }
5188
5189 private static void copyZipEntry(ZipEntry zipEntry,
5190 ZipFile inZipFile,
5191 ZipOutputStream outZipStream) throws IOException {
5192 byte[] buffer = new byte[4096];
5193 int num;
5194
5195 ZipEntry newEntry;
5196 if (zipEntry.getMethod() == ZipEntry.STORED) {
5197 // Preserve the STORED method of the input entry.
5198 newEntry = new ZipEntry(zipEntry);
5199 } else {
5200 // Create a new entry so that the compressed len is recomputed.
5201 newEntry = new ZipEntry(zipEntry.getName());
5202 }
5203 outZipStream.putNextEntry(newEntry);
5204
5205 InputStream data = inZipFile.getInputStream(zipEntry);
5206 while ((num = data.read(buffer)) > 0) {
5207 outZipStream.write(buffer, 0, num);
5208 }
5209 outZipStream.flush();
5210 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005212 private void deleteTempPackageFiles() {
5213 FilenameFilter filter = new FilenameFilter() {
5214 public boolean accept(File dir, String name) {
5215 return name.startsWith("vmdl") && name.endsWith(".tmp");
5216 }
5217 };
5218 String tmpFilesList[] = mAppInstallDir.list(filter);
5219 if(tmpFilesList == null) {
5220 return;
5221 }
5222 for(int i = 0; i < tmpFilesList.length; i++) {
5223 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5224 tmpFile.delete();
5225 }
5226 }
5227
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005228 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 File tmpPackageFile;
5230 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005231 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232 } catch (IOException e) {
5233 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5234 return null;
5235 }
5236 try {
5237 FileUtils.setPermissions(
5238 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5239 -1, -1);
5240 } catch (IOException e) {
5241 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5242 return null;
5243 }
5244 return tmpPackageFile;
5245 }
5246
5247 public void deletePackage(final String packageName,
5248 final IPackageDeleteObserver observer,
5249 final int flags) {
5250 mContext.enforceCallingOrSelfPermission(
5251 android.Manifest.permission.DELETE_PACKAGES, null);
5252 // Queue up an async operation since the package deletion may take a little while.
5253 mHandler.post(new Runnable() {
5254 public void run() {
5255 mHandler.removeCallbacks(this);
5256 final boolean succeded = deletePackageX(packageName, true, true, flags);
5257 if (observer != null) {
5258 try {
5259 observer.packageDeleted(succeded);
5260 } catch (RemoteException e) {
5261 Log.i(TAG, "Observer no longer exists.");
5262 } //end catch
5263 } //end if
5264 } //end run
5265 });
5266 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005268 /**
5269 * This method is an internal method that could be get invoked either
5270 * to delete an installed package or to clean up a failed installation.
5271 * After deleting an installed package, a broadcast is sent to notify any
5272 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005273 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005274 * installation wouldn't have sent the initial broadcast either
5275 * The key steps in deleting a package are
5276 * deleting the package information in internal structures like mPackages,
5277 * deleting the packages base directories through installd
5278 * updating mSettings to reflect current status
5279 * persisting settings for later use
5280 * sending a broadcast if necessary
5281 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5283 boolean deleteCodeAndResources, int flags) {
5284 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005285 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286
5287 synchronized (mInstallLock) {
5288 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5289 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005292 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5293 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5294
5295 // If the removed package was a system update, the old system packaged
5296 // was re-enabled; we need to broadcast this information
5297 if (systemUpdate) {
5298 Bundle extras = new Bundle(1);
5299 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5300 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5301
5302 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5303 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005305 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005306 // Delete the resources here after sending the broadcast to let
5307 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005308 if (info.args != null) {
5309 synchronized (mInstallLock) {
5310 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005311 }
5312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005313 return res;
5314 }
5315
5316 static class PackageRemovedInfo {
5317 String removedPackage;
5318 int uid = -1;
5319 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005320 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005321 // Clean up resources deleted packages.
5322 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005324 void sendBroadcast(boolean fullRemove, boolean replacing) {
5325 Bundle extras = new Bundle(1);
5326 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5327 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5328 if (replacing) {
5329 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5330 }
5331 if (removedPackage != null) {
5332 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5333 }
5334 if (removedUid >= 0) {
5335 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5336 }
5337 }
5338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005340 /*
5341 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5342 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005343 * 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 -08005344 * delete a partially installed application.
5345 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005346 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005347 int flags) {
5348 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005349 if (outInfo != null) {
5350 outInfo.removedPackage = packageName;
5351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005352 removePackageLI(p, true);
5353 // Retrieve object to delete permissions for shared user later on
5354 PackageSetting deletedPs;
5355 synchronized (mPackages) {
5356 deletedPs = mSettings.mPackages.get(packageName);
5357 }
5358 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005359 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005361 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 if (retCode < 0) {
5363 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5364 + packageName + ", retcode=" + retCode);
5365 // we don't consider this to be a failure of the core package deletion
5366 }
5367 } else {
5368 //for emulator
5369 PackageParser.Package pkg = mPackages.get(packageName);
5370 File dataDir = new File(pkg.applicationInfo.dataDir);
5371 dataDir.delete();
5372 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005373 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005375 if (outInfo != null) {
5376 outInfo.removedUid = mSettings.removePackageLP(packageName);
5377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 }
5379 }
5380 synchronized (mPackages) {
5381 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5382 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005383 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 }
5385 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005386 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 }
5388 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005390 /*
5391 * Tries to delete system package.
5392 */
5393 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005394 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 ApplicationInfo applicationInfo = p.applicationInfo;
5396 //applicable for non-partially installed applications only
5397 if (applicationInfo == null) {
5398 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5399 return false;
5400 }
5401 PackageSetting ps = null;
5402 // Confirm if the system package has been updated
5403 // An updated system app can be deleted. This will also have to restore
5404 // the system pkg from system partition
5405 synchronized (mPackages) {
5406 ps = mSettings.getDisabledSystemPkg(p.packageName);
5407 }
5408 if (ps == null) {
5409 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5410 return false;
5411 } else {
5412 Log.i(TAG, "Deleting system pkg from data partition");
5413 }
5414 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005415 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005416 boolean deleteCodeAndResources = false;
5417 if (ps.versionCode < p.mVersionCode) {
5418 // Delete code and resources for downgrades
5419 deleteCodeAndResources = true;
5420 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5421 flags &= ~PackageManager.DONT_DELETE_DATA;
5422 }
5423 } else {
5424 // Preserve data by setting flag
5425 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5426 flags |= PackageManager.DONT_DELETE_DATA;
5427 }
5428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5430 if (!ret) {
5431 return false;
5432 }
5433 synchronized (mPackages) {
5434 // Reinstate the old system package
5435 mSettings.enableSystemPackageLP(p.packageName);
5436 }
5437 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005438 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005440 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442 if (newPkg == null) {
5443 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5444 return false;
5445 }
5446 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005447 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 mSettings.writeLP();
5449 }
5450 return true;
5451 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5454 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5455 ApplicationInfo applicationInfo = p.applicationInfo;
5456 if (applicationInfo == null) {
5457 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5458 return false;
5459 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005460 if (outInfo != null) {
5461 outInfo.uid = applicationInfo.uid;
5462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463
5464 // Delete package data from internal structures and also remove data if flag is set
5465 removePackageDataLI(p, outInfo, flags);
5466
5467 // Delete application code and resources
5468 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005469 // TODO can pick up from PackageSettings as well
5470 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
5471 PackageManager.INSTALL_ON_SDCARD : 0;
5472 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5473 PackageManager.INSTALL_FORWARD_LOCK : 0;
5474 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005475 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 }
5477 return true;
5478 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005480 /*
5481 * This method handles package deletion in general
5482 */
5483 private boolean deletePackageLI(String packageName,
5484 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5485 if (packageName == null) {
5486 Log.w(TAG, "Attempt to delete null packageName.");
5487 return false;
5488 }
5489 PackageParser.Package p;
5490 boolean dataOnly = false;
5491 synchronized (mPackages) {
5492 p = mPackages.get(packageName);
5493 if (p == null) {
5494 //this retrieves partially installed apps
5495 dataOnly = true;
5496 PackageSetting ps = mSettings.mPackages.get(packageName);
5497 if (ps == null) {
5498 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5499 return false;
5500 }
5501 p = ps.pkg;
5502 }
5503 }
5504 if (p == null) {
5505 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5506 return false;
5507 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 if (dataOnly) {
5510 // Delete application data first
5511 removePackageDataLI(p, outInfo, flags);
5512 return true;
5513 }
5514 // At this point the package should have ApplicationInfo associated with it
5515 if (p.applicationInfo == null) {
5516 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5517 return false;
5518 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005519 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5521 Log.i(TAG, "Removing system package:"+p.packageName);
5522 // When an updated system application is deleted we delete the existing resources as well and
5523 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005524 ret = deleteSystemPackageLI(p, flags, outInfo);
5525 } else {
5526 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005527 // Kill application pre-emptively especially for apps on sd.
5528 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005529 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005531 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 public void clearApplicationUserData(final String packageName,
5535 final IPackageDataObserver observer) {
5536 mContext.enforceCallingOrSelfPermission(
5537 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5538 // Queue up an async operation since the package deletion may take a little while.
5539 mHandler.post(new Runnable() {
5540 public void run() {
5541 mHandler.removeCallbacks(this);
5542 final boolean succeeded;
5543 synchronized (mInstallLock) {
5544 succeeded = clearApplicationUserDataLI(packageName);
5545 }
5546 if (succeeded) {
5547 // invoke DeviceStorageMonitor's update method to clear any notifications
5548 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5549 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5550 if (dsm != null) {
5551 dsm.updateMemory();
5552 }
5553 }
5554 if(observer != null) {
5555 try {
5556 observer.onRemoveCompleted(packageName, succeeded);
5557 } catch (RemoteException e) {
5558 Log.i(TAG, "Observer no longer exists.");
5559 }
5560 } //end if observer
5561 } //end run
5562 });
5563 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 private boolean clearApplicationUserDataLI(String packageName) {
5566 if (packageName == null) {
5567 Log.w(TAG, "Attempt to delete null packageName.");
5568 return false;
5569 }
5570 PackageParser.Package p;
5571 boolean dataOnly = false;
5572 synchronized (mPackages) {
5573 p = mPackages.get(packageName);
5574 if(p == null) {
5575 dataOnly = true;
5576 PackageSetting ps = mSettings.mPackages.get(packageName);
5577 if((ps == null) || (ps.pkg == null)) {
5578 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5579 return false;
5580 }
5581 p = ps.pkg;
5582 }
5583 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005584 boolean useEncryptedFSDir = false;
5585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 if(!dataOnly) {
5587 //need to check this only for fully installed applications
5588 if (p == null) {
5589 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5590 return false;
5591 }
5592 final ApplicationInfo applicationInfo = p.applicationInfo;
5593 if (applicationInfo == null) {
5594 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5595 return false;
5596 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005597 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005598 }
5599 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005600 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 if (retCode < 0) {
5602 Log.w(TAG, "Couldn't remove cache files for package: "
5603 + packageName);
5604 return false;
5605 }
5606 }
5607 return true;
5608 }
5609
5610 public void deleteApplicationCacheFiles(final String packageName,
5611 final IPackageDataObserver observer) {
5612 mContext.enforceCallingOrSelfPermission(
5613 android.Manifest.permission.DELETE_CACHE_FILES, null);
5614 // Queue up an async operation since the package deletion may take a little while.
5615 mHandler.post(new Runnable() {
5616 public void run() {
5617 mHandler.removeCallbacks(this);
5618 final boolean succeded;
5619 synchronized (mInstallLock) {
5620 succeded = deleteApplicationCacheFilesLI(packageName);
5621 }
5622 if(observer != null) {
5623 try {
5624 observer.onRemoveCompleted(packageName, succeded);
5625 } catch (RemoteException e) {
5626 Log.i(TAG, "Observer no longer exists.");
5627 }
5628 } //end if observer
5629 } //end run
5630 });
5631 }
5632
5633 private boolean deleteApplicationCacheFilesLI(String packageName) {
5634 if (packageName == null) {
5635 Log.w(TAG, "Attempt to delete null packageName.");
5636 return false;
5637 }
5638 PackageParser.Package p;
5639 synchronized (mPackages) {
5640 p = mPackages.get(packageName);
5641 }
5642 if (p == null) {
5643 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5644 return false;
5645 }
5646 final ApplicationInfo applicationInfo = p.applicationInfo;
5647 if (applicationInfo == null) {
5648 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5649 return false;
5650 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005651 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005653 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 if (retCode < 0) {
5655 Log.w(TAG, "Couldn't remove cache files for package: "
5656 + packageName);
5657 return false;
5658 }
5659 }
5660 return true;
5661 }
5662
5663 public void getPackageSizeInfo(final String packageName,
5664 final IPackageStatsObserver observer) {
5665 mContext.enforceCallingOrSelfPermission(
5666 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5667 // Queue up an async operation since the package deletion may take a little while.
5668 mHandler.post(new Runnable() {
5669 public void run() {
5670 mHandler.removeCallbacks(this);
5671 PackageStats lStats = new PackageStats(packageName);
5672 final boolean succeded;
5673 synchronized (mInstallLock) {
5674 succeded = getPackageSizeInfoLI(packageName, lStats);
5675 }
5676 if(observer != null) {
5677 try {
5678 observer.onGetStatsCompleted(lStats, succeded);
5679 } catch (RemoteException e) {
5680 Log.i(TAG, "Observer no longer exists.");
5681 }
5682 } //end if observer
5683 } //end run
5684 });
5685 }
5686
5687 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5688 if (packageName == null) {
5689 Log.w(TAG, "Attempt to get size of null packageName.");
5690 return false;
5691 }
5692 PackageParser.Package p;
5693 boolean dataOnly = false;
5694 synchronized (mPackages) {
5695 p = mPackages.get(packageName);
5696 if(p == null) {
5697 dataOnly = true;
5698 PackageSetting ps = mSettings.mPackages.get(packageName);
5699 if((ps == null) || (ps.pkg == null)) {
5700 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5701 return false;
5702 }
5703 p = ps.pkg;
5704 }
5705 }
5706 String publicSrcDir = null;
5707 if(!dataOnly) {
5708 final ApplicationInfo applicationInfo = p.applicationInfo;
5709 if (applicationInfo == null) {
5710 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5711 return false;
5712 }
5713 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
5714 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005715 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 if (mInstaller != null) {
5717 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08005718 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 if (res < 0) {
5720 return false;
5721 } else {
5722 return true;
5723 }
5724 }
5725 return true;
5726 }
5727
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 public void addPackageToPreferred(String packageName) {
5730 mContext.enforceCallingOrSelfPermission(
5731 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005732 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 }
5734
5735 public void removePackageFromPreferred(String packageName) {
5736 mContext.enforceCallingOrSelfPermission(
5737 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005738 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 }
5740
5741 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005742 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 }
5744
5745 public void addPreferredActivity(IntentFilter filter, int match,
5746 ComponentName[] set, ComponentName activity) {
5747 mContext.enforceCallingOrSelfPermission(
5748 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5749
5750 synchronized (mPackages) {
5751 Log.i(TAG, "Adding preferred activity " + activity + ":");
5752 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5753 mSettings.mPreferredActivities.addFilter(
5754 new PreferredActivity(filter, match, set, activity));
5755 mSettings.writeLP();
5756 }
5757 }
5758
Satish Sampath8dbe6122009-06-02 23:35:54 +01005759 public void replacePreferredActivity(IntentFilter filter, int match,
5760 ComponentName[] set, ComponentName activity) {
5761 mContext.enforceCallingOrSelfPermission(
5762 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5763 if (filter.countActions() != 1) {
5764 throw new IllegalArgumentException(
5765 "replacePreferredActivity expects filter to have only 1 action.");
5766 }
5767 if (filter.countCategories() != 1) {
5768 throw new IllegalArgumentException(
5769 "replacePreferredActivity expects filter to have only 1 category.");
5770 }
5771 if (filter.countDataAuthorities() != 0
5772 || filter.countDataPaths() != 0
5773 || filter.countDataSchemes() != 0
5774 || filter.countDataTypes() != 0) {
5775 throw new IllegalArgumentException(
5776 "replacePreferredActivity expects filter to have no data authorities, " +
5777 "paths, schemes or types.");
5778 }
5779 synchronized (mPackages) {
5780 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5781 String action = filter.getAction(0);
5782 String category = filter.getCategory(0);
5783 while (it.hasNext()) {
5784 PreferredActivity pa = it.next();
5785 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5786 it.remove();
5787 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5788 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5789 }
5790 }
5791 addPreferredActivity(filter, match, set, activity);
5792 }
5793 }
5794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 public void clearPackagePreferredActivities(String packageName) {
5796 mContext.enforceCallingOrSelfPermission(
5797 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5798
5799 synchronized (mPackages) {
5800 if (clearPackagePreferredActivitiesLP(packageName)) {
5801 mSettings.writeLP();
5802 }
5803 }
5804 }
5805
5806 boolean clearPackagePreferredActivitiesLP(String packageName) {
5807 boolean changed = false;
5808 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5809 while (it.hasNext()) {
5810 PreferredActivity pa = it.next();
5811 if (pa.mActivity.getPackageName().equals(packageName)) {
5812 it.remove();
5813 changed = true;
5814 }
5815 }
5816 return changed;
5817 }
5818
5819 public int getPreferredActivities(List<IntentFilter> outFilters,
5820 List<ComponentName> outActivities, String packageName) {
5821
5822 int num = 0;
5823 synchronized (mPackages) {
5824 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5825 while (it.hasNext()) {
5826 PreferredActivity pa = it.next();
5827 if (packageName == null
5828 || pa.mActivity.getPackageName().equals(packageName)) {
5829 if (outFilters != null) {
5830 outFilters.add(new IntentFilter(pa));
5831 }
5832 if (outActivities != null) {
5833 outActivities.add(pa.mActivity);
5834 }
5835 }
5836 }
5837 }
5838
5839 return num;
5840 }
5841
5842 public void setApplicationEnabledSetting(String appPackageName,
5843 int newState, int flags) {
5844 setEnabledSetting(appPackageName, null, newState, flags);
5845 }
5846
5847 public void setComponentEnabledSetting(ComponentName componentName,
5848 int newState, int flags) {
5849 setEnabledSetting(componentName.getPackageName(),
5850 componentName.getClassName(), newState, flags);
5851 }
5852
5853 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005854 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5856 || newState == COMPONENT_ENABLED_STATE_ENABLED
5857 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5858 throw new IllegalArgumentException("Invalid new component state: "
5859 + newState);
5860 }
5861 PackageSetting pkgSetting;
5862 final int uid = Binder.getCallingUid();
5863 final int permission = mContext.checkCallingPermission(
5864 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5865 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005866 boolean sendNow = false;
5867 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005868 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005870 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005872 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005874 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005876 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 }
5878 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005879 "Unknown component: " + packageName
5880 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 }
5882 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5883 throw new SecurityException(
5884 "Permission Denial: attempt to change component state from pid="
5885 + Binder.getCallingPid()
5886 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5887 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005888 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 // We're dealing with an application/package level state change
5890 pkgSetting.enabled = newState;
5891 } else {
5892 // We're dealing with a component level state change
5893 switch (newState) {
5894 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005895 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005896 break;
5897 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005898 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 break;
5900 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005901 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 break;
5903 default:
5904 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005905 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 }
5907 }
5908 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005909 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005910 components = mPendingBroadcasts.get(packageName);
5911 boolean newPackage = components == null;
5912 if (newPackage) {
5913 components = new ArrayList<String>();
5914 }
5915 if (!components.contains(componentName)) {
5916 components.add(componentName);
5917 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005918 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5919 sendNow = true;
5920 // Purge entry from pending broadcast list if another one exists already
5921 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005922 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005923 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005924 if (newPackage) {
5925 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005926 }
5927 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5928 // Schedule a message
5929 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5930 }
5931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005932 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 long callingId = Binder.clearCallingIdentity();
5935 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005936 if (sendNow) {
5937 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005938 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 } finally {
5941 Binder.restoreCallingIdentity(callingId);
5942 }
5943 }
5944
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005945 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005946 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5947 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5948 + " components=" + componentNames);
5949 Bundle extras = new Bundle(4);
5950 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5951 String nameList[] = new String[componentNames.size()];
5952 componentNames.toArray(nameList);
5953 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005954 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5955 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005956 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005957 }
5958
Jacek Surazski65e13172009-04-28 15:26:38 +02005959 public String getInstallerPackageName(String packageName) {
5960 synchronized (mPackages) {
5961 PackageSetting pkg = mSettings.mPackages.get(packageName);
5962 if (pkg == null) {
5963 throw new IllegalArgumentException("Unknown package: " + packageName);
5964 }
5965 return pkg.installerPackageName;
5966 }
5967 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 public int getApplicationEnabledSetting(String appPackageName) {
5970 synchronized (mPackages) {
5971 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5972 if (pkg == null) {
5973 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5974 }
5975 return pkg.enabled;
5976 }
5977 }
5978
5979 public int getComponentEnabledSetting(ComponentName componentName) {
5980 synchronized (mPackages) {
5981 final String packageNameStr = componentName.getPackageName();
5982 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5983 if (pkg == null) {
5984 throw new IllegalArgumentException("Unknown component: " + componentName);
5985 }
5986 final String classNameStr = componentName.getClassName();
5987 return pkg.currentEnabledStateLP(classNameStr);
5988 }
5989 }
5990
5991 public void enterSafeMode() {
5992 if (!mSystemReady) {
5993 mSafeMode = true;
5994 }
5995 }
5996
5997 public void systemReady() {
5998 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005999
6000 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006001 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006002 mContext.getContentResolver(),
6003 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006004 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006005 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006006 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 }
6009
6010 public boolean isSafeMode() {
6011 return mSafeMode;
6012 }
6013
6014 public boolean hasSystemUidErrors() {
6015 return mHasSystemUidErrors;
6016 }
6017
6018 static String arrayToString(int[] array) {
6019 StringBuffer buf = new StringBuffer(128);
6020 buf.append('[');
6021 if (array != null) {
6022 for (int i=0; i<array.length; i++) {
6023 if (i > 0) buf.append(", ");
6024 buf.append(array[i]);
6025 }
6026 }
6027 buf.append(']');
6028 return buf.toString();
6029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 @Override
6032 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6033 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6034 != PackageManager.PERMISSION_GRANTED) {
6035 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6036 + Binder.getCallingPid()
6037 + ", uid=" + Binder.getCallingUid()
6038 + " without permission "
6039 + android.Manifest.permission.DUMP);
6040 return;
6041 }
6042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 synchronized (mPackages) {
6044 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006045 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 pw.println(" ");
6047 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006048 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 pw.println(" ");
6050 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006051 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 pw.println(" ");
6053 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006054 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 pw.println("Permissions:");
6057 {
6058 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006059 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6060 pw.print(Integer.toHexString(System.identityHashCode(p)));
6061 pw.println("):");
6062 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6063 pw.print(" uid="); pw.print(p.uid);
6064 pw.print(" gids="); pw.print(arrayToString(p.gids));
6065 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 }
6067 }
6068 pw.println(" ");
6069 pw.println("Packages:");
6070 {
6071 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006072 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
6073 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6074 pw.println("):");
6075 pw.print(" userId="); pw.print(ps.userId);
6076 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6077 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6078 pw.print(" pkg="); pw.println(ps.pkg);
6079 pw.print(" codePath="); pw.println(ps.codePathString);
6080 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006082 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006083 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006084 pw.print(" supportsScreens=[");
6085 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006086 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006087 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006088 if (!first) pw.print(", ");
6089 first = false;
6090 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006092 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006093 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006094 if (!first) pw.print(", ");
6095 first = false;
6096 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006098 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006099 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006100 if (!first) pw.print(", ");
6101 first = false;
6102 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006103 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006104 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006105 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006106 if (!first) pw.print(", ");
6107 first = false;
6108 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006109 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006110 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006111 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6112 if (!first) pw.print(", ");
6113 first = false;
6114 pw.print("anyDensity");
6115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006117 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006118 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6119 pw.print(" signatures="); pw.println(ps.signatures);
6120 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6121 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6122 pw.print(" installStatus="); pw.print(ps.installStatus);
6123 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 if (ps.disabledComponents.size() > 0) {
6125 pw.println(" disabledComponents:");
6126 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006127 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 }
6129 }
6130 if (ps.enabledComponents.size() > 0) {
6131 pw.println(" enabledComponents:");
6132 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006133 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006134 }
6135 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006136 if (ps.grantedPermissions.size() > 0) {
6137 pw.println(" grantedPermissions:");
6138 for (String s : ps.grantedPermissions) {
6139 pw.print(" "); pw.println(s);
6140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006142 if (ps.loadedPermissions.size() > 0) {
6143 pw.println(" loadedPermissions:");
6144 for (String s : ps.loadedPermissions) {
6145 pw.print(" "); pw.println(s);
6146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 }
6148 }
6149 }
6150 pw.println(" ");
6151 pw.println("Shared Users:");
6152 {
6153 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006154 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6155 pw.print(Integer.toHexString(System.identityHashCode(su)));
6156 pw.println("):");
6157 pw.print(" userId="); pw.print(su.userId);
6158 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006159 pw.println(" grantedPermissions:");
6160 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006161 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 }
6163 pw.println(" loadedPermissions:");
6164 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006165 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 }
6167 }
6168 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 pw.println(" ");
6171 pw.println("Settings parse messages:");
6172 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006173
6174 pw.println(" ");
6175 pw.println("Package warning messages:");
6176 File fname = getSettingsProblemFile();
6177 FileInputStream in;
6178 try {
6179 in = new FileInputStream(fname);
6180 int avail = in.available();
6181 byte[] data = new byte[avail];
6182 in.read(data);
6183 pw.println(new String(data));
6184 } catch (FileNotFoundException e) {
6185 } catch (IOException e) {
6186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006188
6189 synchronized (mProviders) {
6190 pw.println(" ");
6191 pw.println("Registered ContentProviders:");
6192 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006193 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006194 pw.println(p.toString());
6195 }
6196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 }
6198
6199 static final class BasePermission {
6200 final static int TYPE_NORMAL = 0;
6201 final static int TYPE_BUILTIN = 1;
6202 final static int TYPE_DYNAMIC = 2;
6203
6204 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006205 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 final int type;
6207 PackageParser.Permission perm;
6208 PermissionInfo pendingInfo;
6209 int uid;
6210 int[] gids;
6211
6212 BasePermission(String _name, String _sourcePackage, int _type) {
6213 name = _name;
6214 sourcePackage = _sourcePackage;
6215 type = _type;
6216 }
6217 }
6218
6219 static class PackageSignatures {
6220 private Signature[] mSignatures;
6221
6222 PackageSignatures(Signature[] sigs) {
6223 assignSignatures(sigs);
6224 }
6225
6226 PackageSignatures() {
6227 }
6228
6229 void writeXml(XmlSerializer serializer, String tagName,
6230 ArrayList<Signature> pastSignatures) throws IOException {
6231 if (mSignatures == null) {
6232 return;
6233 }
6234 serializer.startTag(null, tagName);
6235 serializer.attribute(null, "count",
6236 Integer.toString(mSignatures.length));
6237 for (int i=0; i<mSignatures.length; i++) {
6238 serializer.startTag(null, "cert");
6239 final Signature sig = mSignatures[i];
6240 final int sigHash = sig.hashCode();
6241 final int numPast = pastSignatures.size();
6242 int j;
6243 for (j=0; j<numPast; j++) {
6244 Signature pastSig = pastSignatures.get(j);
6245 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6246 serializer.attribute(null, "index", Integer.toString(j));
6247 break;
6248 }
6249 }
6250 if (j >= numPast) {
6251 pastSignatures.add(sig);
6252 serializer.attribute(null, "index", Integer.toString(numPast));
6253 serializer.attribute(null, "key", sig.toCharsString());
6254 }
6255 serializer.endTag(null, "cert");
6256 }
6257 serializer.endTag(null, tagName);
6258 }
6259
6260 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6261 throws IOException, XmlPullParserException {
6262 String countStr = parser.getAttributeValue(null, "count");
6263 if (countStr == null) {
6264 reportSettingsProblem(Log.WARN,
6265 "Error in package manager settings: <signatures> has"
6266 + " no count at " + parser.getPositionDescription());
6267 XmlUtils.skipCurrentTag(parser);
6268 }
6269 final int count = Integer.parseInt(countStr);
6270 mSignatures = new Signature[count];
6271 int pos = 0;
6272
6273 int outerDepth = parser.getDepth();
6274 int type;
6275 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6276 && (type != XmlPullParser.END_TAG
6277 || parser.getDepth() > outerDepth)) {
6278 if (type == XmlPullParser.END_TAG
6279 || type == XmlPullParser.TEXT) {
6280 continue;
6281 }
6282
6283 String tagName = parser.getName();
6284 if (tagName.equals("cert")) {
6285 if (pos < count) {
6286 String index = parser.getAttributeValue(null, "index");
6287 if (index != null) {
6288 try {
6289 int idx = Integer.parseInt(index);
6290 String key = parser.getAttributeValue(null, "key");
6291 if (key == null) {
6292 if (idx >= 0 && idx < pastSignatures.size()) {
6293 Signature sig = pastSignatures.get(idx);
6294 if (sig != null) {
6295 mSignatures[pos] = pastSignatures.get(idx);
6296 pos++;
6297 } else {
6298 reportSettingsProblem(Log.WARN,
6299 "Error in package manager settings: <cert> "
6300 + "index " + index + " is not defined at "
6301 + parser.getPositionDescription());
6302 }
6303 } else {
6304 reportSettingsProblem(Log.WARN,
6305 "Error in package manager settings: <cert> "
6306 + "index " + index + " is out of bounds at "
6307 + parser.getPositionDescription());
6308 }
6309 } else {
6310 while (pastSignatures.size() <= idx) {
6311 pastSignatures.add(null);
6312 }
6313 Signature sig = new Signature(key);
6314 pastSignatures.set(idx, sig);
6315 mSignatures[pos] = sig;
6316 pos++;
6317 }
6318 } catch (NumberFormatException e) {
6319 reportSettingsProblem(Log.WARN,
6320 "Error in package manager settings: <cert> "
6321 + "index " + index + " is not a number at "
6322 + parser.getPositionDescription());
6323 }
6324 } else {
6325 reportSettingsProblem(Log.WARN,
6326 "Error in package manager settings: <cert> has"
6327 + " no index at " + parser.getPositionDescription());
6328 }
6329 } else {
6330 reportSettingsProblem(Log.WARN,
6331 "Error in package manager settings: too "
6332 + "many <cert> tags, expected " + count
6333 + " at " + parser.getPositionDescription());
6334 }
6335 } else {
6336 reportSettingsProblem(Log.WARN,
6337 "Unknown element under <cert>: "
6338 + parser.getName());
6339 }
6340 XmlUtils.skipCurrentTag(parser);
6341 }
6342
6343 if (pos < count) {
6344 // Should never happen -- there is an error in the written
6345 // settings -- but if it does we don't want to generate
6346 // a bad array.
6347 Signature[] newSigs = new Signature[pos];
6348 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6349 mSignatures = newSigs;
6350 }
6351 }
6352
6353 /**
6354 * If any of the given 'sigs' is contained in the existing signatures,
6355 * then completely replace the current signatures with the ones in
6356 * 'sigs'. This is used for updating an existing package to a newly
6357 * installed version.
6358 */
6359 boolean updateSignatures(Signature[] sigs, boolean update) {
6360 if (mSignatures == null) {
6361 if (update) {
6362 assignSignatures(sigs);
6363 }
6364 return true;
6365 }
6366 if (sigs == null) {
6367 return false;
6368 }
6369
6370 for (int i=0; i<sigs.length; i++) {
6371 Signature sig = sigs[i];
6372 for (int j=0; j<mSignatures.length; j++) {
6373 if (mSignatures[j].equals(sig)) {
6374 if (update) {
6375 assignSignatures(sigs);
6376 }
6377 return true;
6378 }
6379 }
6380 }
6381 return false;
6382 }
6383
6384 /**
6385 * If any of the given 'sigs' is contained in the existing signatures,
6386 * then add in any new signatures found in 'sigs'. This is used for
6387 * including a new package into an existing shared user id.
6388 */
6389 boolean mergeSignatures(Signature[] sigs, boolean update) {
6390 if (mSignatures == null) {
6391 if (update) {
6392 assignSignatures(sigs);
6393 }
6394 return true;
6395 }
6396 if (sigs == null) {
6397 return false;
6398 }
6399
6400 Signature[] added = null;
6401 int addedCount = 0;
6402 boolean haveMatch = false;
6403 for (int i=0; i<sigs.length; i++) {
6404 Signature sig = sigs[i];
6405 boolean found = false;
6406 for (int j=0; j<mSignatures.length; j++) {
6407 if (mSignatures[j].equals(sig)) {
6408 found = true;
6409 haveMatch = true;
6410 break;
6411 }
6412 }
6413
6414 if (!found) {
6415 if (added == null) {
6416 added = new Signature[sigs.length];
6417 }
6418 added[i] = sig;
6419 addedCount++;
6420 }
6421 }
6422
6423 if (!haveMatch) {
6424 // Nothing matched -- reject the new signatures.
6425 return false;
6426 }
6427 if (added == null) {
6428 // Completely matched -- nothing else to do.
6429 return true;
6430 }
6431
6432 // Add additional signatures in.
6433 if (update) {
6434 Signature[] total = new Signature[addedCount+mSignatures.length];
6435 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6436 int j = mSignatures.length;
6437 for (int i=0; i<added.length; i++) {
6438 if (added[i] != null) {
6439 total[j] = added[i];
6440 j++;
6441 }
6442 }
6443 mSignatures = total;
6444 }
6445 return true;
6446 }
6447
6448 private void assignSignatures(Signature[] sigs) {
6449 if (sigs == null) {
6450 mSignatures = null;
6451 return;
6452 }
6453 mSignatures = new Signature[sigs.length];
6454 for (int i=0; i<sigs.length; i++) {
6455 mSignatures[i] = sigs[i];
6456 }
6457 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 @Override
6460 public String toString() {
6461 StringBuffer buf = new StringBuffer(128);
6462 buf.append("PackageSignatures{");
6463 buf.append(Integer.toHexString(System.identityHashCode(this)));
6464 buf.append(" [");
6465 if (mSignatures != null) {
6466 for (int i=0; i<mSignatures.length; i++) {
6467 if (i > 0) buf.append(", ");
6468 buf.append(Integer.toHexString(
6469 System.identityHashCode(mSignatures[i])));
6470 }
6471 }
6472 buf.append("]}");
6473 return buf.toString();
6474 }
6475 }
6476
6477 static class PreferredActivity extends IntentFilter {
6478 final int mMatch;
6479 final String[] mSetPackages;
6480 final String[] mSetClasses;
6481 final String[] mSetComponents;
6482 final ComponentName mActivity;
6483 final String mShortActivity;
6484 String mParseError;
6485
6486 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6487 ComponentName activity) {
6488 super(filter);
6489 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6490 mActivity = activity;
6491 mShortActivity = activity.flattenToShortString();
6492 mParseError = null;
6493 if (set != null) {
6494 final int N = set.length;
6495 String[] myPackages = new String[N];
6496 String[] myClasses = new String[N];
6497 String[] myComponents = new String[N];
6498 for (int i=0; i<N; i++) {
6499 ComponentName cn = set[i];
6500 if (cn == null) {
6501 mSetPackages = null;
6502 mSetClasses = null;
6503 mSetComponents = null;
6504 return;
6505 }
6506 myPackages[i] = cn.getPackageName().intern();
6507 myClasses[i] = cn.getClassName().intern();
6508 myComponents[i] = cn.flattenToShortString().intern();
6509 }
6510 mSetPackages = myPackages;
6511 mSetClasses = myClasses;
6512 mSetComponents = myComponents;
6513 } else {
6514 mSetPackages = null;
6515 mSetClasses = null;
6516 mSetComponents = null;
6517 }
6518 }
6519
6520 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6521 IOException {
6522 mShortActivity = parser.getAttributeValue(null, "name");
6523 mActivity = ComponentName.unflattenFromString(mShortActivity);
6524 if (mActivity == null) {
6525 mParseError = "Bad activity name " + mShortActivity;
6526 }
6527 String matchStr = parser.getAttributeValue(null, "match");
6528 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6529 String setCountStr = parser.getAttributeValue(null, "set");
6530 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6531
6532 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6533 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6534 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6535
6536 int setPos = 0;
6537
6538 int outerDepth = parser.getDepth();
6539 int type;
6540 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6541 && (type != XmlPullParser.END_TAG
6542 || parser.getDepth() > outerDepth)) {
6543 if (type == XmlPullParser.END_TAG
6544 || type == XmlPullParser.TEXT) {
6545 continue;
6546 }
6547
6548 String tagName = parser.getName();
6549 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6550 // + parser.getDepth() + " tag=" + tagName);
6551 if (tagName.equals("set")) {
6552 String name = parser.getAttributeValue(null, "name");
6553 if (name == null) {
6554 if (mParseError == null) {
6555 mParseError = "No name in set tag in preferred activity "
6556 + mShortActivity;
6557 }
6558 } else if (setPos >= setCount) {
6559 if (mParseError == null) {
6560 mParseError = "Too many set tags in preferred activity "
6561 + mShortActivity;
6562 }
6563 } else {
6564 ComponentName cn = ComponentName.unflattenFromString(name);
6565 if (cn == null) {
6566 if (mParseError == null) {
6567 mParseError = "Bad set name " + name + " in preferred activity "
6568 + mShortActivity;
6569 }
6570 } else {
6571 myPackages[setPos] = cn.getPackageName();
6572 myClasses[setPos] = cn.getClassName();
6573 myComponents[setPos] = name;
6574 setPos++;
6575 }
6576 }
6577 XmlUtils.skipCurrentTag(parser);
6578 } else if (tagName.equals("filter")) {
6579 //Log.i(TAG, "Starting to parse filter...");
6580 readFromXml(parser);
6581 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6582 // + parser.getDepth() + " tag=" + parser.getName());
6583 } else {
6584 reportSettingsProblem(Log.WARN,
6585 "Unknown element under <preferred-activities>: "
6586 + parser.getName());
6587 XmlUtils.skipCurrentTag(parser);
6588 }
6589 }
6590
6591 if (setPos != setCount) {
6592 if (mParseError == null) {
6593 mParseError = "Not enough set tags (expected " + setCount
6594 + " but found " + setPos + ") in " + mShortActivity;
6595 }
6596 }
6597
6598 mSetPackages = myPackages;
6599 mSetClasses = myClasses;
6600 mSetComponents = myComponents;
6601 }
6602
6603 public void writeToXml(XmlSerializer serializer) throws IOException {
6604 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6605 serializer.attribute(null, "name", mShortActivity);
6606 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6607 serializer.attribute(null, "set", Integer.toString(NS));
6608 for (int s=0; s<NS; s++) {
6609 serializer.startTag(null, "set");
6610 serializer.attribute(null, "name", mSetComponents[s]);
6611 serializer.endTag(null, "set");
6612 }
6613 serializer.startTag(null, "filter");
6614 super.writeToXml(serializer);
6615 serializer.endTag(null, "filter");
6616 }
6617
6618 boolean sameSet(List<ResolveInfo> query, int priority) {
6619 if (mSetPackages == null) return false;
6620 final int NQ = query.size();
6621 final int NS = mSetPackages.length;
6622 int numMatch = 0;
6623 for (int i=0; i<NQ; i++) {
6624 ResolveInfo ri = query.get(i);
6625 if (ri.priority != priority) continue;
6626 ActivityInfo ai = ri.activityInfo;
6627 boolean good = false;
6628 for (int j=0; j<NS; j++) {
6629 if (mSetPackages[j].equals(ai.packageName)
6630 && mSetClasses[j].equals(ai.name)) {
6631 numMatch++;
6632 good = true;
6633 break;
6634 }
6635 }
6636 if (!good) return false;
6637 }
6638 return numMatch == NS;
6639 }
6640 }
6641
6642 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006643 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 HashSet<String> grantedPermissions = new HashSet<String>();
6646 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006651 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
6652 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6653 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006654 }
6655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657 /**
6658 * Settings base class for pending and resolved classes.
6659 */
6660 static class PackageSettingBase extends GrantedPermissions {
6661 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006662 File codePath;
6663 String codePathString;
6664 File resourcePath;
6665 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 private long timeStamp;
6667 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006668 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006670 boolean uidError;
6671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006672 PackageSignatures signatures = new PackageSignatures();
6673
6674 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006676 /* Explicitly disabled components */
6677 HashSet<String> disabledComponents = new HashSet<String>(0);
6678 /* Explicitly enabled components */
6679 HashSet<String> enabledComponents = new HashSet<String>(0);
6680 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6681 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006682
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006683 PackageSettingBase origPackage;
6684
Jacek Surazski65e13172009-04-28 15:26:38 +02006685 /* package name of the app that installed this package */
6686 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687
6688 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006689 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 super(pkgFlags);
6691 this.name = name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006692 init(codePath, resourcePath, pVersionCode);
6693 }
6694
6695 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 this.codePath = codePath;
6697 this.codePathString = codePath.toString();
6698 this.resourcePath = resourcePath;
6699 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006700 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006702
Jacek Surazski65e13172009-04-28 15:26:38 +02006703 public void setInstallerPackageName(String packageName) {
6704 installerPackageName = packageName;
6705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006706
Jacek Surazski65e13172009-04-28 15:26:38 +02006707 String getInstallerPackageName() {
6708 return installerPackageName;
6709 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 public void setInstallStatus(int newStatus) {
6712 installStatus = newStatus;
6713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 public int getInstallStatus() {
6716 return installStatus;
6717 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 public void setTimeStamp(long newStamp) {
6720 if (newStamp != timeStamp) {
6721 timeStamp = newStamp;
6722 timeStampString = Long.toString(newStamp);
6723 }
6724 }
6725
6726 public void setTimeStamp(long newStamp, String newStampStr) {
6727 timeStamp = newStamp;
6728 timeStampString = newStampStr;
6729 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 public long getTimeStamp() {
6732 return timeStamp;
6733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 public String getTimeStampStr() {
6736 return timeStampString;
6737 }
6738
6739 public void copyFrom(PackageSettingBase base) {
6740 grantedPermissions = base.grantedPermissions;
6741 gids = base.gids;
6742 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006744 timeStamp = base.timeStamp;
6745 timeStampString = base.timeStampString;
6746 signatures = base.signatures;
6747 permissionsFixed = base.permissionsFixed;
6748 disabledComponents = base.disabledComponents;
6749 enabledComponents = base.enabledComponents;
6750 enabled = base.enabled;
6751 installStatus = base.installStatus;
6752 }
6753
6754 void enableComponentLP(String componentClassName) {
6755 disabledComponents.remove(componentClassName);
6756 enabledComponents.add(componentClassName);
6757 }
6758
6759 void disableComponentLP(String componentClassName) {
6760 enabledComponents.remove(componentClassName);
6761 disabledComponents.add(componentClassName);
6762 }
6763
6764 void restoreComponentLP(String componentClassName) {
6765 enabledComponents.remove(componentClassName);
6766 disabledComponents.remove(componentClassName);
6767 }
6768
6769 int currentEnabledStateLP(String componentName) {
6770 if (enabledComponents.contains(componentName)) {
6771 return COMPONENT_ENABLED_STATE_ENABLED;
6772 } else if (disabledComponents.contains(componentName)) {
6773 return COMPONENT_ENABLED_STATE_DISABLED;
6774 } else {
6775 return COMPONENT_ENABLED_STATE_DEFAULT;
6776 }
6777 }
6778 }
6779
6780 /**
6781 * Settings data for a particular package we know about.
6782 */
6783 static final class PackageSetting extends PackageSettingBase {
6784 int userId;
6785 PackageParser.Package pkg;
6786 SharedUserSetting sharedUser;
6787
6788 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006789 int pVersionCode, int pkgFlags) {
6790 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006791 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 @Override
6794 public String toString() {
6795 return "PackageSetting{"
6796 + Integer.toHexString(System.identityHashCode(this))
6797 + " " + name + "/" + userId + "}";
6798 }
6799 }
6800
6801 /**
6802 * Settings data for a particular shared user ID we know about.
6803 */
6804 static final class SharedUserSetting extends GrantedPermissions {
6805 final String name;
6806 int userId;
6807 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6808 final PackageSignatures signatures = new PackageSignatures();
6809
6810 SharedUserSetting(String _name, int _pkgFlags) {
6811 super(_pkgFlags);
6812 name = _name;
6813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 @Override
6816 public String toString() {
6817 return "SharedUserSetting{"
6818 + Integer.toHexString(System.identityHashCode(this))
6819 + " " + name + "/" + userId + "}";
6820 }
6821 }
6822
6823 /**
6824 * Holds information about dynamic settings.
6825 */
6826 private static final class Settings {
6827 private final File mSettingsFilename;
6828 private final File mBackupSettingsFilename;
6829 private final HashMap<String, PackageSetting> mPackages =
6830 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006831 // List of replaced system applications
6832 final HashMap<String, PackageSetting> mDisabledSysPackages =
6833 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006835 // The user's preferred activities associated with particular intent
6836 // filters.
6837 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6838 new IntentResolver<PreferredActivity, PreferredActivity>() {
6839 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006840 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006842 out.print(prefix); out.print(
6843 Integer.toHexString(System.identityHashCode(filter)));
6844 out.print(' ');
6845 out.print(filter.mActivity.flattenToShortString());
6846 out.print(" match=0x");
6847 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006848 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006849 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006850 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006851 out.print(prefix); out.print(" ");
6852 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006853 }
6854 }
6855 }
6856 };
6857 private final HashMap<String, SharedUserSetting> mSharedUsers =
6858 new HashMap<String, SharedUserSetting>();
6859 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6860 private final SparseArray<Object> mOtherUserIds =
6861 new SparseArray<Object>();
6862
6863 // For reading/writing settings file.
6864 private final ArrayList<Signature> mPastSignatures =
6865 new ArrayList<Signature>();
6866
6867 // Mapping from permission names to info about them.
6868 final HashMap<String, BasePermission> mPermissions =
6869 new HashMap<String, BasePermission>();
6870
6871 // Mapping from permission tree names to info about them.
6872 final HashMap<String, BasePermission> mPermissionTrees =
6873 new HashMap<String, BasePermission>();
6874
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006875 // Packages that have been uninstalled and still need their external
6876 // storage data deleted.
6877 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
6878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006879 private final StringBuilder mReadMessages = new StringBuilder();
6880
6881 private static final class PendingPackage extends PackageSettingBase {
6882 final int sharedId;
6883
6884 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006885 int sharedId, int pVersionCode, int pkgFlags) {
6886 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006887 this.sharedId = sharedId;
6888 }
6889 }
6890 private final ArrayList<PendingPackage> mPendingPackages
6891 = new ArrayList<PendingPackage>();
6892
6893 Settings() {
6894 File dataDir = Environment.getDataDirectory();
6895 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08006896 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
6897 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006898 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006899 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006900 FileUtils.setPermissions(systemDir.toString(),
6901 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6902 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6903 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08006904 FileUtils.setPermissions(systemSecureDir.toString(),
6905 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6906 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6907 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006908 mSettingsFilename = new File(systemDir, "packages.xml");
6909 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6910 }
6911
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006912 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006913 SharedUserSetting sharedUser, File codePath, File resourcePath,
6914 int pkgFlags, boolean create, boolean add) {
6915 final String name = pkg.packageName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006916 PackageSetting p = getPackageLP(name, origPackage, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006917 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 return p;
6919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006920
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006921 PackageSetting peekPackageLP(String name) {
6922 return mPackages.get(name);
6923 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006924 PackageSetting p = mPackages.get(name);
6925 if (p != null && p.codePath.getPath().equals(codePath)) {
6926 return p;
6927 }
6928 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006929 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006932 void setInstallStatus(String pkgName, int status) {
6933 PackageSetting p = mPackages.get(pkgName);
6934 if(p != null) {
6935 if(p.getInstallStatus() != status) {
6936 p.setInstallStatus(status);
6937 }
6938 }
6939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006940
Jacek Surazski65e13172009-04-28 15:26:38 +02006941 void setInstallerPackageName(String pkgName,
6942 String installerPkgName) {
6943 PackageSetting p = mPackages.get(pkgName);
6944 if(p != null) {
6945 p.setInstallerPackageName(installerPkgName);
6946 }
6947 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006948
Jacek Surazski65e13172009-04-28 15:26:38 +02006949 String getInstallerPackageName(String pkgName) {
6950 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006951 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02006952 }
6953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954 int getInstallStatus(String pkgName) {
6955 PackageSetting p = mPackages.get(pkgName);
6956 if(p != null) {
6957 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006959 return -1;
6960 }
6961
6962 SharedUserSetting getSharedUserLP(String name,
6963 int pkgFlags, boolean create) {
6964 SharedUserSetting s = mSharedUsers.get(name);
6965 if (s == null) {
6966 if (!create) {
6967 return null;
6968 }
6969 s = new SharedUserSetting(name, pkgFlags);
6970 if (MULTIPLE_APPLICATION_UIDS) {
6971 s.userId = newUserIdLP(s);
6972 } else {
6973 s.userId = FIRST_APPLICATION_UID;
6974 }
6975 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6976 // < 0 means we couldn't assign a userid; fall out and return
6977 // s, which is currently null
6978 if (s.userId >= 0) {
6979 mSharedUsers.put(name, s);
6980 }
6981 }
6982
6983 return s;
6984 }
6985
6986 int disableSystemPackageLP(String name) {
6987 PackageSetting p = mPackages.get(name);
6988 if(p == null) {
6989 Log.w(TAG, "Package:"+name+" is not an installed package");
6990 return -1;
6991 }
6992 PackageSetting dp = mDisabledSysPackages.get(name);
6993 // always make sure the system package code and resource paths dont change
6994 if(dp == null) {
6995 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6996 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6997 }
6998 mDisabledSysPackages.put(name, p);
6999 }
7000 return removePackageLP(name);
7001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007003 PackageSetting enableSystemPackageLP(String name) {
7004 PackageSetting p = mDisabledSysPackages.get(name);
7005 if(p == null) {
7006 Log.w(TAG, "Package:"+name+" is not disabled");
7007 return null;
7008 }
7009 // Reset flag in ApplicationInfo object
7010 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7011 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7012 }
7013 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007014 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 mDisabledSysPackages.remove(name);
7016 return ret;
7017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007020 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 PackageSetting p = mPackages.get(name);
7022 if (p != null) {
7023 if (p.userId == uid) {
7024 return p;
7025 }
7026 reportSettingsProblem(Log.ERROR,
7027 "Adding duplicate package, keeping first: " + name);
7028 return null;
7029 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007030 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 p.userId = uid;
7032 if (addUserIdLP(uid, p, name)) {
7033 mPackages.put(name, p);
7034 return p;
7035 }
7036 return null;
7037 }
7038
7039 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7040 SharedUserSetting s = mSharedUsers.get(name);
7041 if (s != null) {
7042 if (s.userId == uid) {
7043 return s;
7044 }
7045 reportSettingsProblem(Log.ERROR,
7046 "Adding duplicate shared user, keeping first: " + name);
7047 return null;
7048 }
7049 s = new SharedUserSetting(name, pkgFlags);
7050 s.userId = uid;
7051 if (addUserIdLP(uid, s, name)) {
7052 mSharedUsers.put(name, s);
7053 return s;
7054 }
7055 return null;
7056 }
7057
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007058 // Transfer ownership of permissions from one package to another.
7059 private void transferPermissions(String origPkg, String newPkg) {
7060 // Transfer ownership of permissions to the new package.
7061 for (int i=0; i<2; i++) {
7062 HashMap<String, BasePermission> permissions =
7063 i == 0 ? mPermissionTrees : mPermissions;
7064 for (BasePermission bp : permissions.values()) {
7065 if (origPkg.equals(bp.sourcePackage)) {
7066 if (DEBUG_UPGRADE) Log.v(TAG,
7067 "Moving permission " + bp.name
7068 + " from pkg " + bp.sourcePackage
7069 + " to " + newPkg);
7070 bp.sourcePackage = newPkg;
7071 bp.perm = null;
7072 if (bp.pendingInfo != null) {
7073 bp.sourcePackage = newPkg;
7074 }
7075 bp.uid = 0;
7076 bp.gids = null;
7077 }
7078 }
7079 }
7080 }
7081
7082 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007084 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007085 PackageSetting p = mPackages.get(name);
7086 if (p != null) {
7087 if (!p.codePath.equals(codePath)) {
7088 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007089 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007090 // This is an updated system app with versions in both system
7091 // and data partition. Just let the most recent version
7092 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007093 Log.w(TAG, "Trying to update system app code path from " +
7094 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007095 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007096 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07007097 reportSettingsProblem(Log.WARN,
7098 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007099 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007100 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007101 }
7102 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 reportSettingsProblem(Log.WARN,
7104 "Package " + name + " shared user changed from "
7105 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7106 + " to "
7107 + (sharedUser != null ? sharedUser.name : "<nothing>")
7108 + "; replacing with new");
7109 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007110 } else {
7111 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7112 // If what we are scanning is a system package, then
7113 // make it so, regardless of whether it was previously
7114 // installed only in the data partition.
7115 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 }
7118 }
7119 if (p == null) {
7120 // Create a new PackageSettings entry. this can end up here because
7121 // of code path mismatch or user id mismatch of an updated system partition
7122 if (!create) {
7123 return null;
7124 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007125 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007126 if (origPackage != null) {
7127 // We are consuming the data from an existing package.
7128 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7129 + " is adopting original package " + origPackage.name);
7130 p.copyFrom(origPackage);
7131 p.sharedUser = origPackage.sharedUser;
7132 p.userId = origPackage.userId;
7133 p.origPackage = origPackage;
7134 transferPermissions(origPackage.name, name);
7135 // Update new package state.
7136 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007137 } else {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007138 p.setTimeStamp(codePath.lastModified());
7139 p.sharedUser = sharedUser;
7140 if (sharedUser != null) {
7141 p.userId = sharedUser.userId;
7142 } else if (MULTIPLE_APPLICATION_UIDS) {
7143 // Clone the setting here for disabled system packages
7144 PackageSetting dis = mDisabledSysPackages.get(name);
7145 if (dis != null) {
7146 // For disabled packages a new setting is created
7147 // from the existing user id. This still has to be
7148 // added to list of user id's
7149 // Copy signatures from previous setting
7150 if (dis.signatures.mSignatures != null) {
7151 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7152 }
7153 p.userId = dis.userId;
7154 // Clone permissions
7155 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7156 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7157 // Clone component info
7158 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7159 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7160 // Add new setting to list of user ids
7161 addUserIdLP(p.userId, p, name);
7162 } else {
7163 // Assign new user id
7164 p.userId = newUserIdLP(p);
7165 }
7166 } else {
7167 p.userId = FIRST_APPLICATION_UID;
7168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007169 }
7170 if (p.userId < 0) {
7171 reportSettingsProblem(Log.WARN,
7172 "Package " + name + " could not be assigned a valid uid");
7173 return null;
7174 }
7175 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007176 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007178 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007179 }
7180 }
7181 return p;
7182 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007183
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007184 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007185 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007186 String codePath = pkg.applicationInfo.sourceDir;
7187 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007188 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007189 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007190 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007191 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007192 p.codePath = new File(codePath);
7193 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007194 }
7195 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007196 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007197 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007198 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007199 p.resourcePath = new File(resourcePath);
7200 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007201 }
7202 // Update version code if needed
7203 if (pkg.mVersionCode != p.versionCode) {
7204 p.versionCode = pkg.mVersionCode;
7205 }
7206 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7207 }
7208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 // Utility method that adds a PackageSetting to mPackages and
7210 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007211 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 SharedUserSetting sharedUser) {
7213 mPackages.put(name, p);
7214 if (sharedUser != null) {
7215 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7216 reportSettingsProblem(Log.ERROR,
7217 "Package " + p.name + " was user "
7218 + p.sharedUser + " but is now " + sharedUser
7219 + "; I am not changing its files so it will probably fail!");
7220 p.sharedUser.packages.remove(p);
7221 } else if (p.userId != sharedUser.userId) {
7222 reportSettingsProblem(Log.ERROR,
7223 "Package " + p.name + " was user id " + p.userId
7224 + " but is now user " + sharedUser
7225 + " with id " + sharedUser.userId
7226 + "; I am not changing its files so it will probably fail!");
7227 }
7228
7229 sharedUser.packages.add(p);
7230 p.sharedUser = sharedUser;
7231 p.userId = sharedUser.userId;
7232 }
7233 }
7234
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007235 /*
7236 * Update the shared user setting when a package using
7237 * specifying the shared user id is removed. The gids
7238 * associated with each permission of the deleted package
7239 * are removed from the shared user's gid list only if its
7240 * not in use by other permissions of packages in the
7241 * shared user setting.
7242 */
7243 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007244 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7245 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7246 return;
7247 }
7248 // No sharedUserId
7249 if (deletedPs.sharedUser == null) {
7250 return;
7251 }
7252 SharedUserSetting sus = deletedPs.sharedUser;
7253 // Update permissions
7254 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7255 boolean used = false;
7256 if (!sus.grantedPermissions.contains (eachPerm)) {
7257 continue;
7258 }
7259 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007260 if (pkg.pkg != null &&
7261 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7262 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007263 used = true;
7264 break;
7265 }
7266 }
7267 if (!used) {
7268 // can safely delete this permission from list
7269 sus.grantedPermissions.remove(eachPerm);
7270 sus.loadedPermissions.remove(eachPerm);
7271 }
7272 }
7273 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007274 int newGids[] = globalGids;
7275 for (String eachPerm : sus.grantedPermissions) {
7276 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007277 if (bp != null) {
7278 newGids = appendInts(newGids, bp.gids);
7279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007280 }
7281 sus.gids = newGids;
7282 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 private int removePackageLP(String name) {
7285 PackageSetting p = mPackages.get(name);
7286 if (p != null) {
7287 mPackages.remove(name);
7288 if (p.sharedUser != null) {
7289 p.sharedUser.packages.remove(p);
7290 if (p.sharedUser.packages.size() == 0) {
7291 mSharedUsers.remove(p.sharedUser.name);
7292 removeUserIdLP(p.sharedUser.userId);
7293 return p.sharedUser.userId;
7294 }
7295 } else {
7296 removeUserIdLP(p.userId);
7297 return p.userId;
7298 }
7299 }
7300 return -1;
7301 }
7302
7303 private boolean addUserIdLP(int uid, Object obj, Object name) {
7304 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7305 return false;
7306 }
7307
7308 if (uid >= FIRST_APPLICATION_UID) {
7309 int N = mUserIds.size();
7310 final int index = uid - FIRST_APPLICATION_UID;
7311 while (index >= N) {
7312 mUserIds.add(null);
7313 N++;
7314 }
7315 if (mUserIds.get(index) != null) {
7316 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007317 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007318 + " name=" + name);
7319 return false;
7320 }
7321 mUserIds.set(index, obj);
7322 } else {
7323 if (mOtherUserIds.get(uid) != null) {
7324 reportSettingsProblem(Log.ERROR,
7325 "Adding duplicate shared id: " + uid
7326 + " name=" + name);
7327 return false;
7328 }
7329 mOtherUserIds.put(uid, obj);
7330 }
7331 return true;
7332 }
7333
7334 public Object getUserIdLP(int uid) {
7335 if (uid >= FIRST_APPLICATION_UID) {
7336 int N = mUserIds.size();
7337 final int index = uid - FIRST_APPLICATION_UID;
7338 return index < N ? mUserIds.get(index) : null;
7339 } else {
7340 return mOtherUserIds.get(uid);
7341 }
7342 }
7343
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007344 private Set<String> findPackagesWithFlag(int flag) {
7345 Set<String> ret = new HashSet<String>();
7346 for (PackageSetting ps : mPackages.values()) {
7347 // Has to match atleast all the flag bits set on flag
7348 if ((ps.pkgFlags & flag) == flag) {
7349 ret.add(ps.name);
7350 }
7351 }
7352 return ret;
7353 }
7354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007355 private void removeUserIdLP(int uid) {
7356 if (uid >= FIRST_APPLICATION_UID) {
7357 int N = mUserIds.size();
7358 final int index = uid - FIRST_APPLICATION_UID;
7359 if (index < N) mUserIds.set(index, null);
7360 } else {
7361 mOtherUserIds.remove(uid);
7362 }
7363 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007365 void writeLP() {
7366 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7367
7368 // Keep the old settings around until we know the new ones have
7369 // been successfully written.
7370 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007371 // Presence of backup settings file indicates that we failed
7372 // to persist settings earlier. So preserve the older
7373 // backup for future reference since the current settings
7374 // might have been corrupted.
7375 if (!mBackupSettingsFilename.exists()) {
7376 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7377 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7378 return;
7379 }
7380 } else {
7381 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007383 }
7384
7385 mPastSignatures.clear();
7386
7387 try {
7388 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7389
7390 //XmlSerializer serializer = XmlUtils.serializerInstance();
7391 XmlSerializer serializer = new FastXmlSerializer();
7392 serializer.setOutput(str, "utf-8");
7393 serializer.startDocument(null, true);
7394 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7395
7396 serializer.startTag(null, "packages");
7397
7398 serializer.startTag(null, "permission-trees");
7399 for (BasePermission bp : mPermissionTrees.values()) {
7400 writePermission(serializer, bp);
7401 }
7402 serializer.endTag(null, "permission-trees");
7403
7404 serializer.startTag(null, "permissions");
7405 for (BasePermission bp : mPermissions.values()) {
7406 writePermission(serializer, bp);
7407 }
7408 serializer.endTag(null, "permissions");
7409
7410 for (PackageSetting pkg : mPackages.values()) {
7411 writePackage(serializer, pkg);
7412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007414 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7415 writeDisabledSysPackage(serializer, pkg);
7416 }
7417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007418 serializer.startTag(null, "preferred-activities");
7419 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7420 serializer.startTag(null, "item");
7421 pa.writeToXml(serializer);
7422 serializer.endTag(null, "item");
7423 }
7424 serializer.endTag(null, "preferred-activities");
7425
7426 for (SharedUserSetting usr : mSharedUsers.values()) {
7427 serializer.startTag(null, "shared-user");
7428 serializer.attribute(null, "name", usr.name);
7429 serializer.attribute(null, "userId",
7430 Integer.toString(usr.userId));
7431 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7432 serializer.startTag(null, "perms");
7433 for (String name : usr.grantedPermissions) {
7434 serializer.startTag(null, "item");
7435 serializer.attribute(null, "name", name);
7436 serializer.endTag(null, "item");
7437 }
7438 serializer.endTag(null, "perms");
7439 serializer.endTag(null, "shared-user");
7440 }
7441
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007442 if (mPackagesToBeCleaned.size() > 0) {
7443 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7444 serializer.startTag(null, "cleaning-package");
7445 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7446 serializer.endTag(null, "cleaning-package");
7447 }
7448 }
7449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007450 serializer.endTag(null, "packages");
7451
7452 serializer.endDocument();
7453
7454 str.flush();
7455 str.close();
7456
7457 // New settings successfully written, old ones are no longer
7458 // needed.
7459 mBackupSettingsFilename.delete();
7460 FileUtils.setPermissions(mSettingsFilename.toString(),
7461 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7462 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7463 |FileUtils.S_IROTH,
7464 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007465 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007466
7467 } catch(XmlPullParserException e) {
7468 Log.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 -08007469 } catch(java.io.IOException e) {
7470 Log.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 -08007471 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007472 // Clean up partially written file
7473 if (mSettingsFilename.exists()) {
7474 if (!mSettingsFilename.delete()) {
7475 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7476 }
7477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 //Debug.stopMethodTracing();
7479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007480
7481 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007482 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 serializer.startTag(null, "updated-package");
7484 serializer.attribute(null, "name", pkg.name);
7485 serializer.attribute(null, "codePath", pkg.codePathString);
7486 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007487 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007488 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7489 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7490 }
7491 if (pkg.sharedUser == null) {
7492 serializer.attribute(null, "userId",
7493 Integer.toString(pkg.userId));
7494 } else {
7495 serializer.attribute(null, "sharedUserId",
7496 Integer.toString(pkg.userId));
7497 }
7498 serializer.startTag(null, "perms");
7499 if (pkg.sharedUser == null) {
7500 // If this is a shared user, the permissions will
7501 // be written there. We still need to write an
7502 // empty permissions list so permissionsFixed will
7503 // be set.
7504 for (final String name : pkg.grantedPermissions) {
7505 BasePermission bp = mPermissions.get(name);
7506 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7507 // We only need to write signature or system permissions but this wont
7508 // match the semantics of grantedPermissions. So write all permissions.
7509 serializer.startTag(null, "item");
7510 serializer.attribute(null, "name", name);
7511 serializer.endTag(null, "item");
7512 }
7513 }
7514 }
7515 serializer.endTag(null, "perms");
7516 serializer.endTag(null, "updated-package");
7517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007518
7519 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007520 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007521 serializer.startTag(null, "package");
7522 serializer.attribute(null, "name", pkg.name);
7523 serializer.attribute(null, "codePath", pkg.codePathString);
7524 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7525 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7526 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007527 serializer.attribute(null, "flags",
7528 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007529 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007530 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007531 if (pkg.sharedUser == null) {
7532 serializer.attribute(null, "userId",
7533 Integer.toString(pkg.userId));
7534 } else {
7535 serializer.attribute(null, "sharedUserId",
7536 Integer.toString(pkg.userId));
7537 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007538 if (pkg.uidError) {
7539 serializer.attribute(null, "uidError", "true");
7540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007541 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7542 serializer.attribute(null, "enabled",
7543 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7544 ? "true" : "false");
7545 }
7546 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7547 serializer.attribute(null, "installStatus", "false");
7548 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007549 if (pkg.installerPackageName != null) {
7550 serializer.attribute(null, "installer", pkg.installerPackageName);
7551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7553 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7554 serializer.startTag(null, "perms");
7555 if (pkg.sharedUser == null) {
7556 // If this is a shared user, the permissions will
7557 // be written there. We still need to write an
7558 // empty permissions list so permissionsFixed will
7559 // be set.
7560 for (final String name : pkg.grantedPermissions) {
7561 serializer.startTag(null, "item");
7562 serializer.attribute(null, "name", name);
7563 serializer.endTag(null, "item");
7564 }
7565 }
7566 serializer.endTag(null, "perms");
7567 }
7568 if (pkg.disabledComponents.size() > 0) {
7569 serializer.startTag(null, "disabled-components");
7570 for (final String name : pkg.disabledComponents) {
7571 serializer.startTag(null, "item");
7572 serializer.attribute(null, "name", name);
7573 serializer.endTag(null, "item");
7574 }
7575 serializer.endTag(null, "disabled-components");
7576 }
7577 if (pkg.enabledComponents.size() > 0) {
7578 serializer.startTag(null, "enabled-components");
7579 for (final String name : pkg.enabledComponents) {
7580 serializer.startTag(null, "item");
7581 serializer.attribute(null, "name", name);
7582 serializer.endTag(null, "item");
7583 }
7584 serializer.endTag(null, "enabled-components");
7585 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 serializer.endTag(null, "package");
7588 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 void writePermission(XmlSerializer serializer, BasePermission bp)
7591 throws XmlPullParserException, java.io.IOException {
7592 if (bp.type != BasePermission.TYPE_BUILTIN
7593 && bp.sourcePackage != null) {
7594 serializer.startTag(null, "item");
7595 serializer.attribute(null, "name", bp.name);
7596 serializer.attribute(null, "package", bp.sourcePackage);
7597 if (DEBUG_SETTINGS) Log.v(TAG,
7598 "Writing perm: name=" + bp.name + " type=" + bp.type);
7599 if (bp.type == BasePermission.TYPE_DYNAMIC) {
7600 PermissionInfo pi = bp.perm != null ? bp.perm.info
7601 : bp.pendingInfo;
7602 if (pi != null) {
7603 serializer.attribute(null, "type", "dynamic");
7604 if (pi.icon != 0) {
7605 serializer.attribute(null, "icon",
7606 Integer.toString(pi.icon));
7607 }
7608 if (pi.nonLocalizedLabel != null) {
7609 serializer.attribute(null, "label",
7610 pi.nonLocalizedLabel.toString());
7611 }
7612 if (pi.protectionLevel !=
7613 PermissionInfo.PROTECTION_NORMAL) {
7614 serializer.attribute(null, "protection",
7615 Integer.toString(pi.protectionLevel));
7616 }
7617 }
7618 }
7619 serializer.endTag(null, "item");
7620 }
7621 }
7622
7623 String getReadMessagesLP() {
7624 return mReadMessages.toString();
7625 }
7626
Oscar Montemayora8529f62009-11-18 10:14:20 -08007627 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
7629 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007630 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007631 while(its.hasNext()) {
7632 String key = its.next();
7633 PackageSetting ps = mPackages.get(key);
7634 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08007635 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 }
7637 }
7638 return ret;
7639 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 boolean readLP() {
7642 FileInputStream str = null;
7643 if (mBackupSettingsFilename.exists()) {
7644 try {
7645 str = new FileInputStream(mBackupSettingsFilename);
7646 mReadMessages.append("Reading from backup settings file\n");
7647 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007648 if (mSettingsFilename.exists()) {
7649 // If both the backup and settings file exist, we
7650 // ignore the settings since it might have been
7651 // corrupted.
7652 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
7653 mSettingsFilename.delete();
7654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655 } catch (java.io.IOException e) {
7656 // We'll try for the normal settings file.
7657 }
7658 }
7659
7660 mPastSignatures.clear();
7661
7662 try {
7663 if (str == null) {
7664 if (!mSettingsFilename.exists()) {
7665 mReadMessages.append("No settings file found\n");
7666 Log.i(TAG, "No current settings file!");
7667 return false;
7668 }
7669 str = new FileInputStream(mSettingsFilename);
7670 }
7671 XmlPullParser parser = Xml.newPullParser();
7672 parser.setInput(str, null);
7673
7674 int type;
7675 while ((type=parser.next()) != XmlPullParser.START_TAG
7676 && type != XmlPullParser.END_DOCUMENT) {
7677 ;
7678 }
7679
7680 if (type != XmlPullParser.START_TAG) {
7681 mReadMessages.append("No start tag found in settings file\n");
7682 Log.e(TAG, "No start tag found in package manager settings");
7683 return false;
7684 }
7685
7686 int outerDepth = parser.getDepth();
7687 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7688 && (type != XmlPullParser.END_TAG
7689 || parser.getDepth() > outerDepth)) {
7690 if (type == XmlPullParser.END_TAG
7691 || type == XmlPullParser.TEXT) {
7692 continue;
7693 }
7694
7695 String tagName = parser.getName();
7696 if (tagName.equals("package")) {
7697 readPackageLP(parser);
7698 } else if (tagName.equals("permissions")) {
7699 readPermissionsLP(mPermissions, parser);
7700 } else if (tagName.equals("permission-trees")) {
7701 readPermissionsLP(mPermissionTrees, parser);
7702 } else if (tagName.equals("shared-user")) {
7703 readSharedUserLP(parser);
7704 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08007705 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007706 } else if (tagName.equals("preferred-activities")) {
7707 readPreferredActivitiesLP(parser);
7708 } else if(tagName.equals("updated-package")) {
7709 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007710 } else if (tagName.equals("cleaning-package")) {
7711 String name = parser.getAttributeValue(null, "name");
7712 if (name != null) {
7713 mPackagesToBeCleaned.add(name);
7714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 } else {
7716 Log.w(TAG, "Unknown element under <packages>: "
7717 + parser.getName());
7718 XmlUtils.skipCurrentTag(parser);
7719 }
7720 }
7721
7722 str.close();
7723
7724 } catch(XmlPullParserException e) {
7725 mReadMessages.append("Error reading: " + e.toString());
7726 Log.e(TAG, "Error reading package manager settings", e);
7727
7728 } catch(java.io.IOException e) {
7729 mReadMessages.append("Error reading: " + e.toString());
7730 Log.e(TAG, "Error reading package manager settings", e);
7731
7732 }
7733
7734 int N = mPendingPackages.size();
7735 for (int i=0; i<N; i++) {
7736 final PendingPackage pp = mPendingPackages.get(i);
7737 Object idObj = getUserIdLP(pp.sharedId);
7738 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007739 PackageSetting p = getPackageLP(pp.name, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007741 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742 if (p == null) {
7743 Log.w(TAG, "Unable to create application package for "
7744 + pp.name);
7745 continue;
7746 }
7747 p.copyFrom(pp);
7748 } else if (idObj != null) {
7749 String msg = "Bad package setting: package " + pp.name
7750 + " has shared uid " + pp.sharedId
7751 + " that is not a shared uid\n";
7752 mReadMessages.append(msg);
7753 Log.e(TAG, msg);
7754 } else {
7755 String msg = "Bad package setting: package " + pp.name
7756 + " has shared uid " + pp.sharedId
7757 + " that is not defined\n";
7758 mReadMessages.append(msg);
7759 Log.e(TAG, msg);
7760 }
7761 }
7762 mPendingPackages.clear();
7763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 mReadMessages.append("Read completed successfully: "
7765 + mPackages.size() + " packages, "
7766 + mSharedUsers.size() + " shared uids\n");
7767
7768 return true;
7769 }
7770
7771 private int readInt(XmlPullParser parser, String ns, String name,
7772 int defValue) {
7773 String v = parser.getAttributeValue(ns, name);
7774 try {
7775 if (v == null) {
7776 return defValue;
7777 }
7778 return Integer.parseInt(v);
7779 } catch (NumberFormatException e) {
7780 reportSettingsProblem(Log.WARN,
7781 "Error in package manager settings: attribute " +
7782 name + " has bad integer value " + v + " at "
7783 + parser.getPositionDescription());
7784 }
7785 return defValue;
7786 }
7787
7788 private void readPermissionsLP(HashMap<String, BasePermission> out,
7789 XmlPullParser parser)
7790 throws IOException, XmlPullParserException {
7791 int outerDepth = parser.getDepth();
7792 int type;
7793 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7794 && (type != XmlPullParser.END_TAG
7795 || parser.getDepth() > outerDepth)) {
7796 if (type == XmlPullParser.END_TAG
7797 || type == XmlPullParser.TEXT) {
7798 continue;
7799 }
7800
7801 String tagName = parser.getName();
7802 if (tagName.equals("item")) {
7803 String name = parser.getAttributeValue(null, "name");
7804 String sourcePackage = parser.getAttributeValue(null, "package");
7805 String ptype = parser.getAttributeValue(null, "type");
7806 if (name != null && sourcePackage != null) {
7807 boolean dynamic = "dynamic".equals(ptype);
7808 BasePermission bp = new BasePermission(name, sourcePackage,
7809 dynamic
7810 ? BasePermission.TYPE_DYNAMIC
7811 : BasePermission.TYPE_NORMAL);
7812 if (dynamic) {
7813 PermissionInfo pi = new PermissionInfo();
7814 pi.packageName = sourcePackage.intern();
7815 pi.name = name.intern();
7816 pi.icon = readInt(parser, null, "icon", 0);
7817 pi.nonLocalizedLabel = parser.getAttributeValue(
7818 null, "label");
7819 pi.protectionLevel = readInt(parser, null, "protection",
7820 PermissionInfo.PROTECTION_NORMAL);
7821 bp.pendingInfo = pi;
7822 }
7823 out.put(bp.name, bp);
7824 } else {
7825 reportSettingsProblem(Log.WARN,
7826 "Error in package manager settings: permissions has"
7827 + " no name at " + parser.getPositionDescription());
7828 }
7829 } else {
7830 reportSettingsProblem(Log.WARN,
7831 "Unknown element reading permissions: "
7832 + parser.getName() + " at "
7833 + parser.getPositionDescription());
7834 }
7835 XmlUtils.skipCurrentTag(parser);
7836 }
7837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007839 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007840 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007841 String name = parser.getAttributeValue(null, "name");
7842 String codePathStr = parser.getAttributeValue(null, "codePath");
7843 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
7844 if(resourcePathStr == null) {
7845 resourcePathStr = codePathStr;
7846 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007847 String version = parser.getAttributeValue(null, "version");
7848 int versionCode = 0;
7849 if (version != null) {
7850 try {
7851 versionCode = Integer.parseInt(version);
7852 } catch (NumberFormatException e) {
7853 }
7854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 int pkgFlags = 0;
7857 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007858 PackageSetting ps = new PackageSetting(name,
7859 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007860 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 String timeStampStr = parser.getAttributeValue(null, "ts");
7862 if (timeStampStr != null) {
7863 try {
7864 long timeStamp = Long.parseLong(timeStampStr);
7865 ps.setTimeStamp(timeStamp, timeStampStr);
7866 } catch (NumberFormatException e) {
7867 }
7868 }
7869 String idStr = parser.getAttributeValue(null, "userId");
7870 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
7871 if(ps.userId <= 0) {
7872 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7873 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
7874 }
7875 int outerDepth = parser.getDepth();
7876 int type;
7877 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7878 && (type != XmlPullParser.END_TAG
7879 || parser.getDepth() > outerDepth)) {
7880 if (type == XmlPullParser.END_TAG
7881 || type == XmlPullParser.TEXT) {
7882 continue;
7883 }
7884
7885 String tagName = parser.getName();
7886 if (tagName.equals("perms")) {
7887 readGrantedPermissionsLP(parser,
7888 ps.grantedPermissions);
7889 } else {
7890 reportSettingsProblem(Log.WARN,
7891 "Unknown element under <updated-package>: "
7892 + parser.getName());
7893 XmlUtils.skipCurrentTag(parser);
7894 }
7895 }
7896 mDisabledSysPackages.put(name, ps);
7897 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 private void readPackageLP(XmlPullParser parser)
7900 throws XmlPullParserException, IOException {
7901 String name = null;
7902 String idStr = null;
7903 String sharedIdStr = null;
7904 String codePathStr = null;
7905 String resourcePathStr = null;
7906 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007907 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007908 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 int pkgFlags = 0;
7910 String timeStampStr;
7911 long timeStamp = 0;
7912 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007913 String version = null;
7914 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 try {
7916 name = parser.getAttributeValue(null, "name");
7917 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007918 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7920 codePathStr = parser.getAttributeValue(null, "codePath");
7921 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007922 version = parser.getAttributeValue(null, "version");
7923 if (version != null) {
7924 try {
7925 versionCode = Integer.parseInt(version);
7926 } catch (NumberFormatException e) {
7927 }
7928 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007929 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007930
7931 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007932 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007933 try {
7934 pkgFlags = Integer.parseInt(systemStr);
7935 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 }
7937 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007938 // For backward compatibility
7939 systemStr = parser.getAttributeValue(null, "system");
7940 if (systemStr != null) {
7941 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
7942 } else {
7943 // Old settings that don't specify system... just treat
7944 // them as system, good enough.
7945 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007947 }
7948 timeStampStr = parser.getAttributeValue(null, "ts");
7949 if (timeStampStr != null) {
7950 try {
7951 timeStamp = Long.parseLong(timeStampStr);
7952 } catch (NumberFormatException e) {
7953 }
7954 }
7955 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7956 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7957 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7958 if (resourcePathStr == null) {
7959 resourcePathStr = codePathStr;
7960 }
7961 if (name == null) {
7962 reportSettingsProblem(Log.WARN,
7963 "Error in package manager settings: <package> has no name at "
7964 + parser.getPositionDescription());
7965 } else if (codePathStr == null) {
7966 reportSettingsProblem(Log.WARN,
7967 "Error in package manager settings: <package> has no codePath at "
7968 + parser.getPositionDescription());
7969 } else if (userId > 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007970 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007971 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7973 + ": userId=" + userId + " pkg=" + packageSetting);
7974 if (packageSetting == null) {
7975 reportSettingsProblem(Log.ERROR,
7976 "Failure adding uid " + userId
7977 + " while parsing settings at "
7978 + parser.getPositionDescription());
7979 } else {
7980 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7981 }
7982 } else if (sharedIdStr != null) {
7983 userId = sharedIdStr != null
7984 ? Integer.parseInt(sharedIdStr) : 0;
7985 if (userId > 0) {
7986 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007987 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007988 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7989 mPendingPackages.add((PendingPackage) packageSetting);
7990 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7991 + ": sharedUserId=" + userId + " pkg="
7992 + packageSetting);
7993 } else {
7994 reportSettingsProblem(Log.WARN,
7995 "Error in package manager settings: package "
7996 + name + " has bad sharedId " + sharedIdStr
7997 + " at " + parser.getPositionDescription());
7998 }
7999 } else {
8000 reportSettingsProblem(Log.WARN,
8001 "Error in package manager settings: package "
8002 + name + " has bad userId " + idStr + " at "
8003 + parser.getPositionDescription());
8004 }
8005 } catch (NumberFormatException e) {
8006 reportSettingsProblem(Log.WARN,
8007 "Error in package manager settings: package "
8008 + name + " has bad userId " + idStr + " at "
8009 + parser.getPositionDescription());
8010 }
8011 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008012 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008013 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 final String enabledStr = parser.getAttributeValue(null, "enabled");
8015 if (enabledStr != null) {
8016 if (enabledStr.equalsIgnoreCase("true")) {
8017 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8018 } else if (enabledStr.equalsIgnoreCase("false")) {
8019 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8020 } else if (enabledStr.equalsIgnoreCase("default")) {
8021 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8022 } else {
8023 reportSettingsProblem(Log.WARN,
8024 "Error in package manager settings: package "
8025 + name + " has bad enabled value: " + idStr
8026 + " at " + parser.getPositionDescription());
8027 }
8028 } else {
8029 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8030 }
8031 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8032 if (installStatusStr != null) {
8033 if (installStatusStr.equalsIgnoreCase("false")) {
8034 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8035 } else {
8036 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8037 }
8038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 int outerDepth = parser.getDepth();
8041 int type;
8042 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8043 && (type != XmlPullParser.END_TAG
8044 || parser.getDepth() > outerDepth)) {
8045 if (type == XmlPullParser.END_TAG
8046 || type == XmlPullParser.TEXT) {
8047 continue;
8048 }
8049
8050 String tagName = parser.getName();
8051 if (tagName.equals("disabled-components")) {
8052 readDisabledComponentsLP(packageSetting, parser);
8053 } else if (tagName.equals("enabled-components")) {
8054 readEnabledComponentsLP(packageSetting, parser);
8055 } else if (tagName.equals("sigs")) {
8056 packageSetting.signatures.readXml(parser, mPastSignatures);
8057 } else if (tagName.equals("perms")) {
8058 readGrantedPermissionsLP(parser,
8059 packageSetting.loadedPermissions);
8060 packageSetting.permissionsFixed = true;
8061 } else {
8062 reportSettingsProblem(Log.WARN,
8063 "Unknown element under <package>: "
8064 + parser.getName());
8065 XmlUtils.skipCurrentTag(parser);
8066 }
8067 }
8068 } else {
8069 XmlUtils.skipCurrentTag(parser);
8070 }
8071 }
8072
8073 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8074 XmlPullParser parser)
8075 throws IOException, XmlPullParserException {
8076 int outerDepth = parser.getDepth();
8077 int type;
8078 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8079 && (type != XmlPullParser.END_TAG
8080 || parser.getDepth() > outerDepth)) {
8081 if (type == XmlPullParser.END_TAG
8082 || type == XmlPullParser.TEXT) {
8083 continue;
8084 }
8085
8086 String tagName = parser.getName();
8087 if (tagName.equals("item")) {
8088 String name = parser.getAttributeValue(null, "name");
8089 if (name != null) {
8090 packageSetting.disabledComponents.add(name.intern());
8091 } else {
8092 reportSettingsProblem(Log.WARN,
8093 "Error in package manager settings: <disabled-components> has"
8094 + " no name at " + parser.getPositionDescription());
8095 }
8096 } else {
8097 reportSettingsProblem(Log.WARN,
8098 "Unknown element under <disabled-components>: "
8099 + parser.getName());
8100 }
8101 XmlUtils.skipCurrentTag(parser);
8102 }
8103 }
8104
8105 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8106 XmlPullParser parser)
8107 throws IOException, XmlPullParserException {
8108 int outerDepth = parser.getDepth();
8109 int type;
8110 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8111 && (type != XmlPullParser.END_TAG
8112 || parser.getDepth() > outerDepth)) {
8113 if (type == XmlPullParser.END_TAG
8114 || type == XmlPullParser.TEXT) {
8115 continue;
8116 }
8117
8118 String tagName = parser.getName();
8119 if (tagName.equals("item")) {
8120 String name = parser.getAttributeValue(null, "name");
8121 if (name != null) {
8122 packageSetting.enabledComponents.add(name.intern());
8123 } else {
8124 reportSettingsProblem(Log.WARN,
8125 "Error in package manager settings: <enabled-components> has"
8126 + " no name at " + parser.getPositionDescription());
8127 }
8128 } else {
8129 reportSettingsProblem(Log.WARN,
8130 "Unknown element under <enabled-components>: "
8131 + parser.getName());
8132 }
8133 XmlUtils.skipCurrentTag(parser);
8134 }
8135 }
8136
8137 private void readSharedUserLP(XmlPullParser parser)
8138 throws XmlPullParserException, IOException {
8139 String name = null;
8140 String idStr = null;
8141 int pkgFlags = 0;
8142 SharedUserSetting su = null;
8143 try {
8144 name = parser.getAttributeValue(null, "name");
8145 idStr = parser.getAttributeValue(null, "userId");
8146 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8147 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8148 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8149 }
8150 if (name == null) {
8151 reportSettingsProblem(Log.WARN,
8152 "Error in package manager settings: <shared-user> has no name at "
8153 + parser.getPositionDescription());
8154 } else if (userId == 0) {
8155 reportSettingsProblem(Log.WARN,
8156 "Error in package manager settings: shared-user "
8157 + name + " has bad userId " + idStr + " at "
8158 + parser.getPositionDescription());
8159 } else {
8160 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8161 reportSettingsProblem(Log.ERROR,
8162 "Occurred while parsing settings at "
8163 + parser.getPositionDescription());
8164 }
8165 }
8166 } catch (NumberFormatException e) {
8167 reportSettingsProblem(Log.WARN,
8168 "Error in package manager settings: package "
8169 + name + " has bad userId " + idStr + " at "
8170 + parser.getPositionDescription());
8171 };
8172
8173 if (su != null) {
8174 int outerDepth = parser.getDepth();
8175 int type;
8176 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8177 && (type != XmlPullParser.END_TAG
8178 || parser.getDepth() > outerDepth)) {
8179 if (type == XmlPullParser.END_TAG
8180 || type == XmlPullParser.TEXT) {
8181 continue;
8182 }
8183
8184 String tagName = parser.getName();
8185 if (tagName.equals("sigs")) {
8186 su.signatures.readXml(parser, mPastSignatures);
8187 } else if (tagName.equals("perms")) {
8188 readGrantedPermissionsLP(parser, su.loadedPermissions);
8189 } else {
8190 reportSettingsProblem(Log.WARN,
8191 "Unknown element under <shared-user>: "
8192 + parser.getName());
8193 XmlUtils.skipCurrentTag(parser);
8194 }
8195 }
8196
8197 } else {
8198 XmlUtils.skipCurrentTag(parser);
8199 }
8200 }
8201
8202 private void readGrantedPermissionsLP(XmlPullParser parser,
8203 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8204 int outerDepth = parser.getDepth();
8205 int type;
8206 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8207 && (type != XmlPullParser.END_TAG
8208 || parser.getDepth() > outerDepth)) {
8209 if (type == XmlPullParser.END_TAG
8210 || type == XmlPullParser.TEXT) {
8211 continue;
8212 }
8213
8214 String tagName = parser.getName();
8215 if (tagName.equals("item")) {
8216 String name = parser.getAttributeValue(null, "name");
8217 if (name != null) {
8218 outPerms.add(name.intern());
8219 } else {
8220 reportSettingsProblem(Log.WARN,
8221 "Error in package manager settings: <perms> has"
8222 + " no name at " + parser.getPositionDescription());
8223 }
8224 } else {
8225 reportSettingsProblem(Log.WARN,
8226 "Unknown element under <perms>: "
8227 + parser.getName());
8228 }
8229 XmlUtils.skipCurrentTag(parser);
8230 }
8231 }
8232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008233 private void readPreferredActivitiesLP(XmlPullParser parser)
8234 throws XmlPullParserException, IOException {
8235 int outerDepth = parser.getDepth();
8236 int type;
8237 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8238 && (type != XmlPullParser.END_TAG
8239 || parser.getDepth() > outerDepth)) {
8240 if (type == XmlPullParser.END_TAG
8241 || type == XmlPullParser.TEXT) {
8242 continue;
8243 }
8244
8245 String tagName = parser.getName();
8246 if (tagName.equals("item")) {
8247 PreferredActivity pa = new PreferredActivity(parser);
8248 if (pa.mParseError == null) {
8249 mPreferredActivities.addFilter(pa);
8250 } else {
8251 reportSettingsProblem(Log.WARN,
8252 "Error in package manager settings: <preferred-activity> "
8253 + pa.mParseError + " at "
8254 + parser.getPositionDescription());
8255 }
8256 } else {
8257 reportSettingsProblem(Log.WARN,
8258 "Unknown element under <preferred-activities>: "
8259 + parser.getName());
8260 XmlUtils.skipCurrentTag(parser);
8261 }
8262 }
8263 }
8264
8265 // Returns -1 if we could not find an available UserId to assign
8266 private int newUserIdLP(Object obj) {
8267 // Let's be stupidly inefficient for now...
8268 final int N = mUserIds.size();
8269 for (int i=0; i<N; i++) {
8270 if (mUserIds.get(i) == null) {
8271 mUserIds.set(i, obj);
8272 return FIRST_APPLICATION_UID + i;
8273 }
8274 }
8275
8276 // None left?
8277 if (N >= MAX_APPLICATION_UIDS) {
8278 return -1;
8279 }
8280
8281 mUserIds.add(obj);
8282 return FIRST_APPLICATION_UID + N;
8283 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008285 public PackageSetting getDisabledSystemPkg(String name) {
8286 synchronized(mPackages) {
8287 PackageSetting ps = mDisabledSysPackages.get(name);
8288 return ps;
8289 }
8290 }
8291
8292 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8293 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8294 if (Config.LOGV) {
8295 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8296 + " componentName = " + componentInfo.name);
8297 Log.v(TAG, "enabledComponents: "
8298 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8299 Log.v(TAG, "disabledComponents: "
8300 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8301 }
8302 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8303 || ((componentInfo.enabled
8304 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8305 || (componentInfo.applicationInfo.enabled
8306 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8307 && !packageSettings.disabledComponents.contains(componentInfo.name))
8308 || packageSettings.enabledComponents.contains(componentInfo.name));
8309 }
8310 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008311
8312 // ------- apps on sdcard specific code -------
8313 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008314 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008315 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008316 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008317 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008318
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008319
8320 static MountService getMountService() {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008321 return (MountService) ServiceManager.getService("mount");
8322 }
8323
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008324 private String getEncryptKey() {
8325 try {
8326 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8327 if (sdEncKey == null) {
8328 sdEncKey = SystemKeyStore.getInstance().
8329 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8330 if (sdEncKey == null) {
8331 Log.e(TAG, "Failed to create encryption keys");
8332 return null;
8333 }
8334 }
8335 return sdEncKey;
8336 } catch (NoSuchAlgorithmException nsae) {
8337 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8338 return null;
8339 }
8340 }
8341
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008342 private String createSdDir(File tmpPackageFile, String pkgName) {
8343 // Create mount point via MountService
8344 MountService mountService = getMountService();
8345 long len = tmpPackageFile.length();
8346 int mbLen = (int) (len/(1024*1024));
8347 if ((len - (mbLen * 1024 * 1024)) > 0) {
8348 mbLen++;
8349 }
8350 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
8351 String cachePath = null;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008352 String sdEncKey;
8353 try {
8354 sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8355 if (sdEncKey == null) {
8356 sdEncKey = SystemKeyStore.getInstance().
8357 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8358 if (sdEncKey == null) {
8359 Log.e(TAG, "Failed to create encryption keys for package: " + pkgName + ".");
8360 return null;
8361 }
8362 }
8363 } catch (NoSuchAlgorithmException nsae) {
8364 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8365 return null;
8366 }
San Mehatbe16cb12010-01-29 05:35:35 -08008367
8368 int rc = mountService.createSecureContainer(
8369 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
San Mehatb1043402010-02-05 08:26:50 -08008370 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008371 Log.e(TAG, String.format("Failed to create container (%d)", rc));
8372
8373 rc = mountService.destroySecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008374 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008375 Log.e(TAG, String.format("Failed to cleanup container (%d)", rc));
8376 return null;
8377 }
8378 rc = mountService.createSecureContainer(
8379 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
San Mehatb1043402010-02-05 08:26:50 -08008380 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008381 Log.e(TAG, String.format("Failed to create container (2nd try) (%d)", rc));
8382 return null;
8383 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008384 }
San Mehatbe16cb12010-01-29 05:35:35 -08008385
8386 cachePath = mountService.getSecureContainerPath(pkgName);
8387 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008388 return cachePath;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008389 }
8390
8391 private String mountSdDir(String pkgName, int ownerUid) {
Oscar Montemayord02546b2010-01-14 16:38:40 -08008392 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8393 if (sdEncKey == null) {
8394 Log.e(TAG, "Failed to retrieve encryption keys to mount package code: " + pkgName + ".");
8395 return null;
8396 }
San Mehatbe16cb12010-01-29 05:35:35 -08008397
8398 int rc = getMountService().mountSecureContainer(pkgName, sdEncKey, ownerUid);
8399
San Mehatb1043402010-02-05 08:26:50 -08008400 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008401 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " rc : " + rc);
8402 return null;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008403 }
San Mehatbe16cb12010-01-29 05:35:35 -08008404
8405 return getMountService().getSecureContainerPath(pkgName);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008406 }
8407
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008408 private boolean unMountSdDir(String pkgName) {
8409 // STOPSHIP unmount directory
San Mehatbe16cb12010-01-29 05:35:35 -08008410 int rc = getMountService().unmountSecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008411 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008412 Log.e(TAG, "Failed to unmount : " + pkgName + " with rc " + rc);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008413 return false;
8414 }
San Mehatbe16cb12010-01-29 05:35:35 -08008415 return true;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008416 }
8417
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008418 private boolean renameSdDir(String oldId, String newId) {
8419 try {
8420 getMountService().renameSecureContainer(oldId, newId);
8421 return true;
8422 } catch (IllegalStateException e) {
8423 Log.i(TAG, "Failed ot rename " + oldId + " to " + newId +
8424 " with exception : " + e);
8425 }
8426 return false;
8427 }
8428
8429 private String getSdDir(String pkgName) {
8430 return getMountService().getSecureContainerPath(pkgName);
8431 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008432
San Mehatbe16cb12010-01-29 05:35:35 -08008433 private boolean finalizeSdDir(String pkgName) {
8434 int rc = getMountService().finalizeSecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008435 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008436 Log.i(TAG, "Failed to finalize container for pkg : " + pkgName);
8437 return false;
8438 }
8439 return true;
8440 }
8441
8442 private boolean destroySdDir(String pkgName) {
8443 int rc = getMountService().destroySecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008444 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008445 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
8446 return false;
8447 }
8448 return true;
8449 }
8450
8451 static String[] getSecureContainerList() {
8452 String[] list = getMountService().getSecureContainerList();
8453 return list.length == 0 ? null : list;
8454 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008455
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008456 static boolean isContainerMounted(String cid) {
8457 // STOPSHIP
8458 // New api from MountService
8459 try {
8460 return (getMountService().getSecureContainerPath(cid) != null);
8461 } catch (IllegalStateException e) {
8462 }
8463 return false;
8464 }
8465
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008466 static String getTempContainerId() {
8467 String prefix = "smdl1tmp";
8468 int tmpIdx = 1;
8469 String list[] = getSecureContainerList();
8470 if (list != null) {
8471 int idx = 0;
8472 int idList[] = new int[MAX_CONTAINERS];
8473 boolean neverFound = true;
8474 for (String name : list) {
8475 // Ignore null entries
8476 if (name == null) {
8477 continue;
8478 }
8479 int sidx = name.indexOf(prefix);
8480 if (sidx == -1) {
8481 // Not a temp file. just ignore
8482 continue;
8483 }
8484 String subStr = name.substring(sidx + prefix.length());
8485 idList[idx] = -1;
8486 if (subStr != null) {
8487 try {
8488 int cid = Integer.parseInt(subStr);
8489 idList[idx++] = cid;
8490 neverFound = false;
8491 } catch (NumberFormatException e) {
8492 }
8493 }
8494 }
8495 if (!neverFound) {
8496 // Sort idList
8497 Arrays.sort(idList);
8498 for (int j = 1; j <= idList.length; j++) {
8499 if (idList[j-1] != j) {
8500 tmpIdx = j;
8501 break;
8502 }
8503 }
8504 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008505 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008506 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008507 }
8508
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008509 public void updateExternalMediaStatus(final boolean mediaStatus) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008510 synchronized (mPackages) {
8511 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8512 mediaStatus+", mMediaMounted=" + mMediaMounted);
8513 if (mediaStatus == mMediaMounted) {
8514 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008515 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008516 mMediaMounted = mediaStatus;
8517 // Queue up an async operation since the package installation may take a little while.
8518 mHandler.post(new Runnable() {
8519 public void run() {
8520 mHandler.removeCallbacks(this);
8521 updateExternalMediaStatusInner(mediaStatus);
8522 }
8523 });
8524 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008525 }
8526
8527 void updateExternalMediaStatusInner(boolean mediaStatus) {
8528 final String list[] = getSecureContainerList();
8529 if (list == null || list.length == 0) {
8530 return;
8531 }
8532 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8533 int uidList[] = new int[list.length];
8534 int num = 0;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008535 synchronized (mPackages) {
8536 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8537 for (String cid : list) {
8538 SdInstallArgs args = new SdInstallArgs(cid);
8539 String removeEntry = null;
8540 for (String app : appList) {
8541 if (args.matchContainer(app)) {
8542 removeEntry = app;
8543 break;
8544 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008545 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008546 if (removeEntry == null) {
8547 // No matching app on device. Skip entry or may be cleanup?
8548 // Ignore default package
8549 continue;
8550 }
8551 appList.remove(removeEntry);
8552 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8553 processCids.put(args, ps.codePathString);
8554 int uid = ps.userId;
8555 if (uid != -1) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008556 uidList[num++] = uid;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008557 }
8558 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008559 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008560 int uidArr[] = null;
8561 if (num > 0) {
8562 // Sort uid list
8563 Arrays.sort(uidList, 0, num);
8564 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008565 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008566 uidArr[0] = uidList[0];
8567 int di = 0;
8568 for (int i = 1; i < num; i++) {
8569 if (uidList[i-1] != uidList[i]) {
8570 uidArr[di++] = uidList[i];
8571 }
8572 }
8573 if (true) {
8574 for (int j = 0; j < num; j++) {
8575 Log.i(TAG, "uidArr[" + j + "]=" + uidArr[j]);
8576 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008577 }
8578 }
8579 if (mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008580 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008581 loadMediaPackages(processCids, uidArr);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008582 startCleaningPackages();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008583 } else {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008584 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008585 unloadMediaPackages(processCids, uidArr);
8586 }
8587 }
8588
8589 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8590 ArrayList<String> pkgList, int uidArr[]) {
8591 int size = pkgList.size();
8592 if (size > 0) {
8593 // Send broadcasts here
8594 Bundle extras = new Bundle();
8595 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8596 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008597 if (uidArr != null) {
8598 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8599 }
8600 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8601 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008602 sendPackageBroadcast(action, null, extras);
8603 }
8604 }
8605
8606 void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8607 ArrayList<String> pkgList = new ArrayList<String>();
8608 Set<SdInstallArgs> keys = processCids.keySet();
8609 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008610 String codePath = processCids.get(args);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008611 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install pkg : "
8612 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008613 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008614 Log.e(TAG, "Failed to install package: " + codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008615 continue;
8616 }
8617 // Parse package
8618 int parseFlags = PackageParser.PARSE_CHATTY |
8619 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8620 PackageParser pp = new PackageParser(codePath);
8621 pp.setSeparateProcesses(mSeparateProcesses);
8622 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
8623 codePath, mMetrics, parseFlags);
8624 if (pkg == null) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008625 Log.e(TAG, "Trying to install pkg : "
8626 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008627 continue;
8628 }
8629 setApplicationInfoPaths(pkg, codePath, codePath);
8630 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8631 synchronized (mInstallLock) {
8632 // Scan the package
8633 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
8634 synchronized (mPackages) {
8635 // Grant permissions
8636 grantPermissionsLP(pkg, false);
8637 // Persist settings
8638 mSettings.writeLP();
8639 retCode = PackageManager.INSTALL_SUCCEEDED;
8640 pkgList.add(pkg.packageName);
8641 }
8642 } else {
8643 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
8644 }
8645 }
8646 args.doPostInstall(retCode);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008647 }
8648 // Send broadcasts first
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008649 if (pkgList.size() > 0) {
8650 sendResourcesChangedBroadcast(true, pkgList, uidArr);
8651 Runtime.getRuntime().gc();
8652 // If something failed do we clean up here or next install?
8653 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008654 }
8655
8656 void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008657 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008658 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008659 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008660 Set<SdInstallArgs> keys = processCids.keySet();
8661 for (SdInstallArgs args : keys) {
8662 String cid = args.cid;
8663 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008664 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008665 // Delete package internally
8666 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8667 synchronized (mInstallLock) {
8668 boolean res = deletePackageLI(pkgName, false,
8669 PackageManager.DONT_DELETE_DATA, outInfo);
8670 if (res) {
8671 pkgList.add(pkgName);
8672 } else {
8673 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008674 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008675 }
8676 }
8677 }
8678 // Send broadcasts
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008679 if (pkgList.size() > 0) {
8680 sendResourcesChangedBroadcast(false, pkgList, uidArr);
8681 Runtime.getRuntime().gc();
8682 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008683 // Do clean up. Just unmount
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008684 for (SdInstallArgs args : failedList) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008685 synchronized (mInstallLock) {
8686 args.doPostDeleteLI(false);
8687 }
8688 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690}