blob: 252f2a66a0335f6ad9d55501daa6bf92431238e8 [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;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080023import com.android.internal.content.PackageHelper;
David 'Digit' Turneradd13762010-02-03 17:34:58 -080024import com.android.server.JournaledFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.content.Context;
34import android.content.Intent;
35import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070036import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080037import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070038import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.pm.ActivityInfo;
40import android.content.pm.ApplicationInfo;
41import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070042import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.IPackageDataObserver;
44import android.content.pm.IPackageDeleteObserver;
45import android.content.pm.IPackageInstallObserver;
46import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080047import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.content.pm.IPackageStatsObserver;
49import android.content.pm.InstrumentationInfo;
50import android.content.pm.PackageInfo;
51import android.content.pm.PackageManager;
52import android.content.pm.PackageStats;
53import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
54import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
55import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
56import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
57import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
58import android.content.pm.PackageParser;
59import android.content.pm.PermissionInfo;
60import android.content.pm.PermissionGroupInfo;
61import android.content.pm.ProviderInfo;
62import android.content.pm.ResolveInfo;
63import android.content.pm.ServiceInfo;
64import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.net.Uri;
66import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070067import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080069import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080071import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070072import android.os.Looper;
73import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.os.Parcel;
75import android.os.RemoteException;
76import android.os.Environment;
77import android.os.FileObserver;
78import android.os.FileUtils;
79import android.os.Handler;
San Mehatb1043402010-02-05 08:26:50 -080080import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.ParcelFileDescriptor;
82import android.os.Process;
83import android.os.ServiceManager;
84import android.os.SystemClock;
85import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080086import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.util.*;
88import android.view.Display;
89import android.view.WindowManager;
90
91import java.io.File;
92import java.io.FileDescriptor;
93import java.io.FileInputStream;
94import java.io.FileNotFoundException;
95import java.io.FileOutputStream;
96import java.io.FileReader;
97import java.io.FilenameFilter;
98import java.io.IOException;
99import java.io.InputStream;
100import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800101import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800102import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.ArrayList;
104import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700105import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.Collections;
107import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800108import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Enumeration;
110import java.util.HashMap;
111import java.util.HashSet;
112import java.util.Iterator;
113import java.util.List;
114import java.util.Map;
115import java.util.Set;
116import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800117import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.zip.ZipFile;
119import java.util.zip.ZipOutputStream;
120
121class PackageManagerService extends IPackageManager.Stub {
122 private static final String TAG = "PackageManager";
123 private static final boolean DEBUG_SETTINGS = false;
124 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800125 private static final boolean DEBUG_UPGRADE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126
127 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
128 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400129 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private static final int FIRST_APPLICATION_UID =
131 Process.FIRST_APPLICATION_UID;
132 private static final int MAX_APPLICATION_UIDS = 1000;
133
134 private static final boolean SHOW_INFO = false;
135
136 private static final boolean GET_CERTIFICATES = true;
137
Oscar Montemayora8529f62009-11-18 10:14:20 -0800138 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 private static final int REMOVE_EVENTS =
141 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
142 private static final int ADD_EVENTS =
143 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
144
145 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800146 // Suffix used during package installation when copying/moving
147 // package apks to install directory.
148 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
150 static final int SCAN_MONITOR = 1<<0;
151 static final int SCAN_NO_DEX = 1<<1;
152 static final int SCAN_FORCE_DEX = 1<<2;
153 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800154 static final int SCAN_NEW_INSTALL = 1<<4;
155 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800157 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
158 "com.android.defcontainer",
159 "com.android.defcontainer.DefaultContainerService");
160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
162 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700163 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Dianne Hackborn851a5412009-05-08 12:06:44 -0700165 final int mSdkVersion = Build.VERSION.SDK_INT;
166 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
167 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 final Context mContext;
170 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700171 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 final DisplayMetrics mMetrics;
173 final int mDefParseFlags;
174 final String[] mSeparateProcesses;
175
176 // This is where all application persistent data goes.
177 final File mAppDataDir;
178
Oscar Montemayora8529f62009-11-18 10:14:20 -0800179 // If Encrypted File System feature is enabled, all application persistent data
180 // should go here instead.
181 final File mSecureAppDataDir;
182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 // This is the object monitoring the framework dir.
184 final FileObserver mFrameworkInstallObserver;
185
186 // This is the object monitoring the system app dir.
187 final FileObserver mSystemInstallObserver;
188
189 // This is the object monitoring mAppInstallDir.
190 final FileObserver mAppInstallObserver;
191
192 // This is the object monitoring mDrmAppPrivateInstallDir.
193 final FileObserver mDrmAppInstallObserver;
194
195 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
196 // LOCK HELD. Can be called with mInstallLock held.
197 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 final File mFrameworkDir;
200 final File mSystemAppDir;
201 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700202 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
204 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
205 // apps.
206 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 // Lock for state used when installing and doing other long running
211 // operations. Methods that must be called with this lock held have
212 // the prefix "LI".
213 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 // These are the directories in the 3rd party applications installed dir
216 // that we have currently loaded packages from. Keys are the application's
217 // installed zip file (absolute codePath), and values are Package.
218 final HashMap<String, PackageParser.Package> mAppDirs =
219 new HashMap<String, PackageParser.Package>();
220
221 // Information for the parser to write more useful error messages.
222 File mScanningPath;
223 int mLastScanError;
224
225 final int[] mOutPermissions = new int[3];
226
227 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 // Keys are String (package name), values are Package. This also serves
230 // as the lock for the global state. Methods that must be called with
231 // this lock held have the prefix "LP".
232 final HashMap<String, PackageParser.Package> mPackages =
233 new HashMap<String, PackageParser.Package>();
234
235 final Settings mSettings;
236 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
238 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
239 int[] mGlobalGids;
240
241 // These are the built-in uid -> permission mappings that were read from the
242 // etc/permissions.xml file.
243 final SparseArray<HashSet<String>> mSystemPermissions =
244 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 // These are the built-in shared libraries that were read from the
247 // etc/permissions.xml file.
248 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800249
Dianne Hackborn49237342009-08-27 20:08:01 -0700250 // Temporary for building the final shared libraries for an .apk.
251 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800252
Dianne Hackborn49237342009-08-27 20:08:01 -0700253 // These are the features this devices supports that were read from the
254 // etc/permissions.xml file.
255 final HashMap<String, FeatureInfo> mAvailableFeatures =
256 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 // All available activities, for your resolving pleasure.
259 final ActivityIntentResolver mActivities =
260 new ActivityIntentResolver();
261
262 // All available receivers, for your resolving pleasure.
263 final ActivityIntentResolver mReceivers =
264 new ActivityIntentResolver();
265
266 // All available services, for your resolving pleasure.
267 final ServiceIntentResolver mServices = new ServiceIntentResolver();
268
269 // Keys are String (provider class name), values are Provider.
270 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
271 new HashMap<ComponentName, PackageParser.Provider>();
272
273 // Mapping from provider base names (first directory in content URI codePath)
274 // to the provider information.
275 final HashMap<String, PackageParser.Provider> mProviders =
276 new HashMap<String, PackageParser.Provider>();
277
278 // Mapping from instrumentation class names to info about them.
279 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
280 new HashMap<ComponentName, PackageParser.Instrumentation>();
281
282 // Mapping from permission names to info about them.
283 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
284 new HashMap<String, PackageParser.PermissionGroup>();
285
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800286 // Packages whose data we have transfered into another package, thus
287 // should no longer exist.
288 final HashSet<String> mTransferedPackages = new HashSet<String>();
289
Dianne Hackborn854060af2009-07-09 18:14:31 -0700290 // Broadcast actions that are only available to the system.
291 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 boolean mSystemReady;
294 boolean mSafeMode;
295 boolean mHasSystemUidErrors;
296
297 ApplicationInfo mAndroidApplication;
298 final ActivityInfo mResolveActivity = new ActivityInfo();
299 final ResolveInfo mResolveInfo = new ResolveInfo();
300 ComponentName mResolveComponentName;
301 PackageParser.Package mPlatformPackage;
302
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700303 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800304 final HashMap<String, ArrayList<String>> mPendingBroadcasts
305 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700306 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800307 static final int MCS_BOUND = 3;
308 static final int END_COPY = 4;
309 static final int INIT_COPY = 5;
310 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800311 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800312 static final int FIND_INSTALL_LOC = 8;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700313 // Delay time in millisecs
314 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800315 private ServiceConnection mDefContainerConn = new ServiceConnection() {
316 public void onServiceConnected(ComponentName name, IBinder service) {
317 IMediaContainerService imcs =
318 IMediaContainerService.Stub.asInterface(service);
319 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
320 mHandler.sendMessage(msg);
321 }
322
323 public void onServiceDisconnected(ComponentName name) {
324 }
325 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700326
327 class PackageHandler extends Handler {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800328 final ArrayList<HandlerParams> mPendingInstalls =
329 new ArrayList<HandlerParams>();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800330 // Service Connection to remote media container service to copy
331 // package uri's from external media onto secure containers
332 // or internal storage.
333 private IMediaContainerService mContainerService = null;
334
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700335 PackageHandler(Looper looper) {
336 super(looper);
337 }
338 public void handleMessage(Message msg) {
339 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800340 case INIT_COPY: {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800341 HandlerParams params = (HandlerParams) msg.obj;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800342 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800343 if (mContainerService != null) {
344 // No need to add to pending list. Use remote stub directly
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800345 params.handleStartCopy(mContainerService);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800346 } else {
347 if (mContext.bindService(service, mDefContainerConn,
348 Context.BIND_AUTO_CREATE)) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800349 mPendingInstalls.add(params);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800350 } else {
351 Log.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800352 // Indicate service bind error
353 params.handleServiceError();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800354 }
355 }
356 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800357 }
358 case MCS_BOUND: {
359 // Initialize mContainerService if needed.
360 if (msg.obj != null) {
361 mContainerService = (IMediaContainerService) msg.obj;
362 }
363 if (mPendingInstalls.size() > 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800364 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800365 if (params != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800366 params.handleStartCopy(mContainerService);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800367 }
368 }
369 break;
370 }
371 case MCS_UNBIND : {
372 if (mPendingInstalls.size() == 0) {
373 mContext.unbindService(mDefContainerConn);
374 mContainerService = null;
375 }
376 break;
377 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800379 String packages[];
380 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700381 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700382 int uids[];
383 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800384 if (mPendingBroadcasts == null) {
385 return;
386 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700387 size = mPendingBroadcasts.size();
388 if (size <= 0) {
389 // Nothing to be done. Just return
390 return;
391 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800392 packages = new String[size];
393 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700394 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800395 Iterator<HashMap.Entry<String, ArrayList<String>>>
396 it = mPendingBroadcasts.entrySet().iterator();
397 int i = 0;
398 while (it.hasNext() && i < size) {
399 HashMap.Entry<String, ArrayList<String>> ent = it.next();
400 packages[i] = ent.getKey();
401 components[i] = ent.getValue();
402 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700403 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800404 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700405 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800406 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700407 mPendingBroadcasts.clear();
408 }
409 // Send broadcasts
410 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800411 sendPackageChangedBroadcast(packages[i], true,
412 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700413 }
414 break;
415 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800416 case START_CLEANING_PACKAGE: {
417 String packageName = (String)msg.obj;
418 synchronized (mPackages) {
419 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
420 mSettings.mPackagesToBeCleaned.add(packageName);
421 }
422 }
423 startCleaningPackages();
424 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700425 }
426 }
427 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800428
429 static boolean installOnSd(int flags) {
430 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800431 ((flags & PackageManager.INSTALL_EXTERNAL) == 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800432 return false;
433 }
434 return true;
435 }
436
437 static boolean isFwdLocked(int flags) {
438 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
439 return true;
440 }
441 return false;
442 }
443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 public static final IPackageManager main(Context context, boolean factoryTest) {
445 PackageManagerService m = new PackageManagerService(context, factoryTest);
446 ServiceManager.addService("package", m);
447 return m;
448 }
449
450 static String[] splitString(String str, char sep) {
451 int count = 1;
452 int i = 0;
453 while ((i=str.indexOf(sep, i)) >= 0) {
454 count++;
455 i++;
456 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 String[] res = new String[count];
459 i=0;
460 count = 0;
461 int lastI=0;
462 while ((i=str.indexOf(sep, i)) >= 0) {
463 res[count] = str.substring(lastI, i);
464 count++;
465 i++;
466 lastI = i;
467 }
468 res[count] = str.substring(lastI, str.length());
469 return res;
470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800473 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 if (mSdkVersion <= 0) {
477 Log.w(TAG, "**** ro.build.version.sdk not set!");
478 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 mContext = context;
481 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700482 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 mMetrics = new DisplayMetrics();
484 mSettings = new Settings();
485 mSettings.addSharedUserLP("android.uid.system",
486 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
487 mSettings.addSharedUserLP("android.uid.phone",
488 MULTIPLE_APPLICATION_UIDS
489 ? RADIO_UID : FIRST_APPLICATION_UID,
490 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400491 mSettings.addSharedUserLP("android.uid.log",
492 MULTIPLE_APPLICATION_UIDS
493 ? LOG_UID : FIRST_APPLICATION_UID,
494 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495
496 String separateProcesses = SystemProperties.get("debug.separate_processes");
497 if (separateProcesses != null && separateProcesses.length() > 0) {
498 if ("*".equals(separateProcesses)) {
499 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
500 mSeparateProcesses = null;
501 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
502 } else {
503 mDefParseFlags = 0;
504 mSeparateProcesses = separateProcesses.split(",");
505 Log.w(TAG, "Running with debug.separate_processes: "
506 + separateProcesses);
507 }
508 } else {
509 mDefParseFlags = 0;
510 mSeparateProcesses = null;
511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 Installer installer = new Installer();
514 // Little hacky thing to check if installd is here, to determine
515 // whether we are running on the simulator and thus need to take
516 // care of building the /data file structure ourself.
517 // (apparently the sim now has a working installer)
518 if (installer.ping() && Process.supportsProcesses()) {
519 mInstaller = installer;
520 } else {
521 mInstaller = null;
522 }
523
524 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
525 Display d = wm.getDefaultDisplay();
526 d.getMetrics(mMetrics);
527
528 synchronized (mInstallLock) {
529 synchronized (mPackages) {
530 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 File dataDir = Environment.getDataDirectory();
534 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800535 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
537
538 if (mInstaller == null) {
539 // Make sure these dirs exist, when we are running in
540 // the simulator.
541 // Make a wide-open directory for random misc stuff.
542 File miscDir = new File(dataDir, "misc");
543 miscDir.mkdirs();
544 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800545 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 mDrmAppPrivateInstallDir.mkdirs();
547 }
548
549 readPermissions();
550
551 mRestoredSettings = mSettings.readLP();
552 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800553
554 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800556
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800557 // Set flag to monitor and not change apk file paths when
558 // scanning install directories.
559 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700560 if (mNoDexOpt) {
561 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800562 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700563 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700568 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700571 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 /**
574 * Out of paranoia, ensure that everything in the boot class
575 * path has been dexed.
576 */
577 String bootClassPath = System.getProperty("java.boot.class.path");
578 if (bootClassPath != null) {
579 String[] paths = splitString(bootClassPath, ':');
580 for (int i=0; i<paths.length; i++) {
581 try {
582 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
583 libFiles.add(paths[i]);
584 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700585 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 }
587 } catch (FileNotFoundException e) {
588 Log.w(TAG, "Boot class path not found: " + paths[i]);
589 } catch (IOException e) {
590 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
591 }
592 }
593 } else {
594 Log.w(TAG, "No BOOTCLASSPATH found!");
595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 /**
598 * Also ensure all external libraries have had dexopt run on them.
599 */
600 if (mSharedLibraries.size() > 0) {
601 Iterator<String> libs = mSharedLibraries.values().iterator();
602 while (libs.hasNext()) {
603 String lib = libs.next();
604 try {
605 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
606 libFiles.add(lib);
607 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700608 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 }
610 } catch (FileNotFoundException e) {
611 Log.w(TAG, "Library not found: " + lib);
612 } catch (IOException e) {
613 Log.w(TAG, "Exception reading library: " + lib, e);
614 }
615 }
616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 // Gross hack for now: we know this file doesn't contain any
619 // code, so don't dexopt it to avoid the resulting log spew.
620 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 /**
623 * And there are a number of commands implemented in Java, which
624 * we currently need to do the dexopt on so that they can be
625 * run from a non-root shell.
626 */
627 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700628 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 for (int i=0; i<frameworkFiles.length; i++) {
630 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
631 String path = libPath.getPath();
632 // Skip the file if we alrady did it.
633 if (libFiles.contains(path)) {
634 continue;
635 }
636 // Skip the file if it is not a type we want to dexopt.
637 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
638 continue;
639 }
640 try {
641 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
642 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700643 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 }
645 } catch (FileNotFoundException e) {
646 Log.w(TAG, "Jar not found: " + path);
647 } catch (IOException e) {
648 Log.w(TAG, "Exception reading jar: " + path, e);
649 }
650 }
651 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800652
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700653 if (didDexOpt) {
654 // If we had to do a dexopt of one of the previous
655 // things, then something on the system has changed.
656 // Consider this significant, and wipe away all other
657 // existing dexopt files to ensure we don't leave any
658 // dangling around.
659 String[] files = mDalvikCacheDir.list();
660 if (files != null) {
661 for (int i=0; i<files.length; i++) {
662 String fn = files[i];
663 if (fn.startsWith("data@app@")
664 || fn.startsWith("data@app-private@")) {
665 Log.i(TAG, "Pruning dalvik file: " + fn);
666 (new File(mDalvikCacheDir, fn)).delete();
667 }
668 }
669 }
670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800672
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800673 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 mFrameworkInstallObserver = new AppDirObserver(
675 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
676 mFrameworkInstallObserver.startWatching();
677 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800678 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800679
680 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
682 mSystemInstallObserver = new AppDirObserver(
683 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
684 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800685 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800686
687 if (mInstaller != null) {
688 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
689 mInstaller.moveFiles();
690 }
691
692 // Prune any system packages that no longer exist.
693 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
694 while (psit.hasNext()) {
695 PackageSetting ps = psit.next();
696 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800697 && !mPackages.containsKey(ps.name)
698 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800699 psit.remove();
700 String msg = "System package " + ps.name
701 + " no longer exists; wiping its data";
702 reportSettingsProblem(Log.WARN, msg);
703 if (mInstaller != null) {
704 // XXX how to set useEncryptedFSDir for packages that
705 // are not encrypted?
706 mInstaller.remove(ps.name, true);
707 }
708 }
709 }
710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 mAppInstallDir = new File(dataDir, "app");
712 if (mInstaller == null) {
713 // Make sure these dirs exist, when we are running in
714 // the simulator.
715 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
716 }
717 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800718 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 //clean up list
720 for(int i = 0; i < deletePkgsList.size(); i++) {
721 //clean up here
722 cleanupInstallFailedPackage(deletePkgsList.get(i));
723 }
724 //delete tmp files
725 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800726
727 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 SystemClock.uptimeMillis());
729 mAppInstallObserver = new AppDirObserver(
730 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
731 mAppInstallObserver.startWatching();
732 scanDirLI(mAppInstallDir, 0, scanMode);
733
734 mDrmAppInstallObserver = new AppDirObserver(
735 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
736 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800737 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800739 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 SystemClock.uptimeMillis());
741 Log.i(TAG, "Time to scan packages: "
742 + ((SystemClock.uptimeMillis()-startTime)/1000f)
743 + " seconds");
744
745 updatePermissionsLP();
746
747 mSettings.writeLP();
748
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800749 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 // Now after opening every single application zip, make sure they
753 // are all flushed. Not really needed, but keeps things nice and
754 // tidy.
755 Runtime.getRuntime().gc();
756 } // synchronized (mPackages)
757 } // synchronized (mInstallLock)
758 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 @Override
761 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
762 throws RemoteException {
763 try {
764 return super.onTransact(code, data, reply, flags);
765 } catch (RuntimeException e) {
766 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
767 Log.e(TAG, "Package Manager Crash", e);
768 }
769 throw e;
770 }
771 }
772
Dianne Hackborne6620b22010-01-22 14:46:21 -0800773 void cleanupInstallFailedPackage(PackageSetting ps) {
774 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800776 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
777 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 if (retCode < 0) {
779 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800780 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 }
782 } else {
783 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800784 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 File dataDir = new File(pkg.applicationInfo.dataDir);
786 dataDir.delete();
787 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800788 if (ps.codePath != null) {
789 if (!ps.codePath.delete()) {
790 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
791 }
792 }
793 if (ps.resourcePath != null) {
794 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
795 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
796 }
797 }
798 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 }
800
801 void readPermissions() {
802 // Read permissions from .../etc/permission directory.
803 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
804 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
805 Log.w(TAG, "No directory " + libraryDir + ", skipping");
806 return;
807 }
808 if (!libraryDir.canRead()) {
809 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
810 return;
811 }
812
813 // Iterate over the files in the directory and scan .xml files
814 for (File f : libraryDir.listFiles()) {
815 // We'll read platform.xml last
816 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
817 continue;
818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 if (!f.getPath().endsWith(".xml")) {
821 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
822 continue;
823 }
824 if (!f.canRead()) {
825 Log.w(TAG, "Permissions library file " + f + " cannot be read");
826 continue;
827 }
828
829 readPermissionsFromXml(f);
830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
833 final File permFile = new File(Environment.getRootDirectory(),
834 "etc/permissions/platform.xml");
835 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800836
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700837 StringBuilder sb = new StringBuilder(128);
838 sb.append("Libs:");
839 Iterator<String> it = mSharedLibraries.keySet().iterator();
840 while (it.hasNext()) {
841 sb.append(' ');
842 String name = it.next();
843 sb.append(name);
844 sb.append(':');
845 sb.append(mSharedLibraries.get(name));
846 }
847 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800848
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700849 sb.setLength(0);
850 sb.append("Features:");
851 it = mAvailableFeatures.keySet().iterator();
852 while (it.hasNext()) {
853 sb.append(' ');
854 sb.append(it.next());
855 }
856 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800858
859 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 FileReader permReader = null;
861 try {
862 permReader = new FileReader(permFile);
863 } catch (FileNotFoundException e) {
864 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
865 return;
866 }
867
868 try {
869 XmlPullParser parser = Xml.newPullParser();
870 parser.setInput(permReader);
871
872 XmlUtils.beginDocument(parser, "permissions");
873
874 while (true) {
875 XmlUtils.nextElement(parser);
876 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
877 break;
878 }
879
880 String name = parser.getName();
881 if ("group".equals(name)) {
882 String gidStr = parser.getAttributeValue(null, "gid");
883 if (gidStr != null) {
884 int gid = Integer.parseInt(gidStr);
885 mGlobalGids = appendInt(mGlobalGids, gid);
886 } else {
887 Log.w(TAG, "<group> without gid at "
888 + parser.getPositionDescription());
889 }
890
891 XmlUtils.skipCurrentTag(parser);
892 continue;
893 } else if ("permission".equals(name)) {
894 String perm = parser.getAttributeValue(null, "name");
895 if (perm == null) {
896 Log.w(TAG, "<permission> without name at "
897 + parser.getPositionDescription());
898 XmlUtils.skipCurrentTag(parser);
899 continue;
900 }
901 perm = perm.intern();
902 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 } else if ("assign-permission".equals(name)) {
905 String perm = parser.getAttributeValue(null, "name");
906 if (perm == null) {
907 Log.w(TAG, "<assign-permission> without name at "
908 + parser.getPositionDescription());
909 XmlUtils.skipCurrentTag(parser);
910 continue;
911 }
912 String uidStr = parser.getAttributeValue(null, "uid");
913 if (uidStr == null) {
914 Log.w(TAG, "<assign-permission> without uid at "
915 + parser.getPositionDescription());
916 XmlUtils.skipCurrentTag(parser);
917 continue;
918 }
919 int uid = Process.getUidForName(uidStr);
920 if (uid < 0) {
921 Log.w(TAG, "<assign-permission> with unknown uid \""
922 + uidStr + "\" at "
923 + parser.getPositionDescription());
924 XmlUtils.skipCurrentTag(parser);
925 continue;
926 }
927 perm = perm.intern();
928 HashSet<String> perms = mSystemPermissions.get(uid);
929 if (perms == null) {
930 perms = new HashSet<String>();
931 mSystemPermissions.put(uid, perms);
932 }
933 perms.add(perm);
934 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 } else if ("library".equals(name)) {
937 String lname = parser.getAttributeValue(null, "name");
938 String lfile = parser.getAttributeValue(null, "file");
939 if (lname == null) {
940 Log.w(TAG, "<library> without name at "
941 + parser.getPositionDescription());
942 } else if (lfile == null) {
943 Log.w(TAG, "<library> without file at "
944 + parser.getPositionDescription());
945 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700946 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700947 mSharedLibraries.put(lname, lfile);
948 }
949 XmlUtils.skipCurrentTag(parser);
950 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800951
Dianne Hackborn49237342009-08-27 20:08:01 -0700952 } else if ("feature".equals(name)) {
953 String fname = parser.getAttributeValue(null, "name");
954 if (fname == null) {
955 Log.w(TAG, "<feature> without name at "
956 + parser.getPositionDescription());
957 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700958 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700959 FeatureInfo fi = new FeatureInfo();
960 fi.name = fname;
961 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
963 XmlUtils.skipCurrentTag(parser);
964 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 } else {
967 XmlUtils.skipCurrentTag(parser);
968 continue;
969 }
970
971 }
972 } catch (XmlPullParserException e) {
973 Log.w(TAG, "Got execption parsing permissions.", e);
974 } catch (IOException e) {
975 Log.w(TAG, "Got execption parsing permissions.", e);
976 }
977 }
978
979 void readPermission(XmlPullParser parser, String name)
980 throws IOException, XmlPullParserException {
981
982 name = name.intern();
983
984 BasePermission bp = mSettings.mPermissions.get(name);
985 if (bp == null) {
986 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
987 mSettings.mPermissions.put(name, bp);
988 }
989 int outerDepth = parser.getDepth();
990 int type;
991 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
992 && (type != XmlPullParser.END_TAG
993 || parser.getDepth() > outerDepth)) {
994 if (type == XmlPullParser.END_TAG
995 || type == XmlPullParser.TEXT) {
996 continue;
997 }
998
999 String tagName = parser.getName();
1000 if ("group".equals(tagName)) {
1001 String gidStr = parser.getAttributeValue(null, "gid");
1002 if (gidStr != null) {
1003 int gid = Process.getGidForName(gidStr);
1004 bp.gids = appendInt(bp.gids, gid);
1005 } else {
1006 Log.w(TAG, "<group> without gid at "
1007 + parser.getPositionDescription());
1008 }
1009 }
1010 XmlUtils.skipCurrentTag(parser);
1011 }
1012 }
1013
1014 static int[] appendInt(int[] cur, int val) {
1015 if (cur == null) {
1016 return new int[] { val };
1017 }
1018 final int N = cur.length;
1019 for (int i=0; i<N; i++) {
1020 if (cur[i] == val) {
1021 return cur;
1022 }
1023 }
1024 int[] ret = new int[N+1];
1025 System.arraycopy(cur, 0, ret, 0, N);
1026 ret[N] = val;
1027 return ret;
1028 }
1029
1030 static int[] appendInts(int[] cur, int[] add) {
1031 if (add == null) return cur;
1032 if (cur == null) return add;
1033 final int N = add.length;
1034 for (int i=0; i<N; i++) {
1035 cur = appendInt(cur, add[i]);
1036 }
1037 return cur;
1038 }
1039
1040 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001041 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1042 // The package has been uninstalled but has retained data and resources.
1043 return PackageParser.generatePackageInfo(p, null, flags);
1044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 final PackageSetting ps = (PackageSetting)p.mExtras;
1046 if (ps == null) {
1047 return null;
1048 }
1049 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1050 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1051 }
1052
1053 public PackageInfo getPackageInfo(String packageName, int flags) {
1054 synchronized (mPackages) {
1055 PackageParser.Package p = mPackages.get(packageName);
1056 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001057 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 + ": " + p);
1059 if (p != null) {
1060 return generatePackageInfo(p, flags);
1061 }
1062 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1063 return generatePackageInfoFromSettingsLP(packageName, flags);
1064 }
1065 }
1066 return null;
1067 }
1068
Dianne Hackborn47096932010-02-11 15:57:09 -08001069 public String[] currentToCanonicalPackageNames(String[] names) {
1070 String[] out = new String[names.length];
1071 synchronized (mPackages) {
1072 for (int i=names.length-1; i>=0; i--) {
1073 PackageSetting ps = mSettings.mPackages.get(names[i]);
1074 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1075 }
1076 }
1077 return out;
1078 }
1079
1080 public String[] canonicalToCurrentPackageNames(String[] names) {
1081 String[] out = new String[names.length];
1082 synchronized (mPackages) {
1083 for (int i=names.length-1; i>=0; i--) {
1084 String cur = mSettings.mRenamedPackages.get(names[i]);
1085 out[i] = cur != null ? cur : names[i];
1086 }
1087 }
1088 return out;
1089 }
1090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 public int getPackageUid(String packageName) {
1092 synchronized (mPackages) {
1093 PackageParser.Package p = mPackages.get(packageName);
1094 if(p != null) {
1095 return p.applicationInfo.uid;
1096 }
1097 PackageSetting ps = mSettings.mPackages.get(packageName);
1098 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1099 return -1;
1100 }
1101 p = ps.pkg;
1102 return p != null ? p.applicationInfo.uid : -1;
1103 }
1104 }
1105
1106 public int[] getPackageGids(String packageName) {
1107 synchronized (mPackages) {
1108 PackageParser.Package p = mPackages.get(packageName);
1109 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001110 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 + ": " + p);
1112 if (p != null) {
1113 final PackageSetting ps = (PackageSetting)p.mExtras;
1114 final SharedUserSetting suid = ps.sharedUser;
1115 return suid != null ? suid.gids : ps.gids;
1116 }
1117 }
1118 // stupid thing to indicate an error.
1119 return new int[0];
1120 }
1121
1122 public PermissionInfo getPermissionInfo(String name, int flags) {
1123 synchronized (mPackages) {
1124 final BasePermission p = mSettings.mPermissions.get(name);
1125 if (p != null && p.perm != null) {
1126 return PackageParser.generatePermissionInfo(p.perm, flags);
1127 }
1128 return null;
1129 }
1130 }
1131
1132 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1133 synchronized (mPackages) {
1134 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1135 for (BasePermission p : mSettings.mPermissions.values()) {
1136 if (group == null) {
1137 if (p.perm.info.group == null) {
1138 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1139 }
1140 } else {
1141 if (group.equals(p.perm.info.group)) {
1142 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1143 }
1144 }
1145 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 if (out.size() > 0) {
1148 return out;
1149 }
1150 return mPermissionGroups.containsKey(group) ? out : null;
1151 }
1152 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1155 synchronized (mPackages) {
1156 return PackageParser.generatePermissionGroupInfo(
1157 mPermissionGroups.get(name), flags);
1158 }
1159 }
1160
1161 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1162 synchronized (mPackages) {
1163 final int N = mPermissionGroups.size();
1164 ArrayList<PermissionGroupInfo> out
1165 = new ArrayList<PermissionGroupInfo>(N);
1166 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1167 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1168 }
1169 return out;
1170 }
1171 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1174 PackageSetting ps = mSettings.mPackages.get(packageName);
1175 if(ps != null) {
1176 if(ps.pkg == null) {
1177 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1178 if(pInfo != null) {
1179 return pInfo.applicationInfo;
1180 }
1181 return null;
1182 }
1183 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1184 }
1185 return null;
1186 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1189 PackageSetting ps = mSettings.mPackages.get(packageName);
1190 if(ps != null) {
1191 if(ps.pkg == null) {
1192 ps.pkg = new PackageParser.Package(packageName);
1193 ps.pkg.applicationInfo.packageName = packageName;
1194 }
1195 return generatePackageInfo(ps.pkg, flags);
1196 }
1197 return null;
1198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1201 synchronized (mPackages) {
1202 PackageParser.Package p = mPackages.get(packageName);
1203 if (Config.LOGV) Log.v(
1204 TAG, "getApplicationInfo " + packageName
1205 + ": " + p);
1206 if (p != null) {
1207 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001208 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
1210 if ("android".equals(packageName)||"system".equals(packageName)) {
1211 return mAndroidApplication;
1212 }
1213 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1214 return generateApplicationInfoFromSettingsLP(packageName, flags);
1215 }
1216 }
1217 return null;
1218 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001219
1220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1222 mContext.enforceCallingOrSelfPermission(
1223 android.Manifest.permission.CLEAR_APP_CACHE, null);
1224 // Queue up an async operation since clearing cache may take a little while.
1225 mHandler.post(new Runnable() {
1226 public void run() {
1227 mHandler.removeCallbacks(this);
1228 int retCode = -1;
1229 if (mInstaller != null) {
1230 retCode = mInstaller.freeCache(freeStorageSize);
1231 if (retCode < 0) {
1232 Log.w(TAG, "Couldn't clear application caches");
1233 }
1234 } //end if mInstaller
1235 if (observer != null) {
1236 try {
1237 observer.onRemoveCompleted(null, (retCode >= 0));
1238 } catch (RemoteException e) {
1239 Log.w(TAG, "RemoveException when invoking call back");
1240 }
1241 }
1242 }
1243 });
1244 }
1245
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001246 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001247 mContext.enforceCallingOrSelfPermission(
1248 android.Manifest.permission.CLEAR_APP_CACHE, null);
1249 // Queue up an async operation since clearing cache may take a little while.
1250 mHandler.post(new Runnable() {
1251 public void run() {
1252 mHandler.removeCallbacks(this);
1253 int retCode = -1;
1254 if (mInstaller != null) {
1255 retCode = mInstaller.freeCache(freeStorageSize);
1256 if (retCode < 0) {
1257 Log.w(TAG, "Couldn't clear application caches");
1258 }
1259 }
1260 if(pi != null) {
1261 try {
1262 // Callback via pending intent
1263 int code = (retCode >= 0) ? 1 : 0;
1264 pi.sendIntent(null, code, null,
1265 null, null);
1266 } catch (SendIntentException e1) {
1267 Log.i(TAG, "Failed to send pending intent");
1268 }
1269 }
1270 }
1271 });
1272 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1275 synchronized (mPackages) {
1276 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001277
1278 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001280 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
1282 if (mResolveComponentName.equals(component)) {
1283 return mResolveActivity;
1284 }
1285 }
1286 return null;
1287 }
1288
1289 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1290 synchronized (mPackages) {
1291 PackageParser.Activity a = mReceivers.mActivities.get(component);
1292 if (Config.LOGV) Log.v(
1293 TAG, "getReceiverInfo " + component + ": " + a);
1294 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1295 return PackageParser.generateActivityInfo(a, flags);
1296 }
1297 }
1298 return null;
1299 }
1300
1301 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1302 synchronized (mPackages) {
1303 PackageParser.Service s = mServices.mServices.get(component);
1304 if (Config.LOGV) Log.v(
1305 TAG, "getServiceInfo " + component + ": " + s);
1306 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1307 return PackageParser.generateServiceInfo(s, flags);
1308 }
1309 }
1310 return null;
1311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 public String[] getSystemSharedLibraryNames() {
1314 Set<String> libSet;
1315 synchronized (mPackages) {
1316 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001317 int size = libSet.size();
1318 if (size > 0) {
1319 String[] libs = new String[size];
1320 libSet.toArray(libs);
1321 return libs;
1322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001324 return null;
1325 }
1326
1327 public FeatureInfo[] getSystemAvailableFeatures() {
1328 Collection<FeatureInfo> featSet;
1329 synchronized (mPackages) {
1330 featSet = mAvailableFeatures.values();
1331 int size = featSet.size();
1332 if (size > 0) {
1333 FeatureInfo[] features = new FeatureInfo[size+1];
1334 featSet.toArray(features);
1335 FeatureInfo fi = new FeatureInfo();
1336 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1337 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1338 features[size] = fi;
1339 return features;
1340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 }
1342 return null;
1343 }
1344
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001345 public boolean hasSystemFeature(String name) {
1346 synchronized (mPackages) {
1347 return mAvailableFeatures.containsKey(name);
1348 }
1349 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 public int checkPermission(String permName, String pkgName) {
1352 synchronized (mPackages) {
1353 PackageParser.Package p = mPackages.get(pkgName);
1354 if (p != null && p.mExtras != null) {
1355 PackageSetting ps = (PackageSetting)p.mExtras;
1356 if (ps.sharedUser != null) {
1357 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1358 return PackageManager.PERMISSION_GRANTED;
1359 }
1360 } else if (ps.grantedPermissions.contains(permName)) {
1361 return PackageManager.PERMISSION_GRANTED;
1362 }
1363 }
1364 }
1365 return PackageManager.PERMISSION_DENIED;
1366 }
1367
1368 public int checkUidPermission(String permName, int uid) {
1369 synchronized (mPackages) {
1370 Object obj = mSettings.getUserIdLP(uid);
1371 if (obj != null) {
1372 if (obj instanceof SharedUserSetting) {
1373 SharedUserSetting sus = (SharedUserSetting)obj;
1374 if (sus.grantedPermissions.contains(permName)) {
1375 return PackageManager.PERMISSION_GRANTED;
1376 }
1377 } else if (obj instanceof PackageSetting) {
1378 PackageSetting ps = (PackageSetting)obj;
1379 if (ps.grantedPermissions.contains(permName)) {
1380 return PackageManager.PERMISSION_GRANTED;
1381 }
1382 }
1383 } else {
1384 HashSet<String> perms = mSystemPermissions.get(uid);
1385 if (perms != null && perms.contains(permName)) {
1386 return PackageManager.PERMISSION_GRANTED;
1387 }
1388 }
1389 }
1390 return PackageManager.PERMISSION_DENIED;
1391 }
1392
1393 private BasePermission findPermissionTreeLP(String permName) {
1394 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1395 if (permName.startsWith(bp.name) &&
1396 permName.length() > bp.name.length() &&
1397 permName.charAt(bp.name.length()) == '.') {
1398 return bp;
1399 }
1400 }
1401 return null;
1402 }
1403
1404 private BasePermission checkPermissionTreeLP(String permName) {
1405 if (permName != null) {
1406 BasePermission bp = findPermissionTreeLP(permName);
1407 if (bp != null) {
1408 if (bp.uid == Binder.getCallingUid()) {
1409 return bp;
1410 }
1411 throw new SecurityException("Calling uid "
1412 + Binder.getCallingUid()
1413 + " is not allowed to add to permission tree "
1414 + bp.name + " owned by uid " + bp.uid);
1415 }
1416 }
1417 throw new SecurityException("No permission tree found for " + permName);
1418 }
1419
1420 public boolean addPermission(PermissionInfo info) {
1421 synchronized (mPackages) {
1422 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1423 throw new SecurityException("Label must be specified in permission");
1424 }
1425 BasePermission tree = checkPermissionTreeLP(info.name);
1426 BasePermission bp = mSettings.mPermissions.get(info.name);
1427 boolean added = bp == null;
1428 if (added) {
1429 bp = new BasePermission(info.name, tree.sourcePackage,
1430 BasePermission.TYPE_DYNAMIC);
1431 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1432 throw new SecurityException(
1433 "Not allowed to modify non-dynamic permission "
1434 + info.name);
1435 }
1436 bp.perm = new PackageParser.Permission(tree.perm.owner,
1437 new PermissionInfo(info));
1438 bp.perm.info.packageName = tree.perm.info.packageName;
1439 bp.uid = tree.uid;
1440 if (added) {
1441 mSettings.mPermissions.put(info.name, bp);
1442 }
1443 mSettings.writeLP();
1444 return added;
1445 }
1446 }
1447
1448 public void removePermission(String name) {
1449 synchronized (mPackages) {
1450 checkPermissionTreeLP(name);
1451 BasePermission bp = mSettings.mPermissions.get(name);
1452 if (bp != null) {
1453 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1454 throw new SecurityException(
1455 "Not allowed to modify non-dynamic permission "
1456 + name);
1457 }
1458 mSettings.mPermissions.remove(name);
1459 mSettings.writeLP();
1460 }
1461 }
1462 }
1463
Dianne Hackborn854060af2009-07-09 18:14:31 -07001464 public boolean isProtectedBroadcast(String actionName) {
1465 synchronized (mPackages) {
1466 return mProtectedBroadcasts.contains(actionName);
1467 }
1468 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 public int checkSignatures(String pkg1, String pkg2) {
1471 synchronized (mPackages) {
1472 PackageParser.Package p1 = mPackages.get(pkg1);
1473 PackageParser.Package p2 = mPackages.get(pkg2);
1474 if (p1 == null || p1.mExtras == null
1475 || p2 == null || p2.mExtras == null) {
1476 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1477 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001478 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
1480 }
1481
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001482 public int checkUidSignatures(int uid1, int uid2) {
1483 synchronized (mPackages) {
1484 Signature[] s1;
1485 Signature[] s2;
1486 Object obj = mSettings.getUserIdLP(uid1);
1487 if (obj != null) {
1488 if (obj instanceof SharedUserSetting) {
1489 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1490 } else if (obj instanceof PackageSetting) {
1491 s1 = ((PackageSetting)obj).signatures.mSignatures;
1492 } else {
1493 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1494 }
1495 } else {
1496 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1497 }
1498 obj = mSettings.getUserIdLP(uid2);
1499 if (obj != null) {
1500 if (obj instanceof SharedUserSetting) {
1501 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1502 } else if (obj instanceof PackageSetting) {
1503 s2 = ((PackageSetting)obj).signatures.mSignatures;
1504 } else {
1505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1506 }
1507 } else {
1508 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1509 }
1510 return checkSignaturesLP(s1, s2);
1511 }
1512 }
1513
1514 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1515 if (s1 == null) {
1516 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1518 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1519 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001520 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1522 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001523 final int N1 = s1.length;
1524 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 for (int i=0; i<N1; i++) {
1526 boolean match = false;
1527 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001528 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 match = true;
1530 break;
1531 }
1532 }
1533 if (!match) {
1534 return PackageManager.SIGNATURE_NO_MATCH;
1535 }
1536 }
1537 return PackageManager.SIGNATURE_MATCH;
1538 }
1539
1540 public String[] getPackagesForUid(int uid) {
1541 synchronized (mPackages) {
1542 Object obj = mSettings.getUserIdLP(uid);
1543 if (obj instanceof SharedUserSetting) {
1544 SharedUserSetting sus = (SharedUserSetting)obj;
1545 final int N = sus.packages.size();
1546 String[] res = new String[N];
1547 Iterator<PackageSetting> it = sus.packages.iterator();
1548 int i=0;
1549 while (it.hasNext()) {
1550 res[i++] = it.next().name;
1551 }
1552 return res;
1553 } else if (obj instanceof PackageSetting) {
1554 PackageSetting ps = (PackageSetting)obj;
1555 return new String[] { ps.name };
1556 }
1557 }
1558 return null;
1559 }
1560
1561 public String getNameForUid(int uid) {
1562 synchronized (mPackages) {
1563 Object obj = mSettings.getUserIdLP(uid);
1564 if (obj instanceof SharedUserSetting) {
1565 SharedUserSetting sus = (SharedUserSetting)obj;
1566 return sus.name + ":" + sus.userId;
1567 } else if (obj instanceof PackageSetting) {
1568 PackageSetting ps = (PackageSetting)obj;
1569 return ps.name;
1570 }
1571 }
1572 return null;
1573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 public int getUidForSharedUser(String sharedUserName) {
1576 if(sharedUserName == null) {
1577 return -1;
1578 }
1579 synchronized (mPackages) {
1580 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1581 if(suid == null) {
1582 return -1;
1583 }
1584 return suid.userId;
1585 }
1586 }
1587
1588 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1589 int flags) {
1590 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001591 return chooseBestActivity(intent, resolvedType, flags, query);
1592 }
1593
Mihai Predaeae850c2009-05-13 10:13:48 +02001594 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1595 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 if (query != null) {
1597 final int N = query.size();
1598 if (N == 1) {
1599 return query.get(0);
1600 } else if (N > 1) {
1601 // If there is more than one activity with the same priority,
1602 // then let the user decide between them.
1603 ResolveInfo r0 = query.get(0);
1604 ResolveInfo r1 = query.get(1);
1605 if (false) {
1606 System.out.println(r0.activityInfo.name +
1607 "=" + r0.priority + " vs " +
1608 r1.activityInfo.name +
1609 "=" + r1.priority);
1610 }
1611 // If the first activity has a higher priority, or a different
1612 // default, then it is always desireable to pick it.
1613 if (r0.priority != r1.priority
1614 || r0.preferredOrder != r1.preferredOrder
1615 || r0.isDefault != r1.isDefault) {
1616 return query.get(0);
1617 }
1618 // If we have saved a preference for a preferred activity for
1619 // this Intent, use that.
1620 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1621 flags, query, r0.priority);
1622 if (ri != null) {
1623 return ri;
1624 }
1625 return mResolveInfo;
1626 }
1627 }
1628 return null;
1629 }
1630
1631 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1632 int flags, List<ResolveInfo> query, int priority) {
1633 synchronized (mPackages) {
1634 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1635 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001636 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1638 if (prefs != null && prefs.size() > 0) {
1639 // First figure out how good the original match set is.
1640 // We will only allow preferred activities that came
1641 // from the same match quality.
1642 int match = 0;
1643 final int N = query.size();
1644 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1645 for (int j=0; j<N; j++) {
1646 ResolveInfo ri = query.get(j);
1647 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1648 + ": 0x" + Integer.toHexString(match));
1649 if (ri.match > match) match = ri.match;
1650 }
1651 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1652 + Integer.toHexString(match));
1653 match &= IntentFilter.MATCH_CATEGORY_MASK;
1654 final int M = prefs.size();
1655 for (int i=0; i<M; i++) {
1656 PreferredActivity pa = prefs.get(i);
1657 if (pa.mMatch != match) {
1658 continue;
1659 }
1660 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1661 if (DEBUG_PREFERRED) {
1662 Log.v(TAG, "Got preferred activity:");
1663 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1664 }
1665 if (ai != null) {
1666 for (int j=0; j<N; j++) {
1667 ResolveInfo ri = query.get(j);
1668 if (!ri.activityInfo.applicationInfo.packageName
1669 .equals(ai.applicationInfo.packageName)) {
1670 continue;
1671 }
1672 if (!ri.activityInfo.name.equals(ai.name)) {
1673 continue;
1674 }
1675
1676 // Okay we found a previously set preferred app.
1677 // If the result set is different from when this
1678 // was created, we need to clear it and re-ask the
1679 // user their preference.
1680 if (!pa.sameSet(query, priority)) {
1681 Log.i(TAG, "Result set changed, dropping preferred activity for "
1682 + intent + " type " + resolvedType);
1683 mSettings.mPreferredActivities.removeFilter(pa);
1684 return null;
1685 }
1686
1687 // Yay!
1688 return ri;
1689 }
1690 }
1691 }
1692 }
1693 }
1694 return null;
1695 }
1696
1697 public List<ResolveInfo> queryIntentActivities(Intent intent,
1698 String resolvedType, int flags) {
1699 ComponentName comp = intent.getComponent();
1700 if (comp != null) {
1701 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1702 ActivityInfo ai = getActivityInfo(comp, flags);
1703 if (ai != null) {
1704 ResolveInfo ri = new ResolveInfo();
1705 ri.activityInfo = ai;
1706 list.add(ri);
1707 }
1708 return list;
1709 }
1710
1711 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001712 String pkgName = intent.getPackage();
1713 if (pkgName == null) {
1714 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1715 resolvedType, flags);
1716 }
1717 PackageParser.Package pkg = mPackages.get(pkgName);
1718 if (pkg != null) {
1719 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1720 resolvedType, flags, pkg.activities);
1721 }
1722 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 }
1724 }
1725
1726 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1727 Intent[] specifics, String[] specificTypes, Intent intent,
1728 String resolvedType, int flags) {
1729 final String resultsAction = intent.getAction();
1730
1731 List<ResolveInfo> results = queryIntentActivities(
1732 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1733 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1734
1735 int specificsPos = 0;
1736 int N;
1737
1738 // todo: note that the algorithm used here is O(N^2). This
1739 // isn't a problem in our current environment, but if we start running
1740 // into situations where we have more than 5 or 10 matches then this
1741 // should probably be changed to something smarter...
1742
1743 // First we go through and resolve each of the specific items
1744 // that were supplied, taking care of removing any corresponding
1745 // duplicate items in the generic resolve list.
1746 if (specifics != null) {
1747 for (int i=0; i<specifics.length; i++) {
1748 final Intent sintent = specifics[i];
1749 if (sintent == null) {
1750 continue;
1751 }
1752
1753 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1754 String action = sintent.getAction();
1755 if (resultsAction != null && resultsAction.equals(action)) {
1756 // If this action was explicitly requested, then don't
1757 // remove things that have it.
1758 action = null;
1759 }
1760 ComponentName comp = sintent.getComponent();
1761 ResolveInfo ri = null;
1762 ActivityInfo ai = null;
1763 if (comp == null) {
1764 ri = resolveIntent(
1765 sintent,
1766 specificTypes != null ? specificTypes[i] : null,
1767 flags);
1768 if (ri == null) {
1769 continue;
1770 }
1771 if (ri == mResolveInfo) {
1772 // ACK! Must do something better with this.
1773 }
1774 ai = ri.activityInfo;
1775 comp = new ComponentName(ai.applicationInfo.packageName,
1776 ai.name);
1777 } else {
1778 ai = getActivityInfo(comp, flags);
1779 if (ai == null) {
1780 continue;
1781 }
1782 }
1783
1784 // Look for any generic query activities that are duplicates
1785 // of this specific one, and remove them from the results.
1786 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1787 N = results.size();
1788 int j;
1789 for (j=specificsPos; j<N; j++) {
1790 ResolveInfo sri = results.get(j);
1791 if ((sri.activityInfo.name.equals(comp.getClassName())
1792 && sri.activityInfo.applicationInfo.packageName.equals(
1793 comp.getPackageName()))
1794 || (action != null && sri.filter.matchAction(action))) {
1795 results.remove(j);
1796 if (Config.LOGV) Log.v(
1797 TAG, "Removing duplicate item from " + j
1798 + " due to specific " + specificsPos);
1799 if (ri == null) {
1800 ri = sri;
1801 }
1802 j--;
1803 N--;
1804 }
1805 }
1806
1807 // Add this specific item to its proper place.
1808 if (ri == null) {
1809 ri = new ResolveInfo();
1810 ri.activityInfo = ai;
1811 }
1812 results.add(specificsPos, ri);
1813 ri.specificIndex = i;
1814 specificsPos++;
1815 }
1816 }
1817
1818 // Now we go through the remaining generic results and remove any
1819 // duplicate actions that are found here.
1820 N = results.size();
1821 for (int i=specificsPos; i<N-1; i++) {
1822 final ResolveInfo rii = results.get(i);
1823 if (rii.filter == null) {
1824 continue;
1825 }
1826
1827 // Iterate over all of the actions of this result's intent
1828 // filter... typically this should be just one.
1829 final Iterator<String> it = rii.filter.actionsIterator();
1830 if (it == null) {
1831 continue;
1832 }
1833 while (it.hasNext()) {
1834 final String action = it.next();
1835 if (resultsAction != null && resultsAction.equals(action)) {
1836 // If this action was explicitly requested, then don't
1837 // remove things that have it.
1838 continue;
1839 }
1840 for (int j=i+1; j<N; j++) {
1841 final ResolveInfo rij = results.get(j);
1842 if (rij.filter != null && rij.filter.hasAction(action)) {
1843 results.remove(j);
1844 if (Config.LOGV) Log.v(
1845 TAG, "Removing duplicate item from " + j
1846 + " due to action " + action + " at " + i);
1847 j--;
1848 N--;
1849 }
1850 }
1851 }
1852
1853 // If the caller didn't request filter information, drop it now
1854 // so we don't have to marshall/unmarshall it.
1855 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1856 rii.filter = null;
1857 }
1858 }
1859
1860 // Filter out the caller activity if so requested.
1861 if (caller != null) {
1862 N = results.size();
1863 for (int i=0; i<N; i++) {
1864 ActivityInfo ainfo = results.get(i).activityInfo;
1865 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1866 && caller.getClassName().equals(ainfo.name)) {
1867 results.remove(i);
1868 break;
1869 }
1870 }
1871 }
1872
1873 // If the caller didn't request filter information,
1874 // drop them now so we don't have to
1875 // marshall/unmarshall it.
1876 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1877 N = results.size();
1878 for (int i=0; i<N; i++) {
1879 results.get(i).filter = null;
1880 }
1881 }
1882
1883 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1884 return results;
1885 }
1886
1887 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1888 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001889 ComponentName comp = intent.getComponent();
1890 if (comp != null) {
1891 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1892 ActivityInfo ai = getReceiverInfo(comp, flags);
1893 if (ai != null) {
1894 ResolveInfo ri = new ResolveInfo();
1895 ri.activityInfo = ai;
1896 list.add(ri);
1897 }
1898 return list;
1899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001902 String pkgName = intent.getPackage();
1903 if (pkgName == null) {
1904 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1905 resolvedType, flags);
1906 }
1907 PackageParser.Package pkg = mPackages.get(pkgName);
1908 if (pkg != null) {
1909 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1910 resolvedType, flags, pkg.receivers);
1911 }
1912 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 }
1914 }
1915
1916 public ResolveInfo resolveService(Intent intent, String resolvedType,
1917 int flags) {
1918 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1919 flags);
1920 if (query != null) {
1921 if (query.size() >= 1) {
1922 // If there is more than one service with the same priority,
1923 // just arbitrarily pick the first one.
1924 return query.get(0);
1925 }
1926 }
1927 return null;
1928 }
1929
1930 public List<ResolveInfo> queryIntentServices(Intent intent,
1931 String resolvedType, int flags) {
1932 ComponentName comp = intent.getComponent();
1933 if (comp != null) {
1934 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1935 ServiceInfo si = getServiceInfo(comp, flags);
1936 if (si != null) {
1937 ResolveInfo ri = new ResolveInfo();
1938 ri.serviceInfo = si;
1939 list.add(ri);
1940 }
1941 return list;
1942 }
1943
1944 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001945 String pkgName = intent.getPackage();
1946 if (pkgName == null) {
1947 return (List<ResolveInfo>)mServices.queryIntent(intent,
1948 resolvedType, flags);
1949 }
1950 PackageParser.Package pkg = mPackages.get(pkgName);
1951 if (pkg != null) {
1952 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1953 resolvedType, flags, pkg.services);
1954 }
1955 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
1957 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 public List<PackageInfo> getInstalledPackages(int flags) {
1960 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1961
1962 synchronized (mPackages) {
1963 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1964 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1965 while (i.hasNext()) {
1966 final PackageSetting ps = i.next();
1967 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1968 if(psPkg != null) {
1969 finalList.add(psPkg);
1970 }
1971 }
1972 }
1973 else {
1974 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1975 while (i.hasNext()) {
1976 final PackageParser.Package p = i.next();
1977 if (p.applicationInfo != null) {
1978 PackageInfo pi = generatePackageInfo(p, flags);
1979 if(pi != null) {
1980 finalList.add(pi);
1981 }
1982 }
1983 }
1984 }
1985 }
1986 return finalList;
1987 }
1988
1989 public List<ApplicationInfo> getInstalledApplications(int flags) {
1990 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1991 synchronized(mPackages) {
1992 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1993 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1994 while (i.hasNext()) {
1995 final PackageSetting ps = i.next();
1996 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1997 if(ai != null) {
1998 finalList.add(ai);
1999 }
2000 }
2001 }
2002 else {
2003 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2004 while (i.hasNext()) {
2005 final PackageParser.Package p = i.next();
2006 if (p.applicationInfo != null) {
2007 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2008 if(ai != null) {
2009 finalList.add(ai);
2010 }
2011 }
2012 }
2013 }
2014 }
2015 return finalList;
2016 }
2017
2018 public List<ApplicationInfo> getPersistentApplications(int flags) {
2019 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2020
2021 synchronized (mPackages) {
2022 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2023 while (i.hasNext()) {
2024 PackageParser.Package p = i.next();
2025 if (p.applicationInfo != null
2026 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2027 && (!mSafeMode || (p.applicationInfo.flags
2028 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2029 finalList.add(p.applicationInfo);
2030 }
2031 }
2032 }
2033
2034 return finalList;
2035 }
2036
2037 public ProviderInfo resolveContentProvider(String name, int flags) {
2038 synchronized (mPackages) {
2039 final PackageParser.Provider provider = mProviders.get(name);
2040 return provider != null
2041 && mSettings.isEnabledLP(provider.info, flags)
2042 && (!mSafeMode || (provider.info.applicationInfo.flags
2043 &ApplicationInfo.FLAG_SYSTEM) != 0)
2044 ? PackageParser.generateProviderInfo(provider, flags)
2045 : null;
2046 }
2047 }
2048
Fred Quintana718d8a22009-04-29 17:53:20 -07002049 /**
2050 * @deprecated
2051 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 public void querySyncProviders(List outNames, List outInfo) {
2053 synchronized (mPackages) {
2054 Iterator<Map.Entry<String, PackageParser.Provider>> i
2055 = mProviders.entrySet().iterator();
2056
2057 while (i.hasNext()) {
2058 Map.Entry<String, PackageParser.Provider> entry = i.next();
2059 PackageParser.Provider p = entry.getValue();
2060
2061 if (p.syncable
2062 && (!mSafeMode || (p.info.applicationInfo.flags
2063 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2064 outNames.add(entry.getKey());
2065 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2066 }
2067 }
2068 }
2069 }
2070
2071 public List<ProviderInfo> queryContentProviders(String processName,
2072 int uid, int flags) {
2073 ArrayList<ProviderInfo> finalList = null;
2074
2075 synchronized (mPackages) {
2076 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2077 while (i.hasNext()) {
2078 PackageParser.Provider p = i.next();
2079 if (p.info.authority != null
2080 && (processName == null ||
2081 (p.info.processName.equals(processName)
2082 && p.info.applicationInfo.uid == uid))
2083 && mSettings.isEnabledLP(p.info, flags)
2084 && (!mSafeMode || (p.info.applicationInfo.flags
2085 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2086 if (finalList == null) {
2087 finalList = new ArrayList<ProviderInfo>(3);
2088 }
2089 finalList.add(PackageParser.generateProviderInfo(p,
2090 flags));
2091 }
2092 }
2093 }
2094
2095 if (finalList != null) {
2096 Collections.sort(finalList, mProviderInitOrderSorter);
2097 }
2098
2099 return finalList;
2100 }
2101
2102 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2103 int flags) {
2104 synchronized (mPackages) {
2105 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2106 return PackageParser.generateInstrumentationInfo(i, flags);
2107 }
2108 }
2109
2110 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2111 int flags) {
2112 ArrayList<InstrumentationInfo> finalList =
2113 new ArrayList<InstrumentationInfo>();
2114
2115 synchronized (mPackages) {
2116 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2117 while (i.hasNext()) {
2118 PackageParser.Instrumentation p = i.next();
2119 if (targetPackage == null
2120 || targetPackage.equals(p.info.targetPackage)) {
2121 finalList.add(PackageParser.generateInstrumentationInfo(p,
2122 flags));
2123 }
2124 }
2125 }
2126
2127 return finalList;
2128 }
2129
2130 private void scanDirLI(File dir, int flags, int scanMode) {
2131 Log.d(TAG, "Scanning app dir " + dir);
2132
2133 String[] files = dir.list();
2134
2135 int i;
2136 for (i=0; i<files.length; i++) {
2137 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002138 if (!isPackageFilename(files[i])) {
2139 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002140 continue;
2141 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002142 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002144 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002145 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2146 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002147 // Delete the apk
2148 Log.w(TAG, "Cleaning up failed install of " + file);
2149 file.delete();
2150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 }
2152 }
2153
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002154 private static File getSettingsProblemFile() {
2155 File dataDir = Environment.getDataDirectory();
2156 File systemDir = new File(dataDir, "system");
2157 File fname = new File(systemDir, "uiderrors.txt");
2158 return fname;
2159 }
2160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 private static void reportSettingsProblem(int priority, String msg) {
2162 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002163 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 FileOutputStream out = new FileOutputStream(fname, true);
2165 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002166 SimpleDateFormat formatter = new SimpleDateFormat();
2167 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2168 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 pw.close();
2170 FileUtils.setPermissions(
2171 fname.toString(),
2172 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2173 -1, -1);
2174 } catch (java.io.IOException e) {
2175 }
2176 Log.println(priority, TAG, msg);
2177 }
2178
2179 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2180 PackageParser.Package pkg, File srcFile, int parseFlags) {
2181 if (GET_CERTIFICATES) {
2182 if (ps == null || !ps.codePath.equals(srcFile)
2183 || ps.getTimeStamp() != srcFile.lastModified()) {
2184 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2185 if (!pp.collectCertificates(pkg, parseFlags)) {
2186 mLastScanError = pp.getParseError();
2187 return false;
2188 }
2189 }
2190 }
2191 return true;
2192 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 /*
2195 * Scan a package and return the newly parsed package.
2196 * Returns null in case of errors and the error code is stored in mLastScanError
2197 */
2198 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002199 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002201 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002203 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002206 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 if (pkg == null) {
2208 mLastScanError = pp.getParseError();
2209 return null;
2210 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002211 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 PackageSetting updatedPkg;
2213 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002214 // Look to see if we already know about this package.
2215 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
2216 if (oldName != null && oldName.equals(pkg.mOriginalPackage)) {
2217 // This package has been renamed to its original name. Let's
2218 // use that.
2219 ps = mSettings.peekPackageLP(pkg.mOriginalPackage);
2220 }
2221 // If there was no original package, see one for the real package name.
2222 if (ps == null) {
2223 ps = mSettings.peekPackageLP(pkg.packageName);
2224 }
2225 // Check to see if this package could be hiding/updating a system
2226 // package. Must look for it either under the original or real
2227 // package name depending on our state.
2228 updatedPkg = mSettings.mDisabledSysPackages.get(
2229 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002231 // First check if this is a system package that may involve an update
2232 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2233 if (!ps.codePath.equals(scanFile)) {
2234 // The path has changed from what was last scanned... check the
2235 // version of the new path against what we have stored to determine
2236 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002237 if (pkg.mVersionCode < ps.versionCode) {
2238 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002239 // Ignore entry. Skip it.
2240 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2241 + "ignored: updated version " + ps.versionCode
2242 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002243 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2244 return null;
2245 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002246 // The current app on the system partion is better than
2247 // what we have updated to on the data partition; switch
2248 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002249 // At this point, its safely assumed that package installation for
2250 // apps in system partition will go through. If not there won't be a working
2251 // version of the app
2252 synchronized (mPackages) {
2253 // Just remove the loaded entries from package lists.
2254 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002255 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002256 Log.w(TAG, "Package " + ps.name + " at " + scanFile
2257 + "reverting from " + ps.codePathString
2258 + ": new version " + pkg.mVersionCode
2259 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002260 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2261 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002262 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 }
2265 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002266 if (updatedPkg != null) {
2267 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2268 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2269 }
2270 // Verify certificates against what was last scanned
2271 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2272 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2273 return null;
2274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 // The apk is forward locked (not public) if its code and resources
2276 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002277 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002279 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002280 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002281
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002282 String codePath = null;
2283 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002284 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2285 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002286 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002287 } else {
2288 // Should not happen at all. Just log an error.
2289 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2290 }
2291 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002292 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002293 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002294 codePath = pkg.mScanPath;
2295 // Set application objects path explicitly.
2296 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002298 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002299 }
2300
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002301 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2302 String destCodePath, String destResPath) {
2303 pkg.mPath = pkg.mScanPath = destCodePath;
2304 pkg.applicationInfo.sourceDir = destCodePath;
2305 pkg.applicationInfo.publicSourceDir = destResPath;
2306 }
2307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 private static String fixProcessName(String defProcessName,
2309 String processName, int uid) {
2310 if (processName == null) {
2311 return defProcessName;
2312 }
2313 return processName;
2314 }
2315
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002316 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2318 if (pkg.mSignatures != null) {
2319 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2320 updateSignature)) {
2321 Log.e(TAG, "Package " + pkg.packageName
2322 + " signatures do not match the previously installed version; ignoring!");
2323 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2324 return false;
2325 }
2326
2327 if (pkgSetting.sharedUser != null) {
2328 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2329 pkg.mSignatures, updateSignature)) {
2330 Log.e(TAG, "Package " + pkg.packageName
2331 + " has no signatures that match those in shared user "
2332 + pkgSetting.sharedUser.name + "; ignoring!");
2333 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2334 return false;
2335 }
2336 }
2337 } else {
2338 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2339 }
2340 return true;
2341 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002342
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002343 public boolean performDexOpt(String packageName) {
2344 if (!mNoDexOpt) {
2345 return false;
2346 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002347
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002348 PackageParser.Package p;
2349 synchronized (mPackages) {
2350 p = mPackages.get(packageName);
2351 if (p == null || p.mDidDexOpt) {
2352 return false;
2353 }
2354 }
2355 synchronized (mInstallLock) {
2356 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2357 }
2358 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002359
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002360 static final int DEX_OPT_SKIPPED = 0;
2361 static final int DEX_OPT_PERFORMED = 1;
2362 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002363
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002364 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2365 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002366 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002367 String path = pkg.mScanPath;
2368 int ret = 0;
2369 try {
2370 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002371 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002372 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002373 pkg.mDidDexOpt = true;
2374 performed = true;
2375 }
2376 } catch (FileNotFoundException e) {
2377 Log.w(TAG, "Apk not found for dexopt: " + path);
2378 ret = -1;
2379 } catch (IOException e) {
2380 Log.w(TAG, "Exception reading apk: " + path, e);
2381 ret = -1;
2382 }
2383 if (ret < 0) {
2384 //error from installer
2385 return DEX_OPT_FAILED;
2386 }
2387 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002388
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002389 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2390 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002391
2392 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2393 return Environment.isEncryptedFilesystemEnabled() &&
2394 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2395 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002396
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002397 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2398 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2399 Log.w(TAG, "Unable to update from " + oldPkg.name
2400 + " to " + newPkg.packageName
2401 + ": old package not in system partition");
2402 return false;
2403 } else if (mPackages.get(oldPkg.name) != null) {
2404 Log.w(TAG, "Unable to update from " + oldPkg.name
2405 + " to " + newPkg.packageName
2406 + ": old package still exists");
2407 return false;
2408 }
2409 return true;
2410 }
2411
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002412 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2413 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002414 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002415 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2416 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002417 // Bail out. The resource and code paths haven't been set.
2418 Log.w(TAG, " Code and resource paths haven't been set correctly");
2419 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2420 return null;
2421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 mScanningPath = scanFile;
2423 if (pkg == null) {
2424 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2425 return null;
2426 }
2427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2429 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2430 }
2431
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002432 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 synchronized (mPackages) {
2434 if (mAndroidApplication != null) {
2435 Log.w(TAG, "*************************************************");
2436 Log.w(TAG, "Core android package being redefined. Skipping.");
2437 Log.w(TAG, " file=" + mScanningPath);
2438 Log.w(TAG, "*************************************************");
2439 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2440 return null;
2441 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 // Set up information for our fall-back user intent resolution
2444 // activity.
2445 mPlatformPackage = pkg;
2446 pkg.mVersionCode = mSdkVersion;
2447 mAndroidApplication = pkg.applicationInfo;
2448 mResolveActivity.applicationInfo = mAndroidApplication;
2449 mResolveActivity.name = ResolverActivity.class.getName();
2450 mResolveActivity.packageName = mAndroidApplication.packageName;
2451 mResolveActivity.processName = mAndroidApplication.processName;
2452 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2453 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2454 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2455 mResolveActivity.exported = true;
2456 mResolveActivity.enabled = true;
2457 mResolveInfo.activityInfo = mResolveActivity;
2458 mResolveInfo.priority = 0;
2459 mResolveInfo.preferredOrder = 0;
2460 mResolveInfo.match = 0;
2461 mResolveComponentName = new ComponentName(
2462 mAndroidApplication.packageName, mResolveActivity.name);
2463 }
2464 }
2465
2466 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002467 TAG, "Scanning package " + pkg.packageName);
2468 if (mPackages.containsKey(pkg.packageName)
2469 || mSharedLibraries.containsKey(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 Log.w(TAG, "*************************************************");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002471 Log.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 + " already installed. Skipping duplicate.");
2473 Log.w(TAG, "*************************************************");
2474 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2475 return null;
2476 }
2477
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002478 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002479 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2480 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 SharedUserSetting suid = null;
2483 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002486
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002487 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2488 // Only system apps can use these features.
2489 pkg.mOriginalPackage = null;
2490 pkg.mRealPackage = null;
2491 pkg.mAdoptPermissions = null;
2492 }
2493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 synchronized (mPackages) {
2495 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002496 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2497 if (mTmpSharedLibraries == null ||
2498 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2499 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2500 }
2501 int num = 0;
2502 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2503 for (int i=0; i<N; i++) {
2504 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 if (file == null) {
2506 Log.e(TAG, "Package " + pkg.packageName
2507 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002508 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2510 return null;
2511 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002512 mTmpSharedLibraries[num] = file;
2513 num++;
2514 }
2515 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2516 for (int i=0; i<N; i++) {
2517 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2518 if (file == null) {
2519 Log.w(TAG, "Package " + pkg.packageName
2520 + " desires unavailable shared library "
2521 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2522 } else {
2523 mTmpSharedLibraries[num] = file;
2524 num++;
2525 }
2526 }
2527 if (num > 0) {
2528 pkg.usesLibraryFiles = new String[num];
2529 System.arraycopy(mTmpSharedLibraries, 0,
2530 pkg.usesLibraryFiles, 0, num);
2531 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002532
Dianne Hackborn49237342009-08-27 20:08:01 -07002533 if (pkg.reqFeatures != null) {
2534 N = pkg.reqFeatures.size();
2535 for (int i=0; i<N; i++) {
2536 FeatureInfo fi = pkg.reqFeatures.get(i);
2537 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2538 // Don't care.
2539 continue;
2540 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002541
Dianne Hackborn49237342009-08-27 20:08:01 -07002542 if (fi.name != null) {
2543 if (mAvailableFeatures.get(fi.name) == null) {
2544 Log.e(TAG, "Package " + pkg.packageName
2545 + " requires unavailable feature "
2546 + fi.name + "; failing!");
2547 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2548 return null;
2549 }
2550 }
2551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 }
2553 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 if (pkg.mSharedUserId != null) {
2556 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2557 pkg.applicationInfo.flags, true);
2558 if (suid == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002559 Log.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 + " for shared user failed");
2561 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2562 return null;
2563 }
2564 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2565 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2566 + suid.userId + "): packages=" + suid.packages);
2567 }
2568 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002569
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002570 if (false) {
2571 if (pkg.mOriginalPackage != null) {
2572 Log.w(TAG, "WAITING FOR DEBUGGER");
2573 Debug.waitForDebugger();
2574 Log.i(TAG, "Package " + pkg.packageName + " from original package"
2575 + pkg.mOriginalPackage);
2576 }
2577 }
2578
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002579 // Check if we are renaming from an original package name.
2580 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002581 String realName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002582 if (pkg.mOriginalPackage != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002583 // This package may need to be renamed to a previously
2584 // installed name. Let's check on that...
2585 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
2586 if (pkg.mOriginalPackage.equals(renamed)) {
2587 // This package had originally been installed as the
2588 // original name, and we have already taken care of
2589 // transitioning to the new one. Just update the new
2590 // one to continue using the old name.
2591 realName = pkg.mRealPackage;
2592 if (!pkg.packageName.equals(renamed)) {
2593 // Callers into this function may have already taken
2594 // care of renaming the package; only do it here if
2595 // it is not already done.
2596 pkg.setPackageName(renamed);
2597 }
2598
2599 } else if ((origPackage
2600 = mSettings.peekPackageLP(pkg.mOriginalPackage)) != null) {
2601 // We do have the package already installed under its
2602 // original name... should we use it?
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002603 if (!verifyPackageUpdate(origPackage, pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002604 // New package is not compatible with original.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002605 origPackage = null;
2606 } else if (origPackage.sharedUser != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002607 // Make sure uid is compatible between packages.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002608 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2609 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2610 + " to " + pkg.packageName + ": old uid "
2611 + origPackage.sharedUser.name
2612 + " differs from " + pkg.mSharedUserId);
2613 origPackage = null;
2614 }
2615 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002616 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2617 + pkg.packageName + " to old name " + origPackage.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002618 }
2619 }
2620 }
2621
2622 if (mTransferedPackages.contains(pkg.packageName)) {
2623 Log.w(TAG, "Package " + pkg.packageName
2624 + " was transferred to another, but its .apk remains");
2625 }
2626
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002627 // Just create the setting, don't add it yet. For already existing packages
2628 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002629 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 destResourceFile, pkg.applicationInfo.flags, true, false);
2631 if (pkgSetting == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002632 Log.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2634 return null;
2635 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002636
2637 if (pkgSetting.origPackage != null) {
2638 // If we are first transitioning from an original package,
2639 // fix up the new package's name now. We need to do this after
2640 // looking up the package under its new name, so getPackageLP
2641 // can take care of fiddling things correctly.
2642 pkg.setPackageName(origPackage.name);
2643
2644 // File a report about this.
2645 String msg = "New package " + pkgSetting.realName
2646 + " renamed to replace old package " + pkgSetting.name;
2647 reportSettingsProblem(Log.WARN, msg);
2648
2649 // Make a note of it.
2650 mTransferedPackages.add(origPackage.name);
2651
2652 // No longer need to retain this.
2653 pkgSetting.origPackage = null;
2654 }
2655
2656 if (realName != null) {
2657 // Make a note of it.
2658 mTransferedPackages.add(pkg.packageName);
2659 }
2660
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002661 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2663 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 pkg.applicationInfo.uid = pkgSetting.userId;
2666 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002667
2668 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2670 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2671 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2672 return null;
2673 }
2674 // The signature has changed, but this package is in the system
2675 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002676 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 // However... if this package is part of a shared user, but it
2678 // doesn't match the signature of the shared user, let's fail.
2679 // What this means is that you can't change the signatures
2680 // associated with an overall shared user, which doesn't seem all
2681 // that unreasonable.
2682 if (pkgSetting.sharedUser != null) {
2683 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2684 pkg.mSignatures, false)) {
2685 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2686 return null;
2687 }
2688 }
2689 removeExisting = true;
2690 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002691
The Android Open Source Project10592532009-03-18 17:39:46 -07002692 // Verify that this new package doesn't have any content providers
2693 // that conflict with existing packages. Only do this if the
2694 // package isn't already installed, since we don't want to break
2695 // things that are installed.
2696 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2697 int N = pkg.providers.size();
2698 int i;
2699 for (i=0; i<N; i++) {
2700 PackageParser.Provider p = pkg.providers.get(i);
2701 String names[] = p.info.authority.split(";");
2702 for (int j = 0; j < names.length; j++) {
2703 if (mProviders.containsKey(names[j])) {
2704 PackageParser.Provider other = mProviders.get(names[j]);
2705 Log.w(TAG, "Can't install because provider name " + names[j] +
2706 " (in package " + pkg.applicationInfo.packageName +
2707 ") is already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002708 + ((other != null && other.getComponentName() != null)
2709 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project10592532009-03-18 17:39:46 -07002710 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2711 return null;
2712 }
2713 }
2714 }
2715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002718 final String pkgName = pkg.packageName;
2719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002721 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002723 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 if (ret != 0) {
2725 String msg = "System package " + pkg.packageName
2726 + " could not have data directory erased after signature change.";
2727 reportSettingsProblem(Log.WARN, msg);
2728 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2729 return null;
2730 }
2731 }
2732 Log.w(TAG, "System package " + pkg.packageName
2733 + " signature changed: existing data removed.");
2734 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002737 if (pkg.mAdoptPermissions != null) {
2738 // This package wants to adopt ownership of permissions from
2739 // another package.
2740 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2741 String origName = pkg.mAdoptPermissions.get(i);
2742 PackageSetting orig = mSettings.peekPackageLP(origName);
2743 if (orig != null) {
2744 if (verifyPackageUpdate(orig, pkg)) {
2745 Log.i(TAG, "Adopting permissions from "
2746 + origName + " to " + pkg.packageName);
2747 mSettings.transferPermissions(origName, pkg.packageName);
2748 }
2749 }
2750 }
2751 }
2752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 long scanFileTime = scanFile.lastModified();
2754 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2755 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2756 pkg.applicationInfo.processName = fixProcessName(
2757 pkg.applicationInfo.packageName,
2758 pkg.applicationInfo.processName,
2759 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760
2761 File dataPath;
2762 if (mPlatformPackage == pkg) {
2763 // The system package is special.
2764 dataPath = new File (Environment.getDataDirectory(), "system");
2765 pkg.applicationInfo.dataDir = dataPath.getPath();
2766 } else {
2767 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002768 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2769 if (useEncryptedFSDir) {
2770 dataPath = new File(mSecureAppDataDir, pkgName);
2771 } else {
2772 dataPath = new File(mAppDataDir, pkgName);
2773 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002774
2775 boolean uidError = false;
2776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 if (dataPath.exists()) {
2778 mOutPermissions[1] = 0;
2779 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2780 if (mOutPermissions[1] == pkg.applicationInfo.uid
2781 || !Process.supportsProcesses()) {
2782 pkg.applicationInfo.dataDir = dataPath.getPath();
2783 } else {
2784 boolean recovered = false;
2785 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2786 // If this is a system app, we can at least delete its
2787 // current data so the application will still work.
2788 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002789 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002790 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 // Old data gone!
2792 String msg = "System package " + pkg.packageName
2793 + " has changed from uid: "
2794 + mOutPermissions[1] + " to "
2795 + pkg.applicationInfo.uid + "; old data erased";
2796 reportSettingsProblem(Log.WARN, msg);
2797 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002800 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 pkg.applicationInfo.uid);
2802 if (ret == -1) {
2803 // Ack should not happen!
2804 msg = "System package " + pkg.packageName
2805 + " could not have data directory re-created after delete.";
2806 reportSettingsProblem(Log.WARN, msg);
2807 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2808 return null;
2809 }
2810 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 if (!recovered) {
2813 mHasSystemUidErrors = true;
2814 }
2815 }
2816 if (!recovered) {
2817 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2818 + pkg.applicationInfo.uid + "/fs_"
2819 + mOutPermissions[1];
2820 String msg = "Package " + pkg.packageName
2821 + " has mismatched uid: "
2822 + mOutPermissions[1] + " on disk, "
2823 + pkg.applicationInfo.uid + " in settings";
2824 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002825 mSettings.mReadMessages.append(msg);
2826 mSettings.mReadMessages.append('\n');
2827 uidError = true;
2828 if (!pkgSetting.uidError) {
2829 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 }
2832 }
2833 }
2834 pkg.applicationInfo.dataDir = dataPath.getPath();
2835 } else {
2836 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2837 Log.v(TAG, "Want this data dir: " + dataPath);
2838 //invoke installer to do the actual installation
2839 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002840 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 pkg.applicationInfo.uid);
2842 if(ret < 0) {
2843 // Error from installer
2844 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2845 return null;
2846 }
2847 } else {
2848 dataPath.mkdirs();
2849 if (dataPath.exists()) {
2850 FileUtils.setPermissions(
2851 dataPath.toString(),
2852 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2853 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2854 }
2855 }
2856 if (dataPath.exists()) {
2857 pkg.applicationInfo.dataDir = dataPath.getPath();
2858 } else {
2859 Log.w(TAG, "Unable to create data directory: " + dataPath);
2860 pkg.applicationInfo.dataDir = null;
2861 }
2862 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002863
2864 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 }
2866
2867 // Perform shared library installation and dex validation and
2868 // optimization, if this is not a system app.
2869 if (mInstaller != null) {
2870 String path = scanFile.getPath();
2871 if (scanFileNewer) {
2872 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002873 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2874 if (err != PackageManager.INSTALL_SUCCEEDED) {
2875 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 return null;
2877 }
2878 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002879 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002880
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002881 if ((scanMode&SCAN_NO_DEX) == 0) {
2882 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2884 return null;
2885 }
2886 }
2887 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 if (mFactoryTest && pkg.requestedPermissions.contains(
2890 android.Manifest.permission.FACTORY_TEST)) {
2891 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2892 }
2893
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002894 // Request the ActivityManager to kill the process(only for existing packages)
2895 // so that we do not end up in a confused state while the user is still using the older
2896 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002897 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002898 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002899 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002900 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002903 // We don't expect installation to fail beyond this point,
2904 if ((scanMode&SCAN_MONITOR) != 0) {
2905 mAppDirs.put(pkg.mPath, pkg);
2906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002908 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002910 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08002911 // Make sure we don't accidentally delete its data.
2912 mSettings.mPackagesToBeCleaned.remove(pkgName);
2913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 int N = pkg.providers.size();
2915 StringBuilder r = null;
2916 int i;
2917 for (i=0; i<N; i++) {
2918 PackageParser.Provider p = pkg.providers.get(i);
2919 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2920 p.info.processName, pkg.applicationInfo.uid);
2921 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2922 p.info.name), p);
2923 p.syncable = p.info.isSyncable;
2924 String names[] = p.info.authority.split(";");
2925 p.info.authority = null;
2926 for (int j = 0; j < names.length; j++) {
2927 if (j == 1 && p.syncable) {
2928 // We only want the first authority for a provider to possibly be
2929 // syncable, so if we already added this provider using a different
2930 // authority clear the syncable flag. We copy the provider before
2931 // changing it because the mProviders object contains a reference
2932 // to a provider that we don't want to change.
2933 // Only do this for the second authority since the resulting provider
2934 // object can be the same for all future authorities for this provider.
2935 p = new PackageParser.Provider(p);
2936 p.syncable = false;
2937 }
2938 if (!mProviders.containsKey(names[j])) {
2939 mProviders.put(names[j], p);
2940 if (p.info.authority == null) {
2941 p.info.authority = names[j];
2942 } else {
2943 p.info.authority = p.info.authority + ";" + names[j];
2944 }
2945 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2946 Log.d(TAG, "Registered content provider: " + names[j] +
2947 ", className = " + p.info.name +
2948 ", isSyncable = " + p.info.isSyncable);
2949 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002950 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 Log.w(TAG, "Skipping provider name " + names[j] +
2952 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002953 "): name already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002954 + ((other != null && other.getComponentName() != null)
2955 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 }
2957 }
2958 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2959 if (r == null) {
2960 r = new StringBuilder(256);
2961 } else {
2962 r.append(' ');
2963 }
2964 r.append(p.info.name);
2965 }
2966 }
2967 if (r != null) {
2968 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2969 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 N = pkg.services.size();
2972 r = null;
2973 for (i=0; i<N; i++) {
2974 PackageParser.Service s = pkg.services.get(i);
2975 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2976 s.info.processName, pkg.applicationInfo.uid);
2977 mServices.addService(s);
2978 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2979 if (r == null) {
2980 r = new StringBuilder(256);
2981 } else {
2982 r.append(' ');
2983 }
2984 r.append(s.info.name);
2985 }
2986 }
2987 if (r != null) {
2988 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2989 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 N = pkg.receivers.size();
2992 r = null;
2993 for (i=0; i<N; i++) {
2994 PackageParser.Activity a = pkg.receivers.get(i);
2995 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2996 a.info.processName, pkg.applicationInfo.uid);
2997 mReceivers.addActivity(a, "receiver");
2998 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2999 if (r == null) {
3000 r = new StringBuilder(256);
3001 } else {
3002 r.append(' ');
3003 }
3004 r.append(a.info.name);
3005 }
3006 }
3007 if (r != null) {
3008 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3009 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 N = pkg.activities.size();
3012 r = null;
3013 for (i=0; i<N; i++) {
3014 PackageParser.Activity a = pkg.activities.get(i);
3015 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3016 a.info.processName, pkg.applicationInfo.uid);
3017 mActivities.addActivity(a, "activity");
3018 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3019 if (r == null) {
3020 r = new StringBuilder(256);
3021 } else {
3022 r.append(' ');
3023 }
3024 r.append(a.info.name);
3025 }
3026 }
3027 if (r != null) {
3028 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 N = pkg.permissionGroups.size();
3032 r = null;
3033 for (i=0; i<N; i++) {
3034 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3035 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3036 if (cur == null) {
3037 mPermissionGroups.put(pg.info.name, pg);
3038 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3039 if (r == null) {
3040 r = new StringBuilder(256);
3041 } else {
3042 r.append(' ');
3043 }
3044 r.append(pg.info.name);
3045 }
3046 } else {
3047 Log.w(TAG, "Permission group " + pg.info.name + " from package "
3048 + pg.info.packageName + " ignored: original from "
3049 + cur.info.packageName);
3050 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3051 if (r == null) {
3052 r = new StringBuilder(256);
3053 } else {
3054 r.append(' ');
3055 }
3056 r.append("DUP:");
3057 r.append(pg.info.name);
3058 }
3059 }
3060 }
3061 if (r != null) {
3062 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 N = pkg.permissions.size();
3066 r = null;
3067 for (i=0; i<N; i++) {
3068 PackageParser.Permission p = pkg.permissions.get(i);
3069 HashMap<String, BasePermission> permissionMap =
3070 p.tree ? mSettings.mPermissionTrees
3071 : mSettings.mPermissions;
3072 p.group = mPermissionGroups.get(p.info.group);
3073 if (p.info.group == null || p.group != null) {
3074 BasePermission bp = permissionMap.get(p.info.name);
3075 if (bp == null) {
3076 bp = new BasePermission(p.info.name, p.info.packageName,
3077 BasePermission.TYPE_NORMAL);
3078 permissionMap.put(p.info.name, bp);
3079 }
3080 if (bp.perm == null) {
3081 if (bp.sourcePackage == null
3082 || bp.sourcePackage.equals(p.info.packageName)) {
3083 BasePermission tree = findPermissionTreeLP(p.info.name);
3084 if (tree == null
3085 || tree.sourcePackage.equals(p.info.packageName)) {
3086 bp.perm = p;
3087 bp.uid = pkg.applicationInfo.uid;
3088 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3089 if (r == null) {
3090 r = new StringBuilder(256);
3091 } else {
3092 r.append(' ');
3093 }
3094 r.append(p.info.name);
3095 }
3096 } else {
3097 Log.w(TAG, "Permission " + p.info.name + " from package "
3098 + p.info.packageName + " ignored: base tree "
3099 + tree.name + " is from package "
3100 + tree.sourcePackage);
3101 }
3102 } else {
3103 Log.w(TAG, "Permission " + p.info.name + " from package "
3104 + p.info.packageName + " ignored: original from "
3105 + bp.sourcePackage);
3106 }
3107 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3108 if (r == null) {
3109 r = new StringBuilder(256);
3110 } else {
3111 r.append(' ');
3112 }
3113 r.append("DUP:");
3114 r.append(p.info.name);
3115 }
3116 } else {
3117 Log.w(TAG, "Permission " + p.info.name + " from package "
3118 + p.info.packageName + " ignored: no group "
3119 + p.group);
3120 }
3121 }
3122 if (r != null) {
3123 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3124 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 N = pkg.instrumentation.size();
3127 r = null;
3128 for (i=0; i<N; i++) {
3129 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3130 a.info.packageName = pkg.applicationInfo.packageName;
3131 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3132 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3133 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003134 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3136 if (r == null) {
3137 r = new StringBuilder(256);
3138 } else {
3139 r.append(' ');
3140 }
3141 r.append(a.info.name);
3142 }
3143 }
3144 if (r != null) {
3145 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3146 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003147
Dianne Hackborn854060af2009-07-09 18:14:31 -07003148 if (pkg.protectedBroadcasts != null) {
3149 N = pkg.protectedBroadcasts.size();
3150 for (i=0; i<N; i++) {
3151 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3152 }
3153 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 pkgSetting.setTimeStamp(scanFileTime);
3156 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 return pkg;
3159 }
3160
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003161 private void killApplication(String pkgName, int uid) {
3162 // Request the ActivityManager to kill the process(only for existing packages)
3163 // so that we do not end up in a confused state while the user is still using the older
3164 // version of the application while the new one gets installed.
3165 IActivityManager am = ActivityManagerNative.getDefault();
3166 if (am != null) {
3167 try {
3168 am.killApplicationWithUid(pkgName, uid);
3169 } catch (RemoteException e) {
3170 }
3171 }
3172 }
3173
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003174 // The following constants are returned by cachePackageSharedLibsForAbiLI
3175 // to indicate if native shared libraries were found in the package.
3176 // Values are:
3177 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3178 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3179 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3180 // in package (and not installed)
3181 //
3182 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3183 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3184 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003186 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3187 // and automatically copy them to /data/data/<appname>/lib if present.
3188 //
3189 // NOTE: this method may throw an IOException if the library cannot
3190 // be copied to its final destination, e.g. if there isn't enough
3191 // room left on the data partition, or a ZipException if the package
3192 // file is malformed.
3193 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003194 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3195 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003196 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3197 final String apkLib = "lib/";
3198 final int apkLibLen = apkLib.length();
3199 final int cpuAbiLen = cpuAbi.length();
3200 final String libPrefix = "lib";
3201 final int libPrefixLen = libPrefix.length();
3202 final String libSuffix = ".so";
3203 final int libSuffixLen = libSuffix.length();
3204 boolean hasNativeLibraries = false;
3205 boolean installedNativeLibraries = false;
3206
3207 // the minimum length of a valid native shared library of the form
3208 // lib/<something>/lib<name>.so.
3209 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3210
3211 ZipFile zipFile = new ZipFile(scanFile);
3212 Enumeration<ZipEntry> entries =
3213 (Enumeration<ZipEntry>) zipFile.entries();
3214
3215 while (entries.hasMoreElements()) {
3216 ZipEntry entry = entries.nextElement();
3217 // skip directories
3218 if (entry.isDirectory()) {
3219 continue;
3220 }
3221 String entryName = entry.getName();
3222
3223 // check that the entry looks like lib/<something>/lib<name>.so
3224 // here, but don't check the ABI just yet.
3225 //
3226 // - must be sufficiently long
3227 // - must end with libSuffix, i.e. ".so"
3228 // - must start with apkLib, i.e. "lib/"
3229 if (entryName.length() < minEntryLen ||
3230 !entryName.endsWith(libSuffix) ||
3231 !entryName.startsWith(apkLib) ) {
3232 continue;
3233 }
3234
3235 // file name must start with libPrefix, i.e. "lib"
3236 int lastSlash = entryName.lastIndexOf('/');
3237
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003238 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003239 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3240 continue;
3241 }
3242
3243 hasNativeLibraries = true;
3244
3245 // check the cpuAbi now, between lib/ and /lib<name>.so
3246 //
3247 if (lastSlash != apkLibLen + cpuAbiLen ||
3248 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3249 continue;
3250
3251 // extract the library file name, ensure it doesn't contain
3252 // weird characters. we're guaranteed here that it doesn't contain
3253 // a directory separator though.
3254 String libFileName = entryName.substring(lastSlash+1);
3255 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3256 continue;
3257 }
3258
3259 installedNativeLibraries = true;
3260
3261 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3262 File.separator + libFileName;
3263 File sharedLibraryFile = new File(sharedLibraryFilePath);
3264 if (! sharedLibraryFile.exists() ||
3265 sharedLibraryFile.length() != entry.getSize() ||
3266 sharedLibraryFile.lastModified() != entry.getTime()) {
3267 if (Config.LOGD) {
3268 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003270 if (mInstaller == null) {
3271 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003272 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003273 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003274 sharedLibraryFile);
3275 }
3276 }
3277 if (!hasNativeLibraries)
3278 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3279
3280 if (!installedNativeLibraries)
3281 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3282
3283 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3284 }
3285
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003286 // Find the gdbserver executable program in a package at
3287 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3288 //
3289 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3290 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3291 //
3292 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3293 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3294 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3295 final String GDBSERVER = "gdbserver";
3296 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3297
3298 ZipFile zipFile = new ZipFile(scanFile);
3299 Enumeration<ZipEntry> entries =
3300 (Enumeration<ZipEntry>) zipFile.entries();
3301
3302 while (entries.hasMoreElements()) {
3303 ZipEntry entry = entries.nextElement();
3304 // skip directories
3305 if (entry.isDirectory()) {
3306 continue;
3307 }
3308 String entryName = entry.getName();
3309
3310 if (!entryName.equals(apkGdbServerPath)) {
3311 continue;
3312 }
3313
3314 String installGdbServerPath = installGdbServerDir.getPath() +
3315 "/" + GDBSERVER;
3316 File installGdbServerFile = new File(installGdbServerPath);
3317 if (! installGdbServerFile.exists() ||
3318 installGdbServerFile.length() != entry.getSize() ||
3319 installGdbServerFile.lastModified() != entry.getTime()) {
3320 if (Config.LOGD) {
3321 Log.d(TAG, "Caching gdbserver " + entry.getName());
3322 }
3323 if (mInstaller == null) {
3324 installGdbServerDir.mkdir();
3325 }
3326 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3327 installGdbServerFile);
3328 }
3329 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3330 }
3331 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3332 }
3333
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003334 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3335 // and copy them to /data/data/<appname>/lib.
3336 //
3337 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3338 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3339 // one if ro.product.cpu.abi2 is defined.
3340 //
3341 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3342 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003343 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003344 try {
3345 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3346
3347 // some architectures are capable of supporting several CPU ABIs
3348 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3349 // this is indicated by the definition of the ro.product.cpu.abi2
3350 // system property.
3351 //
3352 // only scan the package twice in case of ABI mismatch
3353 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003354 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003355 if (cpuAbi2 != null) {
3356 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003358
3359 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3360 Log.w(TAG,"Native ABI mismatch from package file");
3361 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003362 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003363
3364 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3365 cpuAbi = cpuAbi2;
3366 }
3367 }
3368
3369 // for debuggable packages, also extract gdbserver from lib/<abi>
3370 // into /data/data/<appname>/lib too.
3371 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3372 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3373 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3374 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3375 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003378 } catch (ZipException e) {
3379 Log.w(TAG, "Failed to extract data from package file", e);
3380 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003382 Log.w(TAG, "Failed to cache package shared libs", e);
3383 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003385 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 }
3387
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003388 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003390 File binaryDir,
3391 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 InputStream inputStream = zipFile.getInputStream(entry);
3393 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003394 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003396 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 // now need to be left as world readable and owned by the system.
3398 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3399 ! tempFile.setLastModified(entry.getTime()) ||
3400 FileUtils.setPermissions(tempFilePath,
3401 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003402 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003404 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 // Failed to properly write file.
3406 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003407 throw new IOException("Couldn't create cached binary "
3408 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 }
3410 } finally {
3411 inputStream.close();
3412 }
3413 }
3414
3415 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3416 if (chatty && Config.LOGD) Log.d(
3417 TAG, "Removing package " + pkg.applicationInfo.packageName );
3418
3419 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 mPackages.remove(pkg.applicationInfo.packageName);
3423 if (pkg.mPath != null) {
3424 mAppDirs.remove(pkg.mPath);
3425 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 PackageSetting ps = (PackageSetting)pkg.mExtras;
3428 if (ps != null && ps.sharedUser != null) {
3429 // XXX don't do this until the data is removed.
3430 if (false) {
3431 ps.sharedUser.packages.remove(ps);
3432 if (ps.sharedUser.packages.size() == 0) {
3433 // Remove.
3434 }
3435 }
3436 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 int N = pkg.providers.size();
3439 StringBuilder r = null;
3440 int i;
3441 for (i=0; i<N; i++) {
3442 PackageParser.Provider p = pkg.providers.get(i);
3443 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3444 p.info.name));
3445 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 /* The is another ContentProvider with this authority when
3448 * this app was installed so this authority is null,
3449 * Ignore it as we don't have to unregister the provider.
3450 */
3451 continue;
3452 }
3453 String names[] = p.info.authority.split(";");
3454 for (int j = 0; j < names.length; j++) {
3455 if (mProviders.get(names[j]) == p) {
3456 mProviders.remove(names[j]);
3457 if (chatty && Config.LOGD) Log.d(
3458 TAG, "Unregistered content provider: " + names[j] +
3459 ", className = " + p.info.name +
3460 ", isSyncable = " + p.info.isSyncable);
3461 }
3462 }
3463 if (chatty) {
3464 if (r == null) {
3465 r = new StringBuilder(256);
3466 } else {
3467 r.append(' ');
3468 }
3469 r.append(p.info.name);
3470 }
3471 }
3472 if (r != null) {
3473 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3474 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 N = pkg.services.size();
3477 r = null;
3478 for (i=0; i<N; i++) {
3479 PackageParser.Service s = pkg.services.get(i);
3480 mServices.removeService(s);
3481 if (chatty) {
3482 if (r == null) {
3483 r = new StringBuilder(256);
3484 } else {
3485 r.append(' ');
3486 }
3487 r.append(s.info.name);
3488 }
3489 }
3490 if (r != null) {
3491 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3492 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 N = pkg.receivers.size();
3495 r = null;
3496 for (i=0; i<N; i++) {
3497 PackageParser.Activity a = pkg.receivers.get(i);
3498 mReceivers.removeActivity(a, "receiver");
3499 if (chatty) {
3500 if (r == null) {
3501 r = new StringBuilder(256);
3502 } else {
3503 r.append(' ');
3504 }
3505 r.append(a.info.name);
3506 }
3507 }
3508 if (r != null) {
3509 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 N = pkg.activities.size();
3513 r = null;
3514 for (i=0; i<N; i++) {
3515 PackageParser.Activity a = pkg.activities.get(i);
3516 mActivities.removeActivity(a, "activity");
3517 if (chatty) {
3518 if (r == null) {
3519 r = new StringBuilder(256);
3520 } else {
3521 r.append(' ');
3522 }
3523 r.append(a.info.name);
3524 }
3525 }
3526 if (r != null) {
3527 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3528 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 N = pkg.permissions.size();
3531 r = null;
3532 for (i=0; i<N; i++) {
3533 PackageParser.Permission p = pkg.permissions.get(i);
3534 boolean tree = false;
3535 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3536 if (bp == null) {
3537 tree = true;
3538 bp = mSettings.mPermissionTrees.get(p.info.name);
3539 }
3540 if (bp != null && bp.perm == p) {
3541 if (bp.type != BasePermission.TYPE_BUILTIN) {
3542 if (tree) {
3543 mSettings.mPermissionTrees.remove(p.info.name);
3544 } else {
3545 mSettings.mPermissions.remove(p.info.name);
3546 }
3547 } else {
3548 bp.perm = null;
3549 }
3550 if (chatty) {
3551 if (r == null) {
3552 r = new StringBuilder(256);
3553 } else {
3554 r.append(' ');
3555 }
3556 r.append(p.info.name);
3557 }
3558 }
3559 }
3560 if (r != null) {
3561 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3562 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003564 N = pkg.instrumentation.size();
3565 r = null;
3566 for (i=0; i<N; i++) {
3567 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003568 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 if (chatty) {
3570 if (r == null) {
3571 r = new StringBuilder(256);
3572 } else {
3573 r.append(' ');
3574 }
3575 r.append(a.info.name);
3576 }
3577 }
3578 if (r != null) {
3579 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3580 }
3581 }
3582 }
3583
3584 private static final boolean isPackageFilename(String name) {
3585 return name != null && name.endsWith(".apk");
3586 }
3587
3588 private void updatePermissionsLP() {
3589 // Make sure there are no dangling permission trees.
3590 Iterator<BasePermission> it = mSettings.mPermissionTrees
3591 .values().iterator();
3592 while (it.hasNext()) {
3593 BasePermission bp = it.next();
3594 if (bp.perm == null) {
3595 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3596 + " from package " + bp.sourcePackage);
3597 it.remove();
3598 }
3599 }
3600
3601 // Make sure all dynamic permissions have been assigned to a package,
3602 // and make sure there are no dangling permissions.
3603 it = mSettings.mPermissions.values().iterator();
3604 while (it.hasNext()) {
3605 BasePermission bp = it.next();
3606 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3607 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3608 + bp.name + " pkg=" + bp.sourcePackage
3609 + " info=" + bp.pendingInfo);
3610 if (bp.perm == null && bp.pendingInfo != null) {
3611 BasePermission tree = findPermissionTreeLP(bp.name);
3612 if (tree != null) {
3613 bp.perm = new PackageParser.Permission(tree.perm.owner,
3614 new PermissionInfo(bp.pendingInfo));
3615 bp.perm.info.packageName = tree.perm.info.packageName;
3616 bp.perm.info.name = bp.name;
3617 bp.uid = tree.uid;
3618 }
3619 }
3620 }
3621 if (bp.perm == null) {
3622 Log.w(TAG, "Removing dangling permission: " + bp.name
3623 + " from package " + bp.sourcePackage);
3624 it.remove();
3625 }
3626 }
3627
3628 // Now update the permissions for all packages, in particular
3629 // replace the granted permissions of the system packages.
3630 for (PackageParser.Package pkg : mPackages.values()) {
3631 grantPermissionsLP(pkg, false);
3632 }
3633 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3636 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3637 if (ps == null) {
3638 return;
3639 }
3640 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3641 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 if (replace) {
3644 ps.permissionsFixed = false;
3645 if (gp == ps) {
3646 gp.grantedPermissions.clear();
3647 gp.gids = mGlobalGids;
3648 }
3649 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 if (gp.gids == null) {
3652 gp.gids = mGlobalGids;
3653 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 final int N = pkg.requestedPermissions.size();
3656 for (int i=0; i<N; i++) {
3657 String name = pkg.requestedPermissions.get(i);
3658 BasePermission bp = mSettings.mPermissions.get(name);
3659 PackageParser.Permission p = bp != null ? bp.perm : null;
3660 if (false) {
3661 if (gp != ps) {
3662 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3663 + ": " + p);
3664 }
3665 }
3666 if (p != null) {
3667 final String perm = p.info.name;
3668 boolean allowed;
3669 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3670 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3671 allowed = true;
3672 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3673 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003674 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003676 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 == PackageManager.SIGNATURE_MATCH);
3678 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3679 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3680 // For updated system applications, the signatureOrSystem permission
3681 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003682 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3684 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3685 if(sysPs.grantedPermissions.contains(perm)) {
3686 allowed = true;
3687 } else {
3688 allowed = false;
3689 }
3690 } else {
3691 allowed = true;
3692 }
3693 }
3694 }
3695 } else {
3696 allowed = false;
3697 }
3698 if (false) {
3699 if (gp != ps) {
3700 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3701 }
3702 }
3703 if (allowed) {
3704 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3705 && ps.permissionsFixed) {
3706 // If this is an existing, non-system package, then
3707 // we can't add any new permissions to it.
3708 if (!gp.loadedPermissions.contains(perm)) {
3709 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003710 // Except... if this is a permission that was added
3711 // to the platform (note: need to only do this when
3712 // updating the platform).
3713 final int NP = PackageParser.NEW_PERMISSIONS.length;
3714 for (int ip=0; ip<NP; ip++) {
3715 final PackageParser.NewPermissionInfo npi
3716 = PackageParser.NEW_PERMISSIONS[ip];
3717 if (npi.name.equals(perm)
3718 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3719 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003720 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003721 + pkg.packageName);
3722 break;
3723 }
3724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003725 }
3726 }
3727 if (allowed) {
3728 if (!gp.grantedPermissions.contains(perm)) {
3729 addedPermission = true;
3730 gp.grantedPermissions.add(perm);
3731 gp.gids = appendInts(gp.gids, bp.gids);
3732 }
3733 } else {
3734 Log.w(TAG, "Not granting permission " + perm
3735 + " to package " + pkg.packageName
3736 + " because it was previously installed without");
3737 }
3738 } else {
3739 Log.w(TAG, "Not granting permission " + perm
3740 + " to package " + pkg.packageName
3741 + " (protectionLevel=" + p.info.protectionLevel
3742 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3743 + ")");
3744 }
3745 } else {
3746 Log.w(TAG, "Unknown permission " + name
3747 + " in package " + pkg.packageName);
3748 }
3749 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003752 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3753 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 // This is the first that we have heard about this package, so the
3755 // permissions we have now selected are fixed until explicitly
3756 // changed.
3757 ps.permissionsFixed = true;
3758 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3759 }
3760 }
3761
3762 private final class ActivityIntentResolver
3763 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003764 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003766 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 }
3768
Mihai Preda074edef2009-05-18 17:13:31 +02003769 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003771 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3773 }
3774
Mihai Predaeae850c2009-05-13 10:13:48 +02003775 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3776 ArrayList<PackageParser.Activity> packageActivities) {
3777 if (packageActivities == null) {
3778 return null;
3779 }
3780 mFlags = flags;
3781 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3782 int N = packageActivities.size();
3783 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3784 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003785
3786 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003787 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003788 intentFilters = packageActivities.get(i).intents;
3789 if (intentFilters != null && intentFilters.size() > 0) {
3790 listCut.add(intentFilters);
3791 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003792 }
3793 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3794 }
3795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003797 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 if (SHOW_INFO || Config.LOGV) Log.v(
3799 TAG, " " + type + " " +
3800 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3801 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3802 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003803 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3805 if (SHOW_INFO || Config.LOGV) {
3806 Log.v(TAG, " IntentFilter:");
3807 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3808 }
3809 if (!intent.debugCheck()) {
3810 Log.w(TAG, "==> For Activity " + a.info.name);
3811 }
3812 addFilter(intent);
3813 }
3814 }
3815
3816 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003817 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818 if (SHOW_INFO || Config.LOGV) Log.v(
3819 TAG, " " + type + " " +
3820 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3821 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3822 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003823 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3825 if (SHOW_INFO || Config.LOGV) {
3826 Log.v(TAG, " IntentFilter:");
3827 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3828 }
3829 removeFilter(intent);
3830 }
3831 }
3832
3833 @Override
3834 protected boolean allowFilterResult(
3835 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3836 ActivityInfo filterAi = filter.activity.info;
3837 for (int i=dest.size()-1; i>=0; i--) {
3838 ActivityInfo destAi = dest.get(i).activityInfo;
3839 if (destAi.name == filterAi.name
3840 && destAi.packageName == filterAi.packageName) {
3841 return false;
3842 }
3843 }
3844 return true;
3845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 @Override
3848 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3849 int match) {
3850 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3851 return null;
3852 }
3853 final PackageParser.Activity activity = info.activity;
3854 if (mSafeMode && (activity.info.applicationInfo.flags
3855 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3856 return null;
3857 }
3858 final ResolveInfo res = new ResolveInfo();
3859 res.activityInfo = PackageParser.generateActivityInfo(activity,
3860 mFlags);
3861 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3862 res.filter = info;
3863 }
3864 res.priority = info.getPriority();
3865 res.preferredOrder = activity.owner.mPreferredOrder;
3866 //System.out.println("Result: " + res.activityInfo.className +
3867 // " = " + res.priority);
3868 res.match = match;
3869 res.isDefault = info.hasDefault;
3870 res.labelRes = info.labelRes;
3871 res.nonLocalizedLabel = info.nonLocalizedLabel;
3872 res.icon = info.icon;
3873 return res;
3874 }
3875
3876 @Override
3877 protected void sortResults(List<ResolveInfo> results) {
3878 Collections.sort(results, mResolvePrioritySorter);
3879 }
3880
3881 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003882 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003884 out.print(prefix); out.print(
3885 Integer.toHexString(System.identityHashCode(filter.activity)));
3886 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003887 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 }
3889
3890// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3891// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3892// final List<ResolveInfo> retList = Lists.newArrayList();
3893// while (i.hasNext()) {
3894// final ResolveInfo resolveInfo = i.next();
3895// if (isEnabledLP(resolveInfo.activityInfo)) {
3896// retList.add(resolveInfo);
3897// }
3898// }
3899// return retList;
3900// }
3901
3902 // Keys are String (activity class name), values are Activity.
3903 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3904 = new HashMap<ComponentName, PackageParser.Activity>();
3905 private int mFlags;
3906 }
3907
3908 private final class ServiceIntentResolver
3909 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003910 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003912 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 }
3914
Mihai Preda074edef2009-05-18 17:13:31 +02003915 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003917 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3919 }
3920
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003921 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3922 ArrayList<PackageParser.Service> packageServices) {
3923 if (packageServices == null) {
3924 return null;
3925 }
3926 mFlags = flags;
3927 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3928 int N = packageServices.size();
3929 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3930 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3931
3932 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3933 for (int i = 0; i < N; ++i) {
3934 intentFilters = packageServices.get(i).intents;
3935 if (intentFilters != null && intentFilters.size() > 0) {
3936 listCut.add(intentFilters);
3937 }
3938 }
3939 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3940 }
3941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003943 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 if (SHOW_INFO || Config.LOGV) Log.v(
3945 TAG, " " + (s.info.nonLocalizedLabel != null
3946 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3947 if (SHOW_INFO || Config.LOGV) Log.v(
3948 TAG, " Class=" + s.info.name);
3949 int NI = s.intents.size();
3950 int j;
3951 for (j=0; j<NI; j++) {
3952 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3953 if (SHOW_INFO || Config.LOGV) {
3954 Log.v(TAG, " IntentFilter:");
3955 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3956 }
3957 if (!intent.debugCheck()) {
3958 Log.w(TAG, "==> For Service " + s.info.name);
3959 }
3960 addFilter(intent);
3961 }
3962 }
3963
3964 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003965 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 if (SHOW_INFO || Config.LOGV) Log.v(
3967 TAG, " " + (s.info.nonLocalizedLabel != null
3968 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3969 if (SHOW_INFO || Config.LOGV) Log.v(
3970 TAG, " Class=" + s.info.name);
3971 int NI = s.intents.size();
3972 int j;
3973 for (j=0; j<NI; j++) {
3974 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3975 if (SHOW_INFO || Config.LOGV) {
3976 Log.v(TAG, " IntentFilter:");
3977 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3978 }
3979 removeFilter(intent);
3980 }
3981 }
3982
3983 @Override
3984 protected boolean allowFilterResult(
3985 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3986 ServiceInfo filterSi = filter.service.info;
3987 for (int i=dest.size()-1; i>=0; i--) {
3988 ServiceInfo destAi = dest.get(i).serviceInfo;
3989 if (destAi.name == filterSi.name
3990 && destAi.packageName == filterSi.packageName) {
3991 return false;
3992 }
3993 }
3994 return true;
3995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 @Override
3998 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3999 int match) {
4000 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4001 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4002 return null;
4003 }
4004 final PackageParser.Service service = info.service;
4005 if (mSafeMode && (service.info.applicationInfo.flags
4006 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4007 return null;
4008 }
4009 final ResolveInfo res = new ResolveInfo();
4010 res.serviceInfo = PackageParser.generateServiceInfo(service,
4011 mFlags);
4012 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4013 res.filter = filter;
4014 }
4015 res.priority = info.getPriority();
4016 res.preferredOrder = service.owner.mPreferredOrder;
4017 //System.out.println("Result: " + res.activityInfo.className +
4018 // " = " + res.priority);
4019 res.match = match;
4020 res.isDefault = info.hasDefault;
4021 res.labelRes = info.labelRes;
4022 res.nonLocalizedLabel = info.nonLocalizedLabel;
4023 res.icon = info.icon;
4024 return res;
4025 }
4026
4027 @Override
4028 protected void sortResults(List<ResolveInfo> results) {
4029 Collections.sort(results, mResolvePrioritySorter);
4030 }
4031
4032 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004033 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004035 out.print(prefix); out.print(
4036 Integer.toHexString(System.identityHashCode(filter.service)));
4037 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004038 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 }
4040
4041// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4042// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4043// final List<ResolveInfo> retList = Lists.newArrayList();
4044// while (i.hasNext()) {
4045// final ResolveInfo resolveInfo = (ResolveInfo) i;
4046// if (isEnabledLP(resolveInfo.serviceInfo)) {
4047// retList.add(resolveInfo);
4048// }
4049// }
4050// return retList;
4051// }
4052
4053 // Keys are String (activity class name), values are Activity.
4054 private final HashMap<ComponentName, PackageParser.Service> mServices
4055 = new HashMap<ComponentName, PackageParser.Service>();
4056 private int mFlags;
4057 };
4058
4059 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4060 new Comparator<ResolveInfo>() {
4061 public int compare(ResolveInfo r1, ResolveInfo r2) {
4062 int v1 = r1.priority;
4063 int v2 = r2.priority;
4064 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4065 if (v1 != v2) {
4066 return (v1 > v2) ? -1 : 1;
4067 }
4068 v1 = r1.preferredOrder;
4069 v2 = r2.preferredOrder;
4070 if (v1 != v2) {
4071 return (v1 > v2) ? -1 : 1;
4072 }
4073 if (r1.isDefault != r2.isDefault) {
4074 return r1.isDefault ? -1 : 1;
4075 }
4076 v1 = r1.match;
4077 v2 = r2.match;
4078 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4079 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4080 }
4081 };
4082
4083 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4084 new Comparator<ProviderInfo>() {
4085 public int compare(ProviderInfo p1, ProviderInfo p2) {
4086 final int v1 = p1.initOrder;
4087 final int v2 = p2.initOrder;
4088 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4089 }
4090 };
4091
4092 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4093 IActivityManager am = ActivityManagerNative.getDefault();
4094 if (am != null) {
4095 try {
4096 final Intent intent = new Intent(action,
4097 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4098 if (extras != null) {
4099 intent.putExtras(extras);
4100 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004101 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 am.broadcastIntent(
4103 null, intent,
4104 null, null, 0, null, null, null, false, false);
4105 } catch (RemoteException ex) {
4106 }
4107 }
4108 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004109
4110 public String nextPackageToClean(String lastPackage) {
4111 synchronized (mPackages) {
4112 if (!mMediaMounted) {
4113 // If the external storage is no longer mounted at this point,
4114 // the caller may not have been able to delete all of this
4115 // packages files and can not delete any more. Bail.
4116 return null;
4117 }
4118 if (lastPackage != null) {
4119 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4120 }
4121 return mSettings.mPackagesToBeCleaned.size() > 0
4122 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4123 }
4124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004126 void schedulePackageCleaning(String packageName) {
4127 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4128 }
4129
4130 void startCleaningPackages() {
4131 synchronized (mPackages) {
4132 if (!mMediaMounted) {
4133 return;
4134 }
4135 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4136 return;
4137 }
4138 }
4139 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4140 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4141 IActivityManager am = ActivityManagerNative.getDefault();
4142 if (am != null) {
4143 try {
4144 am.startService(null, intent, null);
4145 } catch (RemoteException e) {
4146 }
4147 }
4148 }
4149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 private final class AppDirObserver extends FileObserver {
4151 public AppDirObserver(String path, int mask, boolean isrom) {
4152 super(path, mask);
4153 mRootDir = path;
4154 mIsRom = isrom;
4155 }
4156
4157 public void onEvent(int event, String path) {
4158 String removedPackage = null;
4159 int removedUid = -1;
4160 String addedPackage = null;
4161 int addedUid = -1;
4162
4163 synchronized (mInstallLock) {
4164 String fullPathStr = null;
4165 File fullPath = null;
4166 if (path != null) {
4167 fullPath = new File(mRootDir, path);
4168 fullPathStr = fullPath.getPath();
4169 }
4170
4171 if (Config.LOGV) Log.v(
4172 TAG, "File " + fullPathStr + " changed: "
4173 + Integer.toHexString(event));
4174
4175 if (!isPackageFilename(path)) {
4176 if (Config.LOGV) Log.v(
4177 TAG, "Ignoring change of non-package file: " + fullPathStr);
4178 return;
4179 }
4180
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004181 // Ignore packages that are being installed or
4182 // have just been installed.
4183 if (ignoreCodePath(fullPathStr)) {
4184 return;
4185 }
4186 PackageParser.Package p = null;
4187 synchronized (mPackages) {
4188 p = mAppDirs.get(fullPathStr);
4189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004191 if (p != null) {
4192 removePackageLI(p, true);
4193 removedPackage = p.applicationInfo.packageName;
4194 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004195 }
4196 }
4197
4198 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004200 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4202 PackageParser.PARSE_CHATTY |
4203 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004204 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 if (p != null) {
4206 synchronized (mPackages) {
4207 grantPermissionsLP(p, false);
4208 }
4209 addedPackage = p.applicationInfo.packageName;
4210 addedUid = p.applicationInfo.uid;
4211 }
4212 }
4213 }
4214
4215 synchronized (mPackages) {
4216 mSettings.writeLP();
4217 }
4218 }
4219
4220 if (removedPackage != null) {
4221 Bundle extras = new Bundle(1);
4222 extras.putInt(Intent.EXTRA_UID, removedUid);
4223 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4224 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4225 }
4226 if (addedPackage != null) {
4227 Bundle extras = new Bundle(1);
4228 extras.putInt(Intent.EXTRA_UID, addedUid);
4229 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4230 }
4231 }
4232
4233 private final String mRootDir;
4234 private final boolean mIsRom;
4235 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 /* Called when a downloaded package installation has been confirmed by the user */
4238 public void installPackage(
4239 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004240 installPackage(packageURI, observer, flags, null);
4241 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004242
Jacek Surazski65e13172009-04-28 15:26:38 +02004243 /* Called when a downloaded package installation has been confirmed by the user */
4244 public void installPackage(
4245 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4246 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 mContext.enforceCallingOrSelfPermission(
4248 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004249
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004250 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004251 msg.obj = new InstallParams(packageURI, observer, flags,
4252 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004253 mHandler.sendMessage(msg);
4254 }
4255
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004256 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004257 // Queue up an async operation since the package installation may take a little while.
4258 mHandler.post(new Runnable() {
4259 public void run() {
4260 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004261 // Result object to be returned
4262 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004263 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004264 res.uid = -1;
4265 res.pkg = null;
4266 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004267 args.doPreInstall(res.returnCode);
4268 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004269 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004270 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004271 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004272 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004274 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
4275 // call appears in the synchronized block above.
4276 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4277 res.removedInfo.sendBroadcast(false, true);
4278 Bundle extras = new Bundle(1);
4279 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004280 final boolean update = res.removedInfo.removedPackage != null;
4281 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4283 }
4284 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
4285 res.pkg.applicationInfo.packageName,
4286 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004287 if (update) {
4288 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
4289 res.pkg.applicationInfo.packageName,
4290 extras);
4291 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004292 if (res.removedInfo.args != null) {
4293 // Remove the replaced package's older resources safely now
4294 synchronized (mInstallLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004295 res.removedInfo.args.doPostDeleteLI(true);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004296 }
4297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004298 }
4299 Runtime.getRuntime().gc();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004300 if (args.observer != null) {
4301 try {
4302 args.observer.packageInstalled(res.name, res.returnCode);
4303 } catch (RemoteException e) {
4304 Log.i(TAG, "Observer no longer exists.");
4305 }
4306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 }
4308 });
4309 }
4310
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004311 interface HandlerParams {
4312 void handleStartCopy(IMediaContainerService imcs);
4313 void handleServiceError();
4314 }
4315
4316 class InstallParams implements HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004317 final IPackageInstallObserver observer;
4318 int flags;
4319 final Uri packageURI;
4320 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004321 private InstallArgs mArgs;
4322 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004323 InstallParams(Uri packageURI,
4324 IPackageInstallObserver observer, int flags,
4325 String installerPackageName) {
4326 this.packageURI = packageURI;
4327 this.flags = flags;
4328 this.observer = observer;
4329 this.installerPackageName = installerPackageName;
4330 }
4331
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004332 private int getInstallLocation(IMediaContainerService imcs) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004333 try {
4334 return imcs.getRecommendedInstallLocation(packageURI);
4335 } catch (RemoteException e) {
4336 }
4337 return -1;
4338 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004339
4340 public void handleStartCopy(IMediaContainerService imcs) {
4341 int ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4342 if (imcs != null) {
4343 // Remote call to find out default install location
4344 int loc = getInstallLocation(imcs);
4345 // Use install location to create InstallArgs and temporary
4346 // install location
4347 if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
4348 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4349 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4350 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
4351 } else {
4352 if ((flags & PackageManager.INSTALL_EXTERNAL) == 0){
4353 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4354 // Set the flag to install on external media.
4355 flags |= PackageManager.INSTALL_EXTERNAL;
4356 } else {
4357 // Make sure the flag for installing on external
4358 // media is unset
4359 flags &= ~PackageManager.INSTALL_EXTERNAL;
4360 }
4361 }
4362 // Disable forward locked apps on sdcard.
4363 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0 &&
4364 (flags & PackageManager.INSTALL_EXTERNAL) != 0) {
4365 // Make sure forward locked apps can only be installed
4366 // on internal storage
4367 Log.w(TAG, "Cannot install protected apps on sdcard");
4368 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4369 } else {
4370 ret = PackageManager.INSTALL_SUCCEEDED;
4371 }
4372 }
4373 }
4374 // Create the file args now.
4375 mArgs = createInstallArgs(this);
4376 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4377 // Create copy only if we are not in an erroneous state.
4378 // Remote call to initiate copy using temporary file
4379 ret = mArgs.copyApk(imcs, true);
4380 }
4381 mRet = ret;
4382 mHandler.sendEmptyMessage(MCS_UNBIND);
4383 handleReturnCode();
4384 }
4385
4386 void handleReturnCode() {
4387 processPendingInstall(mArgs, mRet);
4388 }
4389
4390 public void handleServiceError() {
4391 mArgs = createInstallArgs(this);
4392 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4393 handleReturnCode();
4394 }
4395 };
4396
4397 /*
4398 * Utility class used in movePackage api.
4399 * srcArgs and targetArgs are not set for invalid flags and make
4400 * sure to do null checks when invoking methods on them.
4401 * We probably want to return ErrorPrams for both failed installs
4402 * and moves.
4403 */
4404 class MoveParams implements HandlerParams {
4405 final IPackageMoveObserver observer;
4406 final int flags;
4407 final String packageName;
4408 final InstallArgs srcArgs;
4409 final InstallArgs targetArgs;
4410 int mRet;
4411 MoveParams(InstallArgs srcArgs,
4412 IPackageMoveObserver observer,
4413 int flags, String packageName) {
4414 this.srcArgs = srcArgs;
4415 this.observer = observer;
4416 this.flags = flags;
4417 this.packageName = packageName;
4418 if (srcArgs != null) {
4419 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4420 targetArgs = createInstallArgs(packageUri, flags, packageName);
4421 } else {
4422 targetArgs = null;
4423 }
4424 }
4425
4426 public void handleStartCopy(IMediaContainerService imcs) {
4427 // Create the file args now.
4428 mRet = targetArgs.copyApk(imcs, false);
4429 targetArgs.doPreInstall(mRet);
4430 mHandler.sendEmptyMessage(MCS_UNBIND);
4431 handleReturnCode();
4432 }
4433
4434 void handleReturnCode() {
4435 targetArgs.doPostInstall(mRet);
4436 // TODO invoke pending move
4437 processPendingMove(this, mRet);
4438 }
4439
4440 public void handleServiceError() {
4441 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4442 handleReturnCode();
4443 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004444 };
4445
4446 private InstallArgs createInstallArgs(InstallParams params) {
4447 if (installOnSd(params.flags)) {
4448 return new SdInstallArgs(params);
4449 } else {
4450 return new FileInstallArgs(params);
4451 }
4452 }
4453
4454 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4455 if (installOnSd(flags)) {
4456 return new SdInstallArgs(fullCodePath, fullResourcePath);
4457 } else {
4458 return new FileInstallArgs(fullCodePath, fullResourcePath);
4459 }
4460 }
4461
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004462 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4463 if (installOnSd(flags)) {
4464 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4465 return new SdInstallArgs(packageURI, cid);
4466 } else {
4467 return new FileInstallArgs(packageURI, pkgName);
4468 }
4469 }
4470
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004471 static abstract class InstallArgs {
4472 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004473 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004474 final int flags;
4475 final Uri packageURI;
4476 final String installerPackageName;
4477
4478 InstallArgs(Uri packageURI,
4479 IPackageInstallObserver observer, int flags,
4480 String installerPackageName) {
4481 this.packageURI = packageURI;
4482 this.flags = flags;
4483 this.observer = observer;
4484 this.installerPackageName = installerPackageName;
4485 }
4486
4487 abstract void createCopyFile();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004488 abstract int copyApk(IMediaContainerService imcs, boolean temp);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004489 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004490 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004491 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004492 abstract String getCodePath();
4493 abstract String getResourcePath();
4494 // Need installer lock especially for dex file removal.
4495 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004496 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004497 }
4498
4499 class FileInstallArgs extends InstallArgs {
4500 File installDir;
4501 String codeFileName;
4502 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004503 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004504
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004505 FileInstallArgs(InstallParams params) {
4506 super(params.packageURI, params.observer,
4507 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004508 }
4509
4510 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4511 super(null, null, 0, null);
4512 File codeFile = new File(fullCodePath);
4513 installDir = codeFile.getParentFile();
4514 codeFileName = fullCodePath;
4515 resourceFileName = fullResourcePath;
4516 }
4517
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004518 FileInstallArgs(Uri packageURI, String pkgName) {
4519 super(packageURI, null, 0, null);
4520 boolean fwdLocked = isFwdLocked(flags);
4521 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4522 String apkName = getNextCodePath(null, pkgName, ".apk");
4523 codeFileName = new File(installDir, apkName + ".apk").getPath();
4524 resourceFileName = getResourcePathFromCodePath();
4525 }
4526
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004527 String getCodePath() {
4528 return codeFileName;
4529 }
4530
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004531 void createCopyFile() {
4532 boolean fwdLocked = isFwdLocked(flags);
4533 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4534 codeFileName = createTempPackageFile(installDir).getPath();
4535 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004536 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004537 }
4538
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004539 int copyApk(IMediaContainerService imcs, boolean temp) {
4540 if (temp) {
4541 // Generate temp file name
4542 createCopyFile();
4543 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004544 // Get a ParcelFileDescriptor to write to the output file
4545 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004546 if (!created) {
4547 try {
4548 codeFile.createNewFile();
4549 // Set permissions
4550 if (!setPermissions()) {
4551 // Failed setting permissions.
4552 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4553 }
4554 } catch (IOException e) {
4555 Log.w(TAG, "Failed to create file " + codeFile);
4556 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4557 }
4558 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004559 ParcelFileDescriptor out = null;
4560 try {
4561 out = ParcelFileDescriptor.open(codeFile,
4562 ParcelFileDescriptor.MODE_READ_WRITE);
4563 } catch (FileNotFoundException e) {
4564 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4565 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4566 }
4567 // Copy the resource now
4568 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4569 try {
4570 if (imcs.copyResource(packageURI, out)) {
4571 ret = PackageManager.INSTALL_SUCCEEDED;
4572 }
4573 } catch (RemoteException e) {
4574 } finally {
4575 try { if (out != null) out.close(); } catch (IOException e) {}
4576 }
4577 return ret;
4578 }
4579
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004580 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004581 if (status != PackageManager.INSTALL_SUCCEEDED) {
4582 cleanUp();
4583 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004584 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004585 }
4586
4587 boolean doRename(int status, final String pkgName, String oldCodePath) {
4588 if (status != PackageManager.INSTALL_SUCCEEDED) {
4589 cleanUp();
4590 return false;
4591 } else {
4592 // Rename based on packageName
4593 File codeFile = new File(getCodePath());
4594 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4595 File desFile = new File(installDir, apkName + ".apk");
4596 if (!codeFile.renameTo(desFile)) {
4597 return false;
4598 }
4599 // Reset paths since the file has been renamed.
4600 codeFileName = desFile.getPath();
4601 resourceFileName = getResourcePathFromCodePath();
4602 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004603 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004604 // Failed setting permissions.
4605 return false;
4606 }
4607 return true;
4608 }
4609 }
4610
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004611 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004612 if (status != PackageManager.INSTALL_SUCCEEDED) {
4613 cleanUp();
4614 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004615 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004616 }
4617
4618 String getResourcePath() {
4619 return resourceFileName;
4620 }
4621
4622 String getResourcePathFromCodePath() {
4623 String codePath = getCodePath();
4624 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4625 String apkNameOnly = getApkName(codePath);
4626 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4627 } else {
4628 return codePath;
4629 }
4630 }
4631
4632 private boolean cleanUp() {
4633 boolean ret = true;
4634 String sourceDir = getCodePath();
4635 String publicSourceDir = getResourcePath();
4636 if (sourceDir != null) {
4637 File sourceFile = new File(sourceDir);
4638 if (!sourceFile.exists()) {
4639 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4640 ret = false;
4641 }
4642 // Delete application's code and resources
4643 sourceFile.delete();
4644 }
4645 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4646 final File publicSourceFile = new File(publicSourceDir);
4647 if (!publicSourceFile.exists()) {
4648 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4649 }
4650 if (publicSourceFile.exists()) {
4651 publicSourceFile.delete();
4652 }
4653 }
4654 return ret;
4655 }
4656
4657 void cleanUpResourcesLI() {
4658 String sourceDir = getCodePath();
4659 if (cleanUp() && mInstaller != null) {
4660 int retCode = mInstaller.rmdex(sourceDir);
4661 if (retCode < 0) {
4662 Log.w(TAG, "Couldn't remove dex file for package: "
4663 + " at location "
4664 + sourceDir + ", retcode=" + retCode);
4665 // we don't consider this to be a failure of the core package deletion
4666 }
4667 }
4668 }
4669
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004670 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004671 // TODO Do this in a more elegant way later on. for now just a hack
4672 if (!isFwdLocked(flags)) {
4673 final int filePermissions =
4674 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4675 |FileUtils.S_IROTH;
4676 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4677 if (retCode != 0) {
4678 Log.e(TAG, "Couldn't set new package file permissions for " +
4679 getCodePath()
4680 + ". The return code was: " + retCode);
4681 // TODO Define new internal error
4682 return false;
4683 }
4684 return true;
4685 }
4686 return true;
4687 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004688
4689 boolean doPostDeleteLI(boolean delete) {
4690 cleanUpResourcesLI();
4691 return true;
4692 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004693 }
4694
4695 class SdInstallArgs extends InstallArgs {
4696 String cid;
4697 String cachePath;
4698 static final String RES_FILE_NAME = "pkg.apk";
4699
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004700 SdInstallArgs(InstallParams params) {
4701 super(params.packageURI, params.observer,
4702 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004703 }
4704
4705 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004706 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004707 // Extract cid from fullCodePath
4708 int eidx = fullCodePath.lastIndexOf("/");
4709 String subStr1 = fullCodePath.substring(0, eidx);
4710 int sidx = subStr1.lastIndexOf("/");
4711 cid = subStr1.substring(sidx+1, eidx);
4712 cachePath = subStr1;
4713 }
4714
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004715 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004716 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
4717 this.cid = cid;
4718 }
4719
4720 SdInstallArgs(Uri packageURI, String cid) {
4721 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004722 this.cid = cid;
4723 }
4724
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004725 void createCopyFile() {
4726 cid = getTempContainerId();
4727 }
4728
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004729 int copyApk(IMediaContainerService imcs, boolean temp) {
4730 if (temp) {
4731 createCopyFile();
4732 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004733 try {
4734 cachePath = imcs.copyResourceToContainer(
4735 packageURI, cid,
4736 getEncryptKey(), RES_FILE_NAME);
4737 } catch (RemoteException e) {
4738 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004739 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4740 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004741 }
4742
4743 @Override
4744 String getCodePath() {
4745 return cachePath + "/" + RES_FILE_NAME;
4746 }
4747
4748 @Override
4749 String getResourcePath() {
4750 return cachePath + "/" + RES_FILE_NAME;
4751 }
4752
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004753 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004754 if (status != PackageManager.INSTALL_SUCCEEDED) {
4755 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004756 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004757 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004758 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004759 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004760 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004761 if (cachePath == null) {
4762 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4763 }
4764 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004765 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004766 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004767 }
4768
4769 boolean doRename(int status, final String pkgName,
4770 String oldCodePath) {
4771 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004772 String newCachePath = null;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004773 final int RENAME_FAILED = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004774 final int MOUNT_FAILED = 2;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004775 final int PASS = 4;
4776 int errCode = RENAME_FAILED;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004777 String errMsg = "RENAME_FAILED";
4778 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004779 if (mounted) {
4780 // Unmount the container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004781 if (!PackageHelper.unMountSdDir(cid)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004782 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
4783 return false;
4784 }
4785 mounted = false;
4786 }
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004787 if (PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004788 errCode = MOUNT_FAILED;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004789 errMsg = "MOUNT_FAILED";
4790 if ((newCachePath = PackageHelper.mountSdDir(newCacheId,
4791 getEncryptKey(), Process.SYSTEM_UID)) != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004792 errCode = PASS;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004793 errMsg = "PASS";
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004794 }
4795 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004796 if (errCode != PASS) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004797 Log.i(TAG, "Failed to rename " + cid + " to " + newCacheId +
4798 " at path: " + cachePath + " to new path: " + newCachePath +
4799 "err = " + errMsg);
4800 // Mount old container?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004801 return false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004802 } else {
4803 Log.i(TAG, "Succesfully renamed " + cid + " to " + newCacheId +
4804 " at path: " + cachePath + " to new path: " + newCachePath);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004805 }
4806 cid = newCacheId;
4807 cachePath = newCachePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004808 return true;
4809 }
4810
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004811 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004812 if (status != PackageManager.INSTALL_SUCCEEDED) {
4813 cleanUp();
4814 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004815 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004816 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004817 PackageHelper.mountSdDir(cid,
4818 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004819 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004820 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004821 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004822 }
4823
4824 private void cleanUp() {
4825 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004826 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004827 }
4828
4829 void cleanUpResourcesLI() {
4830 String sourceFile = getCodePath();
4831 // Remove dex file
4832 if (mInstaller != null) {
4833 int retCode = mInstaller.rmdex(sourceFile.toString());
4834 if (retCode < 0) {
4835 Log.w(TAG, "Couldn't remove dex file for package: "
4836 + " at location "
4837 + sourceFile.toString() + ", retcode=" + retCode);
4838 // we don't consider this to be a failure of the core package deletion
4839 }
4840 }
4841 cleanUp();
4842 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004843
4844 boolean matchContainer(String app) {
4845 if (cid.startsWith(app)) {
4846 return true;
4847 }
4848 return false;
4849 }
4850
4851 String getPackageName() {
4852 int idx = cid.lastIndexOf("-");
4853 if (idx == -1) {
4854 return cid;
4855 }
4856 return cid.substring(0, idx);
4857 }
4858
4859 boolean doPostDeleteLI(boolean delete) {
4860 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004861 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004862 if (mounted) {
4863 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004864 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004865 }
4866 if (ret && delete) {
4867 cleanUpResourcesLI();
4868 }
4869 return ret;
4870 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004871 };
4872
4873 // Utility method used to create code paths based on package name and available index.
4874 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4875 String idxStr = "";
4876 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004877 // Fall back to default value of idx=1 if prefix is not
4878 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004879 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004880 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004881 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004882 if (subStr.endsWith(suffix)) {
4883 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004884 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004885 // If oldCodePath already contains prefix find out the
4886 // ending index to either increment or decrement.
4887 int sidx = subStr.lastIndexOf(prefix);
4888 if (sidx != -1) {
4889 subStr = subStr.substring(sidx + prefix.length());
4890 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004891 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
4892 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004893 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004894 try {
4895 idx = Integer.parseInt(subStr);
4896 if (idx <= 1) {
4897 idx++;
4898 } else {
4899 idx--;
4900 }
4901 } catch(NumberFormatException e) {
4902 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004903 }
4904 }
4905 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004906 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004907 return prefix + idxStr;
4908 }
4909
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004910 // Utility method used to ignore ADD/REMOVE events
4911 // by directory observer.
4912 private static boolean ignoreCodePath(String fullPathStr) {
4913 String apkName = getApkName(fullPathStr);
4914 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
4915 if (idx != -1 && ((idx+1) < apkName.length())) {
4916 // Make sure the package ends with a numeral
4917 String version = apkName.substring(idx+1);
4918 try {
4919 Integer.parseInt(version);
4920 return true;
4921 } catch (NumberFormatException e) {}
4922 }
4923 return false;
4924 }
4925
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004926 // Utility method that returns the relative package path with respect
4927 // to the installation directory. Like say for /data/data/com.test-1.apk
4928 // string com.test-1 is returned.
4929 static String getApkName(String codePath) {
4930 if (codePath == null) {
4931 return null;
4932 }
4933 int sidx = codePath.lastIndexOf("/");
4934 int eidx = codePath.lastIndexOf(".");
4935 if (eidx == -1) {
4936 eidx = codePath.length();
4937 } else if (eidx == 0) {
4938 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
4939 return null;
4940 }
4941 return codePath.substring(sidx+1, eidx);
4942 }
4943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 class PackageInstalledInfo {
4945 String name;
4946 int uid;
4947 PackageParser.Package pkg;
4948 int returnCode;
4949 PackageRemovedInfo removedInfo;
4950 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 /*
4953 * Install a non-existing package.
4954 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004955 private void installNewPackageLI(PackageParser.Package pkg,
4956 int parseFlags,
4957 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004958 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004959 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08004960 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004961 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08004962
4963 if (useEncryptedFilesystemForPackage(pkg)) {
4964 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
4965 } else {
4966 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
4967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004968 res.name = pkgName;
4969 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004970 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004971 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004972 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004973 + " without first uninstalling.");
4974 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4975 return;
4976 }
4977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004978 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004979 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004980 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004981 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004982 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4983 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4984 }
4985 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004986 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004987 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004988 res);
4989 // delete the partially installed application. the data directory will have to be
4990 // restored if it was already existing
4991 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4992 // remove package from internal structures. Note that we want deletePackageX to
4993 // delete the package data and cache directories that it created in
4994 // scanPackageLocked, unless those directories existed before we even tried to
4995 // install.
4996 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004997 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
4999 res.removedInfo);
5000 }
5001 }
5002 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005003
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005004 private void replacePackageLI(PackageParser.Package pkg,
5005 int parseFlags,
5006 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005007 String installerPackageName, PackageInstalledInfo res) {
5008
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005009 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005010 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011 // First find the old package info and check signatures
5012 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005013 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005014 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005015 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5017 return;
5018 }
5019 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005020 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005021 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005022 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005024 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005025 }
5026 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005028 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005029 PackageParser.Package pkg,
5030 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005031 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005032 PackageParser.Package newPackage = null;
5033 String pkgName = deletedPackage.packageName;
5034 boolean deletedPkg = true;
5035 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005036
Jacek Surazski65e13172009-04-28 15:26:38 +02005037 String oldInstallerPackageName = null;
5038 synchronized (mPackages) {
5039 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5040 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005041
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005042 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005043 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005044 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005045 res.removedInfo)) {
5046 // If the existing package was'nt successfully deleted
5047 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5048 deletedPkg = false;
5049 } else {
5050 // Successfully deleted the old package. Now proceed with re-installation
5051 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005052 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005053 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005054 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005055 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5056 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005057 }
5058 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005059 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005060 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005061 res);
5062 updatedSettings = true;
5063 }
5064 }
5065
5066 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5067 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005068 // were keeping around in case we needed them (see below) can now be deleted.
5069 // This info will be set on the res.removedInfo to clean up later on as post
5070 // install action.
5071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 //update signature on the new package setting
5073 //this should always succeed, since we checked the
5074 //signature earlier.
5075 synchronized(mPackages) {
5076 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5077 parseFlags, true);
5078 }
5079 } else {
5080 // remove package from internal structures. Note that we want deletePackageX to
5081 // delete the package data and cache directories that it created in
5082 // scanPackageLocked, unless those directories existed before we even tried to
5083 // install.
5084 if(updatedSettings) {
5085 deletePackageLI(
5086 pkgName, true,
5087 PackageManager.DONT_DELETE_DATA,
5088 res.removedInfo);
5089 }
5090 // Since we failed to install the new package we need to restore the old
5091 // package that we deleted.
5092 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005093 File restoreFile = new File(deletedPackage.mPath);
5094 if (restoreFile == null) {
5095 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
5096 return;
5097 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005098 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5099 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005100 // Parse old package
5101 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5102 scanPackageLI(restoreFile, parseFlags, scanMode);
5103 synchronized (mPackages) {
5104 grantPermissionsLP(deletedPackage, false);
5105 mSettings.writeLP();
5106 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005107 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5108 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
5109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005110 }
5111 }
5112 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005115 PackageParser.Package pkg,
5116 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005117 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 PackageParser.Package newPackage = null;
5119 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005120 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005121 PackageParser.PARSE_IS_SYSTEM;
5122 String packageName = deletedPackage.packageName;
5123 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5124 if (packageName == null) {
5125 Log.w(TAG, "Attempt to delete null packageName.");
5126 return;
5127 }
5128 PackageParser.Package oldPkg;
5129 PackageSetting oldPkgSetting;
5130 synchronized (mPackages) {
5131 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005132 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005133 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5134 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005135 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 return;
5137 }
5138 }
5139 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5140 res.removedInfo.removedPackage = packageName;
5141 // Remove existing system package
5142 removePackageLI(oldPkg, true);
5143 synchronized (mPackages) {
5144 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5145 }
5146
5147 // Successfully disabled the old package. Now proceed with re-installation
5148 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5149 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005150 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005151 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005152 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005153 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5154 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5155 }
5156 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005157 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005158 updatedSettings = true;
5159 }
5160
5161 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5162 //update signature on the new package setting
5163 //this should always succeed, since we checked the
5164 //signature earlier.
5165 synchronized(mPackages) {
5166 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5167 parseFlags, true);
5168 }
5169 } else {
5170 // Re installation failed. Restore old information
5171 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005172 if (newPackage != null) {
5173 removePackageLI(newPackage, true);
5174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005175 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005176 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005177 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005178 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 // Restore the old system information in Settings
5180 synchronized(mPackages) {
5181 if(updatedSettings) {
5182 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005183 mSettings.setInstallerPackageName(packageName,
5184 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005185 }
5186 mSettings.writeLP();
5187 }
5188 }
5189 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005190
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005191 // Utility method used to move dex files during install.
5192 private int moveDexFiles(PackageParser.Package newPackage) {
5193 int retCode;
5194 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5195 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5196 if (retCode != 0) {
5197 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5198 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5199 }
5200 }
5201 return PackageManager.INSTALL_SUCCEEDED;
5202 }
5203
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005204 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005205 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005206 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005207 synchronized (mPackages) {
5208 //write settings. the installStatus will be incomplete at this stage.
5209 //note that the new package setting would have already been
5210 //added to mPackages. It hasn't been persisted yet.
5211 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5212 mSettings.writeLP();
5213 }
5214
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005215 if ((res.returnCode = moveDexFiles(newPackage))
5216 != PackageManager.INSTALL_SUCCEEDED) {
5217 // Discontinue if moving dex files failed.
5218 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005220 if((res.returnCode = setPermissionsLI(newPackage))
5221 != PackageManager.INSTALL_SUCCEEDED) {
5222 if (mInstaller != null) {
5223 mInstaller.rmdex(newPackage.mScanPath);
5224 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005225 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005226 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005227 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 synchronized (mPackages) {
5230 grantPermissionsLP(newPackage, true);
5231 res.name = pkgName;
5232 res.uid = newPackage.applicationInfo.uid;
5233 res.pkg = newPackage;
5234 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005235 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005236 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5237 //to update install status
5238 mSettings.writeLP();
5239 }
5240 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005241
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005242 private void installPackageLI(InstallArgs args,
5243 boolean newInstall, PackageInstalledInfo res) {
5244 int pFlags = args.flags;
5245 String installerPackageName = args.installerPackageName;
5246 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005247 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005248 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005249 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005250 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5251 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005252 // Result object to be returned
5253 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5254
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005255 // Retrieve PackageSettings and parse package
5256 int parseFlags = PackageParser.PARSE_CHATTY |
5257 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5258 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5259 parseFlags |= mDefParseFlags;
5260 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5261 pp.setSeparateProcesses(mSeparateProcesses);
5262 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5263 null, mMetrics, parseFlags);
5264 if (pkg == null) {
5265 res.returnCode = pp.getParseError();
5266 return;
5267 }
5268 String pkgName = res.name = pkg.packageName;
5269 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5270 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5271 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5272 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005274 }
5275 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5276 res.returnCode = pp.getParseError();
5277 return;
5278 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005279 // Get rid of all references to package scan path via parser.
5280 pp = null;
5281 String oldCodePath = null;
5282 boolean systemApp = false;
5283 synchronized (mPackages) {
5284 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005285 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5286 String oldName = mSettings.mRenamedPackages.get(pkgName);
5287 if (oldName != null && oldName.equals(pkg.mOriginalPackage)
5288 && mPackages.containsKey(oldName)) {
5289 // This package is derived from an original package,
5290 // and this device has been updating from that original
5291 // name. We must continue using the original name, so
5292 // rename the new package here.
5293 pkg.setPackageName(pkg.mOriginalPackage);
5294 pkgName = pkg.packageName;
5295 replace = true;
5296 } else if (mPackages.containsKey(pkgName)) {
5297 // This package, under its official name, already exists
5298 // on the device; we should replace it.
5299 replace = true;
5300 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005301 }
5302 PackageSetting ps = mSettings.mPackages.get(pkgName);
5303 if (ps != null) {
5304 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5305 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5306 systemApp = (ps.pkg.applicationInfo.flags &
5307 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005308 }
5309 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005310 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005311
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005312 if (systemApp && onSd) {
5313 // Disable updates to system apps on sdcard
5314 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5315 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5316 return;
5317 }
5318 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5319 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5320 return;
5321 }
5322 // Set application objects path explicitly after the rename
5323 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005324 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005325 replacePackageLI(pkg, parseFlags, scanMode,
5326 installerPackageName, res);
5327 } else {
5328 installNewPackageLI(pkg, parseFlags, scanMode,
5329 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005330 }
5331 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005332
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005333 private int setPermissionsLI(PackageParser.Package newPackage) {
5334 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005335 int retCode = 0;
5336 // TODO Gross hack but fix later. Ideally move this to be a post installation
5337 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005338 if ((newPackage.applicationInfo.flags
5339 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5340 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005341 try {
5342 extractPublicFiles(newPackage, destResourceFile);
5343 } catch (IOException e) {
5344 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5345 " forward-locked app.");
5346 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5347 } finally {
5348 //TODO clean up the extracted public files
5349 }
5350 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005351 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005352 newPackage.applicationInfo.uid);
5353 } else {
5354 final int filePermissions =
5355 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005356 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 newPackage.applicationInfo.uid);
5358 }
5359 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005360 // The permissions on the resource file was set when it was copied for
5361 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005364 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005365 Log.e(TAG, "Couldn't set new package file permissions for " +
5366 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005368 // TODO Define new internal error
5369 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 }
5371 return PackageManager.INSTALL_SUCCEEDED;
5372 }
5373
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005374 private boolean isForwardLocked(PackageParser.Package pkg) {
5375 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005376 }
5377
5378 private void extractPublicFiles(PackageParser.Package newPackage,
5379 File publicZipFile) throws IOException {
5380 final ZipOutputStream publicZipOutStream =
5381 new ZipOutputStream(new FileOutputStream(publicZipFile));
5382 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5383
5384 // Copy manifest, resources.arsc and res directory to public zip
5385
5386 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5387 while (privateZipEntries.hasMoreElements()) {
5388 final ZipEntry zipEntry = privateZipEntries.nextElement();
5389 final String zipEntryName = zipEntry.getName();
5390 if ("AndroidManifest.xml".equals(zipEntryName)
5391 || "resources.arsc".equals(zipEntryName)
5392 || zipEntryName.startsWith("res/")) {
5393 try {
5394 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5395 } catch (IOException e) {
5396 try {
5397 publicZipOutStream.close();
5398 throw e;
5399 } finally {
5400 publicZipFile.delete();
5401 }
5402 }
5403 }
5404 }
5405
5406 publicZipOutStream.close();
5407 FileUtils.setPermissions(
5408 publicZipFile.getAbsolutePath(),
5409 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5410 -1, -1);
5411 }
5412
5413 private static void copyZipEntry(ZipEntry zipEntry,
5414 ZipFile inZipFile,
5415 ZipOutputStream outZipStream) throws IOException {
5416 byte[] buffer = new byte[4096];
5417 int num;
5418
5419 ZipEntry newEntry;
5420 if (zipEntry.getMethod() == ZipEntry.STORED) {
5421 // Preserve the STORED method of the input entry.
5422 newEntry = new ZipEntry(zipEntry);
5423 } else {
5424 // Create a new entry so that the compressed len is recomputed.
5425 newEntry = new ZipEntry(zipEntry.getName());
5426 }
5427 outZipStream.putNextEntry(newEntry);
5428
5429 InputStream data = inZipFile.getInputStream(zipEntry);
5430 while ((num = data.read(buffer)) > 0) {
5431 outZipStream.write(buffer, 0, num);
5432 }
5433 outZipStream.flush();
5434 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 private void deleteTempPackageFiles() {
5437 FilenameFilter filter = new FilenameFilter() {
5438 public boolean accept(File dir, String name) {
5439 return name.startsWith("vmdl") && name.endsWith(".tmp");
5440 }
5441 };
5442 String tmpFilesList[] = mAppInstallDir.list(filter);
5443 if(tmpFilesList == null) {
5444 return;
5445 }
5446 for(int i = 0; i < tmpFilesList.length; i++) {
5447 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5448 tmpFile.delete();
5449 }
5450 }
5451
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005452 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453 File tmpPackageFile;
5454 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005455 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456 } catch (IOException e) {
5457 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5458 return null;
5459 }
5460 try {
5461 FileUtils.setPermissions(
5462 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5463 -1, -1);
5464 } catch (IOException e) {
5465 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5466 return null;
5467 }
5468 return tmpPackageFile;
5469 }
5470
5471 public void deletePackage(final String packageName,
5472 final IPackageDeleteObserver observer,
5473 final int flags) {
5474 mContext.enforceCallingOrSelfPermission(
5475 android.Manifest.permission.DELETE_PACKAGES, null);
5476 // Queue up an async operation since the package deletion may take a little while.
5477 mHandler.post(new Runnable() {
5478 public void run() {
5479 mHandler.removeCallbacks(this);
5480 final boolean succeded = deletePackageX(packageName, true, true, flags);
5481 if (observer != null) {
5482 try {
5483 observer.packageDeleted(succeded);
5484 } catch (RemoteException e) {
5485 Log.i(TAG, "Observer no longer exists.");
5486 } //end catch
5487 } //end if
5488 } //end run
5489 });
5490 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492 /**
5493 * This method is an internal method that could be get invoked either
5494 * to delete an installed package or to clean up a failed installation.
5495 * After deleting an installed package, a broadcast is sent to notify any
5496 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005497 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 * installation wouldn't have sent the initial broadcast either
5499 * The key steps in deleting a package are
5500 * deleting the package information in internal structures like mPackages,
5501 * deleting the packages base directories through installd
5502 * updating mSettings to reflect current status
5503 * persisting settings for later use
5504 * sending a broadcast if necessary
5505 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5507 boolean deleteCodeAndResources, int flags) {
5508 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005509 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510
5511 synchronized (mInstallLock) {
5512 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5513 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005516 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5517 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5518
5519 // If the removed package was a system update, the old system packaged
5520 // was re-enabled; we need to broadcast this information
5521 if (systemUpdate) {
5522 Bundle extras = new Bundle(1);
5523 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5524 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5525
5526 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5527 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005530 // Delete the resources here after sending the broadcast to let
5531 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005532 if (info.args != null) {
5533 synchronized (mInstallLock) {
5534 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005535 }
5536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 return res;
5538 }
5539
5540 static class PackageRemovedInfo {
5541 String removedPackage;
5542 int uid = -1;
5543 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005544 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005545 // Clean up resources deleted packages.
5546 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 void sendBroadcast(boolean fullRemove, boolean replacing) {
5549 Bundle extras = new Bundle(1);
5550 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5551 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5552 if (replacing) {
5553 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5554 }
5555 if (removedPackage != null) {
5556 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5557 }
5558 if (removedUid >= 0) {
5559 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5560 }
5561 }
5562 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005564 /*
5565 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5566 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005567 * 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 -08005568 * delete a partially installed application.
5569 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005570 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 int flags) {
5572 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005573 if (outInfo != null) {
5574 outInfo.removedPackage = packageName;
5575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 removePackageLI(p, true);
5577 // Retrieve object to delete permissions for shared user later on
5578 PackageSetting deletedPs;
5579 synchronized (mPackages) {
5580 deletedPs = mSettings.mPackages.get(packageName);
5581 }
5582 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005583 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005585 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 if (retCode < 0) {
5587 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5588 + packageName + ", retcode=" + retCode);
5589 // we don't consider this to be a failure of the core package deletion
5590 }
5591 } else {
5592 //for emulator
5593 PackageParser.Package pkg = mPackages.get(packageName);
5594 File dataDir = new File(pkg.applicationInfo.dataDir);
5595 dataDir.delete();
5596 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005597 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005598 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005599 if (outInfo != null) {
5600 outInfo.removedUid = mSettings.removePackageLP(packageName);
5601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 }
5603 }
5604 synchronized (mPackages) {
5605 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5606 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005607 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 }
5609 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005610 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 }
5612 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 /*
5615 * Tries to delete system package.
5616 */
5617 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005618 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 ApplicationInfo applicationInfo = p.applicationInfo;
5620 //applicable for non-partially installed applications only
5621 if (applicationInfo == null) {
5622 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5623 return false;
5624 }
5625 PackageSetting ps = null;
5626 // Confirm if the system package has been updated
5627 // An updated system app can be deleted. This will also have to restore
5628 // the system pkg from system partition
5629 synchronized (mPackages) {
5630 ps = mSettings.getDisabledSystemPkg(p.packageName);
5631 }
5632 if (ps == null) {
5633 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5634 return false;
5635 } else {
5636 Log.i(TAG, "Deleting system pkg from data partition");
5637 }
5638 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005639 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005640 boolean deleteCodeAndResources = false;
5641 if (ps.versionCode < p.mVersionCode) {
5642 // Delete code and resources for downgrades
5643 deleteCodeAndResources = true;
5644 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5645 flags &= ~PackageManager.DONT_DELETE_DATA;
5646 }
5647 } else {
5648 // Preserve data by setting flag
5649 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5650 flags |= PackageManager.DONT_DELETE_DATA;
5651 }
5652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5654 if (!ret) {
5655 return false;
5656 }
5657 synchronized (mPackages) {
5658 // Reinstate the old system package
5659 mSettings.enableSystemPackageLP(p.packageName);
5660 }
5661 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005662 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005663 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005664 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 if (newPkg == null) {
5667 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5668 return false;
5669 }
5670 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005671 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 mSettings.writeLP();
5673 }
5674 return true;
5675 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5678 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5679 ApplicationInfo applicationInfo = p.applicationInfo;
5680 if (applicationInfo == null) {
5681 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5682 return false;
5683 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005684 if (outInfo != null) {
5685 outInfo.uid = applicationInfo.uid;
5686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687
5688 // Delete package data from internal structures and also remove data if flag is set
5689 removePackageDataLI(p, outInfo, flags);
5690
5691 // Delete application code and resources
5692 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005693 // TODO can pick up from PackageSettings as well
5694 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005695 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005696 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5697 PackageManager.INSTALL_FORWARD_LOCK : 0;
5698 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005699 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700 }
5701 return true;
5702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704 /*
5705 * This method handles package deletion in general
5706 */
5707 private boolean deletePackageLI(String packageName,
5708 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5709 if (packageName == null) {
5710 Log.w(TAG, "Attempt to delete null packageName.");
5711 return false;
5712 }
5713 PackageParser.Package p;
5714 boolean dataOnly = false;
5715 synchronized (mPackages) {
5716 p = mPackages.get(packageName);
5717 if (p == null) {
5718 //this retrieves partially installed apps
5719 dataOnly = true;
5720 PackageSetting ps = mSettings.mPackages.get(packageName);
5721 if (ps == null) {
5722 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5723 return false;
5724 }
5725 p = ps.pkg;
5726 }
5727 }
5728 if (p == null) {
5729 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5730 return false;
5731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 if (dataOnly) {
5734 // Delete application data first
5735 removePackageDataLI(p, outInfo, flags);
5736 return true;
5737 }
5738 // At this point the package should have ApplicationInfo associated with it
5739 if (p.applicationInfo == null) {
5740 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5741 return false;
5742 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005743 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5745 Log.i(TAG, "Removing system package:"+p.packageName);
5746 // When an updated system application is deleted we delete the existing resources as well and
5747 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005748 ret = deleteSystemPackageLI(p, flags, outInfo);
5749 } else {
5750 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005751 // Kill application pre-emptively especially for apps on sd.
5752 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005753 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005755 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 public void clearApplicationUserData(final String packageName,
5759 final IPackageDataObserver observer) {
5760 mContext.enforceCallingOrSelfPermission(
5761 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5762 // Queue up an async operation since the package deletion may take a little while.
5763 mHandler.post(new Runnable() {
5764 public void run() {
5765 mHandler.removeCallbacks(this);
5766 final boolean succeeded;
5767 synchronized (mInstallLock) {
5768 succeeded = clearApplicationUserDataLI(packageName);
5769 }
5770 if (succeeded) {
5771 // invoke DeviceStorageMonitor's update method to clear any notifications
5772 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5773 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5774 if (dsm != null) {
5775 dsm.updateMemory();
5776 }
5777 }
5778 if(observer != null) {
5779 try {
5780 observer.onRemoveCompleted(packageName, succeeded);
5781 } catch (RemoteException e) {
5782 Log.i(TAG, "Observer no longer exists.");
5783 }
5784 } //end if observer
5785 } //end run
5786 });
5787 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 private boolean clearApplicationUserDataLI(String packageName) {
5790 if (packageName == null) {
5791 Log.w(TAG, "Attempt to delete null packageName.");
5792 return false;
5793 }
5794 PackageParser.Package p;
5795 boolean dataOnly = false;
5796 synchronized (mPackages) {
5797 p = mPackages.get(packageName);
5798 if(p == null) {
5799 dataOnly = true;
5800 PackageSetting ps = mSettings.mPackages.get(packageName);
5801 if((ps == null) || (ps.pkg == null)) {
5802 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5803 return false;
5804 }
5805 p = ps.pkg;
5806 }
5807 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005808 boolean useEncryptedFSDir = false;
5809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005810 if(!dataOnly) {
5811 //need to check this only for fully installed applications
5812 if (p == null) {
5813 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5814 return false;
5815 }
5816 final ApplicationInfo applicationInfo = p.applicationInfo;
5817 if (applicationInfo == null) {
5818 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5819 return false;
5820 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005821 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 }
5823 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005824 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 if (retCode < 0) {
5826 Log.w(TAG, "Couldn't remove cache files for package: "
5827 + packageName);
5828 return false;
5829 }
5830 }
5831 return true;
5832 }
5833
5834 public void deleteApplicationCacheFiles(final String packageName,
5835 final IPackageDataObserver observer) {
5836 mContext.enforceCallingOrSelfPermission(
5837 android.Manifest.permission.DELETE_CACHE_FILES, null);
5838 // Queue up an async operation since the package deletion may take a little while.
5839 mHandler.post(new Runnable() {
5840 public void run() {
5841 mHandler.removeCallbacks(this);
5842 final boolean succeded;
5843 synchronized (mInstallLock) {
5844 succeded = deleteApplicationCacheFilesLI(packageName);
5845 }
5846 if(observer != null) {
5847 try {
5848 observer.onRemoveCompleted(packageName, succeded);
5849 } catch (RemoteException e) {
5850 Log.i(TAG, "Observer no longer exists.");
5851 }
5852 } //end if observer
5853 } //end run
5854 });
5855 }
5856
5857 private boolean deleteApplicationCacheFilesLI(String packageName) {
5858 if (packageName == null) {
5859 Log.w(TAG, "Attempt to delete null packageName.");
5860 return false;
5861 }
5862 PackageParser.Package p;
5863 synchronized (mPackages) {
5864 p = mPackages.get(packageName);
5865 }
5866 if (p == null) {
5867 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5868 return false;
5869 }
5870 final ApplicationInfo applicationInfo = p.applicationInfo;
5871 if (applicationInfo == null) {
5872 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5873 return false;
5874 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005875 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005876 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005877 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 if (retCode < 0) {
5879 Log.w(TAG, "Couldn't remove cache files for package: "
5880 + packageName);
5881 return false;
5882 }
5883 }
5884 return true;
5885 }
5886
5887 public void getPackageSizeInfo(final String packageName,
5888 final IPackageStatsObserver observer) {
5889 mContext.enforceCallingOrSelfPermission(
5890 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5891 // Queue up an async operation since the package deletion may take a little while.
5892 mHandler.post(new Runnable() {
5893 public void run() {
5894 mHandler.removeCallbacks(this);
5895 PackageStats lStats = new PackageStats(packageName);
5896 final boolean succeded;
5897 synchronized (mInstallLock) {
5898 succeded = getPackageSizeInfoLI(packageName, lStats);
5899 }
5900 if(observer != null) {
5901 try {
5902 observer.onGetStatsCompleted(lStats, succeded);
5903 } catch (RemoteException e) {
5904 Log.i(TAG, "Observer no longer exists.");
5905 }
5906 } //end if observer
5907 } //end run
5908 });
5909 }
5910
5911 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5912 if (packageName == null) {
5913 Log.w(TAG, "Attempt to get size of null packageName.");
5914 return false;
5915 }
5916 PackageParser.Package p;
5917 boolean dataOnly = false;
5918 synchronized (mPackages) {
5919 p = mPackages.get(packageName);
5920 if(p == null) {
5921 dataOnly = true;
5922 PackageSetting ps = mSettings.mPackages.get(packageName);
5923 if((ps == null) || (ps.pkg == null)) {
5924 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5925 return false;
5926 }
5927 p = ps.pkg;
5928 }
5929 }
5930 String publicSrcDir = null;
5931 if(!dataOnly) {
5932 final ApplicationInfo applicationInfo = p.applicationInfo;
5933 if (applicationInfo == null) {
5934 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5935 return false;
5936 }
5937 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
5938 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005939 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 if (mInstaller != null) {
5941 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08005942 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 if (res < 0) {
5944 return false;
5945 } else {
5946 return true;
5947 }
5948 }
5949 return true;
5950 }
5951
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005953 public void addPackageToPreferred(String packageName) {
5954 mContext.enforceCallingOrSelfPermission(
5955 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005956 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 }
5958
5959 public void removePackageFromPreferred(String packageName) {
5960 mContext.enforceCallingOrSelfPermission(
5961 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005962 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 }
5964
5965 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005966 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 }
5968
5969 public void addPreferredActivity(IntentFilter filter, int match,
5970 ComponentName[] set, ComponentName activity) {
5971 mContext.enforceCallingOrSelfPermission(
5972 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5973
5974 synchronized (mPackages) {
5975 Log.i(TAG, "Adding preferred activity " + activity + ":");
5976 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5977 mSettings.mPreferredActivities.addFilter(
5978 new PreferredActivity(filter, match, set, activity));
5979 mSettings.writeLP();
5980 }
5981 }
5982
Satish Sampath8dbe6122009-06-02 23:35:54 +01005983 public void replacePreferredActivity(IntentFilter filter, int match,
5984 ComponentName[] set, ComponentName activity) {
5985 mContext.enforceCallingOrSelfPermission(
5986 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5987 if (filter.countActions() != 1) {
5988 throw new IllegalArgumentException(
5989 "replacePreferredActivity expects filter to have only 1 action.");
5990 }
5991 if (filter.countCategories() != 1) {
5992 throw new IllegalArgumentException(
5993 "replacePreferredActivity expects filter to have only 1 category.");
5994 }
5995 if (filter.countDataAuthorities() != 0
5996 || filter.countDataPaths() != 0
5997 || filter.countDataSchemes() != 0
5998 || filter.countDataTypes() != 0) {
5999 throw new IllegalArgumentException(
6000 "replacePreferredActivity expects filter to have no data authorities, " +
6001 "paths, schemes or types.");
6002 }
6003 synchronized (mPackages) {
6004 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6005 String action = filter.getAction(0);
6006 String category = filter.getCategory(0);
6007 while (it.hasNext()) {
6008 PreferredActivity pa = it.next();
6009 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6010 it.remove();
6011 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6012 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6013 }
6014 }
6015 addPreferredActivity(filter, match, set, activity);
6016 }
6017 }
6018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 public void clearPackagePreferredActivities(String packageName) {
6020 mContext.enforceCallingOrSelfPermission(
6021 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6022
6023 synchronized (mPackages) {
6024 if (clearPackagePreferredActivitiesLP(packageName)) {
6025 mSettings.writeLP();
6026 }
6027 }
6028 }
6029
6030 boolean clearPackagePreferredActivitiesLP(String packageName) {
6031 boolean changed = false;
6032 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6033 while (it.hasNext()) {
6034 PreferredActivity pa = it.next();
6035 if (pa.mActivity.getPackageName().equals(packageName)) {
6036 it.remove();
6037 changed = true;
6038 }
6039 }
6040 return changed;
6041 }
6042
6043 public int getPreferredActivities(List<IntentFilter> outFilters,
6044 List<ComponentName> outActivities, String packageName) {
6045
6046 int num = 0;
6047 synchronized (mPackages) {
6048 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6049 while (it.hasNext()) {
6050 PreferredActivity pa = it.next();
6051 if (packageName == null
6052 || pa.mActivity.getPackageName().equals(packageName)) {
6053 if (outFilters != null) {
6054 outFilters.add(new IntentFilter(pa));
6055 }
6056 if (outActivities != null) {
6057 outActivities.add(pa.mActivity);
6058 }
6059 }
6060 }
6061 }
6062
6063 return num;
6064 }
6065
6066 public void setApplicationEnabledSetting(String appPackageName,
6067 int newState, int flags) {
6068 setEnabledSetting(appPackageName, null, newState, flags);
6069 }
6070
6071 public void setComponentEnabledSetting(ComponentName componentName,
6072 int newState, int flags) {
6073 setEnabledSetting(componentName.getPackageName(),
6074 componentName.getClassName(), newState, flags);
6075 }
6076
6077 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006078 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6080 || newState == COMPONENT_ENABLED_STATE_ENABLED
6081 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6082 throw new IllegalArgumentException("Invalid new component state: "
6083 + newState);
6084 }
6085 PackageSetting pkgSetting;
6086 final int uid = Binder.getCallingUid();
6087 final int permission = mContext.checkCallingPermission(
6088 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6089 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006090 boolean sendNow = false;
6091 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006092 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006094 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006096 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006098 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006100 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006101 }
6102 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006103 "Unknown component: " + packageName
6104 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 }
6106 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6107 throw new SecurityException(
6108 "Permission Denial: attempt to change component state from pid="
6109 + Binder.getCallingPid()
6110 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6111 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006112 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 // We're dealing with an application/package level state change
6114 pkgSetting.enabled = newState;
6115 } else {
6116 // We're dealing with a component level state change
6117 switch (newState) {
6118 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006119 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 break;
6121 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006122 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 break;
6124 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006125 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 break;
6127 default:
6128 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006129 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130 }
6131 }
6132 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006133 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006134 components = mPendingBroadcasts.get(packageName);
6135 boolean newPackage = components == null;
6136 if (newPackage) {
6137 components = new ArrayList<String>();
6138 }
6139 if (!components.contains(componentName)) {
6140 components.add(componentName);
6141 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006142 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6143 sendNow = true;
6144 // Purge entry from pending broadcast list if another one exists already
6145 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006146 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006147 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006148 if (newPackage) {
6149 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006150 }
6151 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6152 // Schedule a message
6153 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6154 }
6155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 long callingId = Binder.clearCallingIdentity();
6159 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006160 if (sendNow) {
6161 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006162 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 } finally {
6165 Binder.restoreCallingIdentity(callingId);
6166 }
6167 }
6168
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006169 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006170 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6171 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6172 + " components=" + componentNames);
6173 Bundle extras = new Bundle(4);
6174 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6175 String nameList[] = new String[componentNames.size()];
6176 componentNames.toArray(nameList);
6177 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006178 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6179 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006180 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006181 }
6182
Jacek Surazski65e13172009-04-28 15:26:38 +02006183 public String getInstallerPackageName(String packageName) {
6184 synchronized (mPackages) {
6185 PackageSetting pkg = mSettings.mPackages.get(packageName);
6186 if (pkg == null) {
6187 throw new IllegalArgumentException("Unknown package: " + packageName);
6188 }
6189 return pkg.installerPackageName;
6190 }
6191 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 public int getApplicationEnabledSetting(String appPackageName) {
6194 synchronized (mPackages) {
6195 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6196 if (pkg == null) {
6197 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6198 }
6199 return pkg.enabled;
6200 }
6201 }
6202
6203 public int getComponentEnabledSetting(ComponentName componentName) {
6204 synchronized (mPackages) {
6205 final String packageNameStr = componentName.getPackageName();
6206 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6207 if (pkg == null) {
6208 throw new IllegalArgumentException("Unknown component: " + componentName);
6209 }
6210 final String classNameStr = componentName.getClassName();
6211 return pkg.currentEnabledStateLP(classNameStr);
6212 }
6213 }
6214
6215 public void enterSafeMode() {
6216 if (!mSystemReady) {
6217 mSafeMode = true;
6218 }
6219 }
6220
6221 public void systemReady() {
6222 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006223
6224 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006225 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006226 mContext.getContentResolver(),
6227 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006228 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006229 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006230 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 }
6233
6234 public boolean isSafeMode() {
6235 return mSafeMode;
6236 }
6237
6238 public boolean hasSystemUidErrors() {
6239 return mHasSystemUidErrors;
6240 }
6241
6242 static String arrayToString(int[] array) {
6243 StringBuffer buf = new StringBuffer(128);
6244 buf.append('[');
6245 if (array != null) {
6246 for (int i=0; i<array.length; i++) {
6247 if (i > 0) buf.append(", ");
6248 buf.append(array[i]);
6249 }
6250 }
6251 buf.append(']');
6252 return buf.toString();
6253 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 @Override
6256 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6257 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6258 != PackageManager.PERMISSION_GRANTED) {
6259 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6260 + Binder.getCallingPid()
6261 + ", uid=" + Binder.getCallingUid()
6262 + " without permission "
6263 + android.Manifest.permission.DUMP);
6264 return;
6265 }
6266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 synchronized (mPackages) {
6268 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006269 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 pw.println(" ");
6271 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006272 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 pw.println(" ");
6274 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006275 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 pw.println(" ");
6277 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006278 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 pw.println("Permissions:");
6281 {
6282 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006283 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6284 pw.print(Integer.toHexString(System.identityHashCode(p)));
6285 pw.println("):");
6286 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6287 pw.print(" uid="); pw.print(p.uid);
6288 pw.print(" gids="); pw.print(arrayToString(p.gids));
6289 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 }
6291 }
6292 pw.println(" ");
6293 pw.println("Packages:");
6294 {
6295 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006296 pw.print(" Package [");
6297 pw.print(ps.realName != null ? ps.realName : ps.name);
6298 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006299 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6300 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006301 if (ps.realName != null) {
6302 pw.print(" compat name="); pw.println(ps.name);
6303 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006304 pw.print(" userId="); pw.print(ps.userId);
6305 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6306 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6307 pw.print(" pkg="); pw.println(ps.pkg);
6308 pw.print(" codePath="); pw.println(ps.codePathString);
6309 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006311 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006312 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006313 pw.print(" supportsScreens=[");
6314 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006315 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006316 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006317 if (!first) pw.print(", ");
6318 first = false;
6319 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006320 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006321 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006322 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006323 if (!first) pw.print(", ");
6324 first = false;
6325 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006326 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006327 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006328 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006329 if (!first) pw.print(", ");
6330 first = false;
6331 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006332 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006333 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006334 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006335 if (!first) pw.print(", ");
6336 first = false;
6337 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006339 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006340 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6341 if (!first) pw.print(", ");
6342 first = false;
6343 pw.print("anyDensity");
6344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006346 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006347 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6348 pw.print(" signatures="); pw.println(ps.signatures);
6349 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6350 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6351 pw.print(" installStatus="); pw.print(ps.installStatus);
6352 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 if (ps.disabledComponents.size() > 0) {
6354 pw.println(" disabledComponents:");
6355 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006356 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 }
6358 }
6359 if (ps.enabledComponents.size() > 0) {
6360 pw.println(" enabledComponents:");
6361 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006362 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 }
6364 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006365 if (ps.grantedPermissions.size() > 0) {
6366 pw.println(" grantedPermissions:");
6367 for (String s : ps.grantedPermissions) {
6368 pw.print(" "); pw.println(s);
6369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006371 if (ps.loadedPermissions.size() > 0) {
6372 pw.println(" loadedPermissions:");
6373 for (String s : ps.loadedPermissions) {
6374 pw.print(" "); pw.println(s);
6375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 }
6377 }
6378 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006379 if (mSettings.mRenamedPackages.size() > 0) {
6380 pw.println(" ");
6381 pw.println("Renamed packages:");
6382 for (HashMap.Entry<String, String> e
6383 : mSettings.mRenamedPackages.entrySet()) {
6384 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6385 pw.println(e.getValue());
6386 }
6387 }
6388 if (mSettings.mDisabledSysPackages.size() > 0) {
6389 pw.println(" ");
6390 pw.println("Hidden system packages:");
6391 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6392 pw.print(" Package [");
6393 pw.print(ps.realName != null ? ps.realName : ps.name);
6394 pw.print("] (");
6395 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6396 pw.println("):");
6397 if (ps.realName != null) {
6398 pw.print(" compat name="); pw.println(ps.name);
6399 }
6400 pw.print(" userId="); pw.println(ps.userId);
6401 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6402 pw.print(" codePath="); pw.println(ps.codePathString);
6403 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6404 }
6405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 pw.println(" ");
6407 pw.println("Shared Users:");
6408 {
6409 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006410 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6411 pw.print(Integer.toHexString(System.identityHashCode(su)));
6412 pw.println("):");
6413 pw.print(" userId="); pw.print(su.userId);
6414 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 pw.println(" grantedPermissions:");
6416 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006417 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 }
6419 pw.println(" loadedPermissions:");
6420 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006421 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 }
6423 }
6424 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 pw.println(" ");
6427 pw.println("Settings parse messages:");
6428 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006429
6430 pw.println(" ");
6431 pw.println("Package warning messages:");
6432 File fname = getSettingsProblemFile();
6433 FileInputStream in;
6434 try {
6435 in = new FileInputStream(fname);
6436 int avail = in.available();
6437 byte[] data = new byte[avail];
6438 in.read(data);
6439 pw.println(new String(data));
6440 } catch (FileNotFoundException e) {
6441 } catch (IOException e) {
6442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006444
6445 synchronized (mProviders) {
6446 pw.println(" ");
6447 pw.println("Registered ContentProviders:");
6448 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006449 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006450 pw.println(p.toString());
6451 }
6452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 }
6454
6455 static final class BasePermission {
6456 final static int TYPE_NORMAL = 0;
6457 final static int TYPE_BUILTIN = 1;
6458 final static int TYPE_DYNAMIC = 2;
6459
6460 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006461 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 final int type;
6463 PackageParser.Permission perm;
6464 PermissionInfo pendingInfo;
6465 int uid;
6466 int[] gids;
6467
6468 BasePermission(String _name, String _sourcePackage, int _type) {
6469 name = _name;
6470 sourcePackage = _sourcePackage;
6471 type = _type;
6472 }
6473 }
6474
6475 static class PackageSignatures {
6476 private Signature[] mSignatures;
6477
6478 PackageSignatures(Signature[] sigs) {
6479 assignSignatures(sigs);
6480 }
6481
6482 PackageSignatures() {
6483 }
6484
6485 void writeXml(XmlSerializer serializer, String tagName,
6486 ArrayList<Signature> pastSignatures) throws IOException {
6487 if (mSignatures == null) {
6488 return;
6489 }
6490 serializer.startTag(null, tagName);
6491 serializer.attribute(null, "count",
6492 Integer.toString(mSignatures.length));
6493 for (int i=0; i<mSignatures.length; i++) {
6494 serializer.startTag(null, "cert");
6495 final Signature sig = mSignatures[i];
6496 final int sigHash = sig.hashCode();
6497 final int numPast = pastSignatures.size();
6498 int j;
6499 for (j=0; j<numPast; j++) {
6500 Signature pastSig = pastSignatures.get(j);
6501 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6502 serializer.attribute(null, "index", Integer.toString(j));
6503 break;
6504 }
6505 }
6506 if (j >= numPast) {
6507 pastSignatures.add(sig);
6508 serializer.attribute(null, "index", Integer.toString(numPast));
6509 serializer.attribute(null, "key", sig.toCharsString());
6510 }
6511 serializer.endTag(null, "cert");
6512 }
6513 serializer.endTag(null, tagName);
6514 }
6515
6516 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6517 throws IOException, XmlPullParserException {
6518 String countStr = parser.getAttributeValue(null, "count");
6519 if (countStr == null) {
6520 reportSettingsProblem(Log.WARN,
6521 "Error in package manager settings: <signatures> has"
6522 + " no count at " + parser.getPositionDescription());
6523 XmlUtils.skipCurrentTag(parser);
6524 }
6525 final int count = Integer.parseInt(countStr);
6526 mSignatures = new Signature[count];
6527 int pos = 0;
6528
6529 int outerDepth = parser.getDepth();
6530 int type;
6531 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6532 && (type != XmlPullParser.END_TAG
6533 || parser.getDepth() > outerDepth)) {
6534 if (type == XmlPullParser.END_TAG
6535 || type == XmlPullParser.TEXT) {
6536 continue;
6537 }
6538
6539 String tagName = parser.getName();
6540 if (tagName.equals("cert")) {
6541 if (pos < count) {
6542 String index = parser.getAttributeValue(null, "index");
6543 if (index != null) {
6544 try {
6545 int idx = Integer.parseInt(index);
6546 String key = parser.getAttributeValue(null, "key");
6547 if (key == null) {
6548 if (idx >= 0 && idx < pastSignatures.size()) {
6549 Signature sig = pastSignatures.get(idx);
6550 if (sig != null) {
6551 mSignatures[pos] = pastSignatures.get(idx);
6552 pos++;
6553 } else {
6554 reportSettingsProblem(Log.WARN,
6555 "Error in package manager settings: <cert> "
6556 + "index " + index + " is not defined at "
6557 + parser.getPositionDescription());
6558 }
6559 } else {
6560 reportSettingsProblem(Log.WARN,
6561 "Error in package manager settings: <cert> "
6562 + "index " + index + " is out of bounds at "
6563 + parser.getPositionDescription());
6564 }
6565 } else {
6566 while (pastSignatures.size() <= idx) {
6567 pastSignatures.add(null);
6568 }
6569 Signature sig = new Signature(key);
6570 pastSignatures.set(idx, sig);
6571 mSignatures[pos] = sig;
6572 pos++;
6573 }
6574 } catch (NumberFormatException e) {
6575 reportSettingsProblem(Log.WARN,
6576 "Error in package manager settings: <cert> "
6577 + "index " + index + " is not a number at "
6578 + parser.getPositionDescription());
6579 }
6580 } else {
6581 reportSettingsProblem(Log.WARN,
6582 "Error in package manager settings: <cert> has"
6583 + " no index at " + parser.getPositionDescription());
6584 }
6585 } else {
6586 reportSettingsProblem(Log.WARN,
6587 "Error in package manager settings: too "
6588 + "many <cert> tags, expected " + count
6589 + " at " + parser.getPositionDescription());
6590 }
6591 } else {
6592 reportSettingsProblem(Log.WARN,
6593 "Unknown element under <cert>: "
6594 + parser.getName());
6595 }
6596 XmlUtils.skipCurrentTag(parser);
6597 }
6598
6599 if (pos < count) {
6600 // Should never happen -- there is an error in the written
6601 // settings -- but if it does we don't want to generate
6602 // a bad array.
6603 Signature[] newSigs = new Signature[pos];
6604 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6605 mSignatures = newSigs;
6606 }
6607 }
6608
6609 /**
6610 * If any of the given 'sigs' is contained in the existing signatures,
6611 * then completely replace the current signatures with the ones in
6612 * 'sigs'. This is used for updating an existing package to a newly
6613 * installed version.
6614 */
6615 boolean updateSignatures(Signature[] sigs, boolean update) {
6616 if (mSignatures == null) {
6617 if (update) {
6618 assignSignatures(sigs);
6619 }
6620 return true;
6621 }
6622 if (sigs == null) {
6623 return false;
6624 }
6625
6626 for (int i=0; i<sigs.length; i++) {
6627 Signature sig = sigs[i];
6628 for (int j=0; j<mSignatures.length; j++) {
6629 if (mSignatures[j].equals(sig)) {
6630 if (update) {
6631 assignSignatures(sigs);
6632 }
6633 return true;
6634 }
6635 }
6636 }
6637 return false;
6638 }
6639
6640 /**
6641 * If any of the given 'sigs' is contained in the existing signatures,
6642 * then add in any new signatures found in 'sigs'. This is used for
6643 * including a new package into an existing shared user id.
6644 */
6645 boolean mergeSignatures(Signature[] sigs, boolean update) {
6646 if (mSignatures == null) {
6647 if (update) {
6648 assignSignatures(sigs);
6649 }
6650 return true;
6651 }
6652 if (sigs == null) {
6653 return false;
6654 }
6655
6656 Signature[] added = null;
6657 int addedCount = 0;
6658 boolean haveMatch = false;
6659 for (int i=0; i<sigs.length; i++) {
6660 Signature sig = sigs[i];
6661 boolean found = false;
6662 for (int j=0; j<mSignatures.length; j++) {
6663 if (mSignatures[j].equals(sig)) {
6664 found = true;
6665 haveMatch = true;
6666 break;
6667 }
6668 }
6669
6670 if (!found) {
6671 if (added == null) {
6672 added = new Signature[sigs.length];
6673 }
6674 added[i] = sig;
6675 addedCount++;
6676 }
6677 }
6678
6679 if (!haveMatch) {
6680 // Nothing matched -- reject the new signatures.
6681 return false;
6682 }
6683 if (added == null) {
6684 // Completely matched -- nothing else to do.
6685 return true;
6686 }
6687
6688 // Add additional signatures in.
6689 if (update) {
6690 Signature[] total = new Signature[addedCount+mSignatures.length];
6691 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6692 int j = mSignatures.length;
6693 for (int i=0; i<added.length; i++) {
6694 if (added[i] != null) {
6695 total[j] = added[i];
6696 j++;
6697 }
6698 }
6699 mSignatures = total;
6700 }
6701 return true;
6702 }
6703
6704 private void assignSignatures(Signature[] sigs) {
6705 if (sigs == null) {
6706 mSignatures = null;
6707 return;
6708 }
6709 mSignatures = new Signature[sigs.length];
6710 for (int i=0; i<sigs.length; i++) {
6711 mSignatures[i] = sigs[i];
6712 }
6713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 @Override
6716 public String toString() {
6717 StringBuffer buf = new StringBuffer(128);
6718 buf.append("PackageSignatures{");
6719 buf.append(Integer.toHexString(System.identityHashCode(this)));
6720 buf.append(" [");
6721 if (mSignatures != null) {
6722 for (int i=0; i<mSignatures.length; i++) {
6723 if (i > 0) buf.append(", ");
6724 buf.append(Integer.toHexString(
6725 System.identityHashCode(mSignatures[i])));
6726 }
6727 }
6728 buf.append("]}");
6729 return buf.toString();
6730 }
6731 }
6732
6733 static class PreferredActivity extends IntentFilter {
6734 final int mMatch;
6735 final String[] mSetPackages;
6736 final String[] mSetClasses;
6737 final String[] mSetComponents;
6738 final ComponentName mActivity;
6739 final String mShortActivity;
6740 String mParseError;
6741
6742 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6743 ComponentName activity) {
6744 super(filter);
6745 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6746 mActivity = activity;
6747 mShortActivity = activity.flattenToShortString();
6748 mParseError = null;
6749 if (set != null) {
6750 final int N = set.length;
6751 String[] myPackages = new String[N];
6752 String[] myClasses = new String[N];
6753 String[] myComponents = new String[N];
6754 for (int i=0; i<N; i++) {
6755 ComponentName cn = set[i];
6756 if (cn == null) {
6757 mSetPackages = null;
6758 mSetClasses = null;
6759 mSetComponents = null;
6760 return;
6761 }
6762 myPackages[i] = cn.getPackageName().intern();
6763 myClasses[i] = cn.getClassName().intern();
6764 myComponents[i] = cn.flattenToShortString().intern();
6765 }
6766 mSetPackages = myPackages;
6767 mSetClasses = myClasses;
6768 mSetComponents = myComponents;
6769 } else {
6770 mSetPackages = null;
6771 mSetClasses = null;
6772 mSetComponents = null;
6773 }
6774 }
6775
6776 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6777 IOException {
6778 mShortActivity = parser.getAttributeValue(null, "name");
6779 mActivity = ComponentName.unflattenFromString(mShortActivity);
6780 if (mActivity == null) {
6781 mParseError = "Bad activity name " + mShortActivity;
6782 }
6783 String matchStr = parser.getAttributeValue(null, "match");
6784 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6785 String setCountStr = parser.getAttributeValue(null, "set");
6786 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6787
6788 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6789 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6790 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6791
6792 int setPos = 0;
6793
6794 int outerDepth = parser.getDepth();
6795 int type;
6796 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6797 && (type != XmlPullParser.END_TAG
6798 || parser.getDepth() > outerDepth)) {
6799 if (type == XmlPullParser.END_TAG
6800 || type == XmlPullParser.TEXT) {
6801 continue;
6802 }
6803
6804 String tagName = parser.getName();
6805 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6806 // + parser.getDepth() + " tag=" + tagName);
6807 if (tagName.equals("set")) {
6808 String name = parser.getAttributeValue(null, "name");
6809 if (name == null) {
6810 if (mParseError == null) {
6811 mParseError = "No name in set tag in preferred activity "
6812 + mShortActivity;
6813 }
6814 } else if (setPos >= setCount) {
6815 if (mParseError == null) {
6816 mParseError = "Too many set tags in preferred activity "
6817 + mShortActivity;
6818 }
6819 } else {
6820 ComponentName cn = ComponentName.unflattenFromString(name);
6821 if (cn == null) {
6822 if (mParseError == null) {
6823 mParseError = "Bad set name " + name + " in preferred activity "
6824 + mShortActivity;
6825 }
6826 } else {
6827 myPackages[setPos] = cn.getPackageName();
6828 myClasses[setPos] = cn.getClassName();
6829 myComponents[setPos] = name;
6830 setPos++;
6831 }
6832 }
6833 XmlUtils.skipCurrentTag(parser);
6834 } else if (tagName.equals("filter")) {
6835 //Log.i(TAG, "Starting to parse filter...");
6836 readFromXml(parser);
6837 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6838 // + parser.getDepth() + " tag=" + parser.getName());
6839 } else {
6840 reportSettingsProblem(Log.WARN,
6841 "Unknown element under <preferred-activities>: "
6842 + parser.getName());
6843 XmlUtils.skipCurrentTag(parser);
6844 }
6845 }
6846
6847 if (setPos != setCount) {
6848 if (mParseError == null) {
6849 mParseError = "Not enough set tags (expected " + setCount
6850 + " but found " + setPos + ") in " + mShortActivity;
6851 }
6852 }
6853
6854 mSetPackages = myPackages;
6855 mSetClasses = myClasses;
6856 mSetComponents = myComponents;
6857 }
6858
6859 public void writeToXml(XmlSerializer serializer) throws IOException {
6860 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6861 serializer.attribute(null, "name", mShortActivity);
6862 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6863 serializer.attribute(null, "set", Integer.toString(NS));
6864 for (int s=0; s<NS; s++) {
6865 serializer.startTag(null, "set");
6866 serializer.attribute(null, "name", mSetComponents[s]);
6867 serializer.endTag(null, "set");
6868 }
6869 serializer.startTag(null, "filter");
6870 super.writeToXml(serializer);
6871 serializer.endTag(null, "filter");
6872 }
6873
6874 boolean sameSet(List<ResolveInfo> query, int priority) {
6875 if (mSetPackages == null) return false;
6876 final int NQ = query.size();
6877 final int NS = mSetPackages.length;
6878 int numMatch = 0;
6879 for (int i=0; i<NQ; i++) {
6880 ResolveInfo ri = query.get(i);
6881 if (ri.priority != priority) continue;
6882 ActivityInfo ai = ri.activityInfo;
6883 boolean good = false;
6884 for (int j=0; j<NS; j++) {
6885 if (mSetPackages[j].equals(ai.packageName)
6886 && mSetClasses[j].equals(ai.name)) {
6887 numMatch++;
6888 good = true;
6889 break;
6890 }
6891 }
6892 if (!good) return false;
6893 }
6894 return numMatch == NS;
6895 }
6896 }
6897
6898 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006899 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 HashSet<String> grantedPermissions = new HashSet<String>();
6902 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006904 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006906 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006907 setFlags(pkgFlags);
6908 }
6909
6910 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006911 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006912 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6913 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006914 }
6915 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006917 /**
6918 * Settings base class for pending and resolved classes.
6919 */
6920 static class PackageSettingBase extends GrantedPermissions {
6921 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006922 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006923 File codePath;
6924 String codePathString;
6925 File resourcePath;
6926 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 private long timeStamp;
6928 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006929 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006930
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006931 boolean uidError;
6932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 PackageSignatures signatures = new PackageSignatures();
6934
6935 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 /* Explicitly disabled components */
6938 HashSet<String> disabledComponents = new HashSet<String>(0);
6939 /* Explicitly enabled components */
6940 HashSet<String> enabledComponents = new HashSet<String>(0);
6941 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6942 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006943
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006944 PackageSettingBase origPackage;
6945
Jacek Surazski65e13172009-04-28 15:26:38 +02006946 /* package name of the app that installed this package */
6947 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006949 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006950 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 super(pkgFlags);
6952 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006953 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006954 init(codePath, resourcePath, pVersionCode);
6955 }
6956
6957 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 this.codePath = codePath;
6959 this.codePathString = codePath.toString();
6960 this.resourcePath = resourcePath;
6961 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006962 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006963 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006964
Jacek Surazski65e13172009-04-28 15:26:38 +02006965 public void setInstallerPackageName(String packageName) {
6966 installerPackageName = packageName;
6967 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006968
Jacek Surazski65e13172009-04-28 15:26:38 +02006969 String getInstallerPackageName() {
6970 return installerPackageName;
6971 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 public void setInstallStatus(int newStatus) {
6974 installStatus = newStatus;
6975 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006977 public int getInstallStatus() {
6978 return installStatus;
6979 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006981 public void setTimeStamp(long newStamp) {
6982 if (newStamp != timeStamp) {
6983 timeStamp = newStamp;
6984 timeStampString = Long.toString(newStamp);
6985 }
6986 }
6987
6988 public void setTimeStamp(long newStamp, String newStampStr) {
6989 timeStamp = newStamp;
6990 timeStampString = newStampStr;
6991 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006993 public long getTimeStamp() {
6994 return timeStamp;
6995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997 public String getTimeStampStr() {
6998 return timeStampString;
6999 }
7000
7001 public void copyFrom(PackageSettingBase base) {
7002 grantedPermissions = base.grantedPermissions;
7003 gids = base.gids;
7004 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007006 timeStamp = base.timeStamp;
7007 timeStampString = base.timeStampString;
7008 signatures = base.signatures;
7009 permissionsFixed = base.permissionsFixed;
7010 disabledComponents = base.disabledComponents;
7011 enabledComponents = base.enabledComponents;
7012 enabled = base.enabled;
7013 installStatus = base.installStatus;
7014 }
7015
7016 void enableComponentLP(String componentClassName) {
7017 disabledComponents.remove(componentClassName);
7018 enabledComponents.add(componentClassName);
7019 }
7020
7021 void disableComponentLP(String componentClassName) {
7022 enabledComponents.remove(componentClassName);
7023 disabledComponents.add(componentClassName);
7024 }
7025
7026 void restoreComponentLP(String componentClassName) {
7027 enabledComponents.remove(componentClassName);
7028 disabledComponents.remove(componentClassName);
7029 }
7030
7031 int currentEnabledStateLP(String componentName) {
7032 if (enabledComponents.contains(componentName)) {
7033 return COMPONENT_ENABLED_STATE_ENABLED;
7034 } else if (disabledComponents.contains(componentName)) {
7035 return COMPONENT_ENABLED_STATE_DISABLED;
7036 } else {
7037 return COMPONENT_ENABLED_STATE_DEFAULT;
7038 }
7039 }
7040 }
7041
7042 /**
7043 * Settings data for a particular package we know about.
7044 */
7045 static final class PackageSetting extends PackageSettingBase {
7046 int userId;
7047 PackageParser.Package pkg;
7048 SharedUserSetting sharedUser;
7049
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007050 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007051 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007052 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 @Override
7056 public String toString() {
7057 return "PackageSetting{"
7058 + Integer.toHexString(System.identityHashCode(this))
7059 + " " + name + "/" + userId + "}";
7060 }
7061 }
7062
7063 /**
7064 * Settings data for a particular shared user ID we know about.
7065 */
7066 static final class SharedUserSetting extends GrantedPermissions {
7067 final String name;
7068 int userId;
7069 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7070 final PackageSignatures signatures = new PackageSignatures();
7071
7072 SharedUserSetting(String _name, int _pkgFlags) {
7073 super(_pkgFlags);
7074 name = _name;
7075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007077 @Override
7078 public String toString() {
7079 return "SharedUserSetting{"
7080 + Integer.toHexString(System.identityHashCode(this))
7081 + " " + name + "/" + userId + "}";
7082 }
7083 }
7084
7085 /**
7086 * Holds information about dynamic settings.
7087 */
7088 private static final class Settings {
7089 private final File mSettingsFilename;
7090 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007091 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 private final HashMap<String, PackageSetting> mPackages =
7093 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 // List of replaced system applications
7095 final HashMap<String, PackageSetting> mDisabledSysPackages =
7096 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007098 // The user's preferred activities associated with particular intent
7099 // filters.
7100 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7101 new IntentResolver<PreferredActivity, PreferredActivity>() {
7102 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007103 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007104 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007105 out.print(prefix); out.print(
7106 Integer.toHexString(System.identityHashCode(filter)));
7107 out.print(' ');
7108 out.print(filter.mActivity.flattenToShortString());
7109 out.print(" match=0x");
7110 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007111 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007112 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007113 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007114 out.print(prefix); out.print(" ");
7115 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007116 }
7117 }
7118 }
7119 };
7120 private final HashMap<String, SharedUserSetting> mSharedUsers =
7121 new HashMap<String, SharedUserSetting>();
7122 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7123 private final SparseArray<Object> mOtherUserIds =
7124 new SparseArray<Object>();
7125
7126 // For reading/writing settings file.
7127 private final ArrayList<Signature> mPastSignatures =
7128 new ArrayList<Signature>();
7129
7130 // Mapping from permission names to info about them.
7131 final HashMap<String, BasePermission> mPermissions =
7132 new HashMap<String, BasePermission>();
7133
7134 // Mapping from permission tree names to info about them.
7135 final HashMap<String, BasePermission> mPermissionTrees =
7136 new HashMap<String, BasePermission>();
7137
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007138 // Packages that have been uninstalled and still need their external
7139 // storage data deleted.
7140 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7141
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007142 // Packages that have been renamed since they were first installed.
7143 // Keys are the new names of the packages, values are the original
7144 // names. The packages appear everwhere else under their original
7145 // names.
7146 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007148 private final StringBuilder mReadMessages = new StringBuilder();
7149
7150 private static final class PendingPackage extends PackageSettingBase {
7151 final int sharedId;
7152
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007153 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007154 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007155 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007156 this.sharedId = sharedId;
7157 }
7158 }
7159 private final ArrayList<PendingPackage> mPendingPackages
7160 = new ArrayList<PendingPackage>();
7161
7162 Settings() {
7163 File dataDir = Environment.getDataDirectory();
7164 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007165 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7166 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007167 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007168 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007169 FileUtils.setPermissions(systemDir.toString(),
7170 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7171 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7172 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007173 FileUtils.setPermissions(systemSecureDir.toString(),
7174 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7175 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7176 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 mSettingsFilename = new File(systemDir, "packages.xml");
7178 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007179 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007180 }
7181
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007182 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007183 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 int pkgFlags, boolean create, boolean add) {
7185 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007186 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007187 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007188 return p;
7189 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007190
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007191 PackageSetting peekPackageLP(String name) {
7192 return mPackages.get(name);
7193 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007194 PackageSetting p = mPackages.get(name);
7195 if (p != null && p.codePath.getPath().equals(codePath)) {
7196 return p;
7197 }
7198 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007199 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007200 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007202 void setInstallStatus(String pkgName, int status) {
7203 PackageSetting p = mPackages.get(pkgName);
7204 if(p != null) {
7205 if(p.getInstallStatus() != status) {
7206 p.setInstallStatus(status);
7207 }
7208 }
7209 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007210
Jacek Surazski65e13172009-04-28 15:26:38 +02007211 void setInstallerPackageName(String pkgName,
7212 String installerPkgName) {
7213 PackageSetting p = mPackages.get(pkgName);
7214 if(p != null) {
7215 p.setInstallerPackageName(installerPkgName);
7216 }
7217 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007218
Jacek Surazski65e13172009-04-28 15:26:38 +02007219 String getInstallerPackageName(String pkgName) {
7220 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007221 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007222 }
7223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 int getInstallStatus(String pkgName) {
7225 PackageSetting p = mPackages.get(pkgName);
7226 if(p != null) {
7227 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007229 return -1;
7230 }
7231
7232 SharedUserSetting getSharedUserLP(String name,
7233 int pkgFlags, boolean create) {
7234 SharedUserSetting s = mSharedUsers.get(name);
7235 if (s == null) {
7236 if (!create) {
7237 return null;
7238 }
7239 s = new SharedUserSetting(name, pkgFlags);
7240 if (MULTIPLE_APPLICATION_UIDS) {
7241 s.userId = newUserIdLP(s);
7242 } else {
7243 s.userId = FIRST_APPLICATION_UID;
7244 }
7245 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7246 // < 0 means we couldn't assign a userid; fall out and return
7247 // s, which is currently null
7248 if (s.userId >= 0) {
7249 mSharedUsers.put(name, s);
7250 }
7251 }
7252
7253 return s;
7254 }
7255
7256 int disableSystemPackageLP(String name) {
7257 PackageSetting p = mPackages.get(name);
7258 if(p == null) {
7259 Log.w(TAG, "Package:"+name+" is not an installed package");
7260 return -1;
7261 }
7262 PackageSetting dp = mDisabledSysPackages.get(name);
7263 // always make sure the system package code and resource paths dont change
7264 if(dp == null) {
7265 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7266 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7267 }
7268 mDisabledSysPackages.put(name, p);
7269 }
7270 return removePackageLP(name);
7271 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007273 PackageSetting enableSystemPackageLP(String name) {
7274 PackageSetting p = mDisabledSysPackages.get(name);
7275 if(p == null) {
7276 Log.w(TAG, "Package:"+name+" is not disabled");
7277 return null;
7278 }
7279 // Reset flag in ApplicationInfo object
7280 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7281 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7282 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007283 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007284 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007285 mDisabledSysPackages.remove(name);
7286 return ret;
7287 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007288
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007289 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007290 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 PackageSetting p = mPackages.get(name);
7292 if (p != null) {
7293 if (p.userId == uid) {
7294 return p;
7295 }
7296 reportSettingsProblem(Log.ERROR,
7297 "Adding duplicate package, keeping first: " + name);
7298 return null;
7299 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007300 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 p.userId = uid;
7302 if (addUserIdLP(uid, p, name)) {
7303 mPackages.put(name, p);
7304 return p;
7305 }
7306 return null;
7307 }
7308
7309 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7310 SharedUserSetting s = mSharedUsers.get(name);
7311 if (s != null) {
7312 if (s.userId == uid) {
7313 return s;
7314 }
7315 reportSettingsProblem(Log.ERROR,
7316 "Adding duplicate shared user, keeping first: " + name);
7317 return null;
7318 }
7319 s = new SharedUserSetting(name, pkgFlags);
7320 s.userId = uid;
7321 if (addUserIdLP(uid, s, name)) {
7322 mSharedUsers.put(name, s);
7323 return s;
7324 }
7325 return null;
7326 }
7327
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007328 // Transfer ownership of permissions from one package to another.
7329 private void transferPermissions(String origPkg, String newPkg) {
7330 // Transfer ownership of permissions to the new package.
7331 for (int i=0; i<2; i++) {
7332 HashMap<String, BasePermission> permissions =
7333 i == 0 ? mPermissionTrees : mPermissions;
7334 for (BasePermission bp : permissions.values()) {
7335 if (origPkg.equals(bp.sourcePackage)) {
7336 if (DEBUG_UPGRADE) Log.v(TAG,
7337 "Moving permission " + bp.name
7338 + " from pkg " + bp.sourcePackage
7339 + " to " + newPkg);
7340 bp.sourcePackage = newPkg;
7341 bp.perm = null;
7342 if (bp.pendingInfo != null) {
7343 bp.sourcePackage = newPkg;
7344 }
7345 bp.uid = 0;
7346 bp.gids = null;
7347 }
7348 }
7349 }
7350 }
7351
7352 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007353 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007354 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007355 PackageSetting p = mPackages.get(name);
7356 if (p != null) {
7357 if (!p.codePath.equals(codePath)) {
7358 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007359 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007360 // This is an updated system app with versions in both system
7361 // and data partition. Just let the most recent version
7362 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007363 Log.w(TAG, "Trying to update system app code path from " +
7364 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007365 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007366 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07007367 reportSettingsProblem(Log.WARN,
7368 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007369 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007370 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007371 }
7372 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 reportSettingsProblem(Log.WARN,
7374 "Package " + name + " shared user changed from "
7375 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7376 + " to "
7377 + (sharedUser != null ? sharedUser.name : "<nothing>")
7378 + "; replacing with new");
7379 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007380 } else {
7381 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7382 // If what we are scanning is a system package, then
7383 // make it so, regardless of whether it was previously
7384 // installed only in the data partition.
7385 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007387 }
7388 }
7389 if (p == null) {
7390 // Create a new PackageSettings entry. this can end up here because
7391 // of code path mismatch or user id mismatch of an updated system partition
7392 if (!create) {
7393 return null;
7394 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007395 if (origPackage != null) {
7396 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007397 p = new PackageSetting(origPackage.name, name, codePath,
7398 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007399 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7400 + " is adopting original package " + origPackage.name);
7401 p.copyFrom(origPackage);
7402 p.sharedUser = origPackage.sharedUser;
7403 p.userId = origPackage.userId;
7404 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007405 mRenamedPackages.put(name, origPackage.name);
7406 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007407 // Update new package state.
7408 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007410 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007411 p.setTimeStamp(codePath.lastModified());
7412 p.sharedUser = sharedUser;
7413 if (sharedUser != null) {
7414 p.userId = sharedUser.userId;
7415 } else if (MULTIPLE_APPLICATION_UIDS) {
7416 // Clone the setting here for disabled system packages
7417 PackageSetting dis = mDisabledSysPackages.get(name);
7418 if (dis != null) {
7419 // For disabled packages a new setting is created
7420 // from the existing user id. This still has to be
7421 // added to list of user id's
7422 // Copy signatures from previous setting
7423 if (dis.signatures.mSignatures != null) {
7424 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7425 }
7426 p.userId = dis.userId;
7427 // Clone permissions
7428 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7429 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7430 // Clone component info
7431 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7432 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7433 // Add new setting to list of user ids
7434 addUserIdLP(p.userId, p, name);
7435 } else {
7436 // Assign new user id
7437 p.userId = newUserIdLP(p);
7438 }
7439 } else {
7440 p.userId = FIRST_APPLICATION_UID;
7441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007442 }
7443 if (p.userId < 0) {
7444 reportSettingsProblem(Log.WARN,
7445 "Package " + name + " could not be assigned a valid uid");
7446 return null;
7447 }
7448 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007449 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007450 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007451 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007452 }
7453 }
7454 return p;
7455 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007456
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007457 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007458 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007459 String codePath = pkg.applicationInfo.sourceDir;
7460 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007461 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007462 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007463 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007464 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007465 p.codePath = new File(codePath);
7466 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007467 }
7468 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007469 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007470 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007471 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007472 p.resourcePath = new File(resourcePath);
7473 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007474 }
7475 // Update version code if needed
7476 if (pkg.mVersionCode != p.versionCode) {
7477 p.versionCode = pkg.mVersionCode;
7478 }
7479 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7480 }
7481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007482 // Utility method that adds a PackageSetting to mPackages and
7483 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007484 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007485 SharedUserSetting sharedUser) {
7486 mPackages.put(name, p);
7487 if (sharedUser != null) {
7488 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7489 reportSettingsProblem(Log.ERROR,
7490 "Package " + p.name + " was user "
7491 + p.sharedUser + " but is now " + sharedUser
7492 + "; I am not changing its files so it will probably fail!");
7493 p.sharedUser.packages.remove(p);
7494 } else if (p.userId != sharedUser.userId) {
7495 reportSettingsProblem(Log.ERROR,
7496 "Package " + p.name + " was user id " + p.userId
7497 + " but is now user " + sharedUser
7498 + " with id " + sharedUser.userId
7499 + "; I am not changing its files so it will probably fail!");
7500 }
7501
7502 sharedUser.packages.add(p);
7503 p.sharedUser = sharedUser;
7504 p.userId = sharedUser.userId;
7505 }
7506 }
7507
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007508 /*
7509 * Update the shared user setting when a package using
7510 * specifying the shared user id is removed. The gids
7511 * associated with each permission of the deleted package
7512 * are removed from the shared user's gid list only if its
7513 * not in use by other permissions of packages in the
7514 * shared user setting.
7515 */
7516 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007517 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7518 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7519 return;
7520 }
7521 // No sharedUserId
7522 if (deletedPs.sharedUser == null) {
7523 return;
7524 }
7525 SharedUserSetting sus = deletedPs.sharedUser;
7526 // Update permissions
7527 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7528 boolean used = false;
7529 if (!sus.grantedPermissions.contains (eachPerm)) {
7530 continue;
7531 }
7532 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007533 if (pkg.pkg != null &&
7534 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7535 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 used = true;
7537 break;
7538 }
7539 }
7540 if (!used) {
7541 // can safely delete this permission from list
7542 sus.grantedPermissions.remove(eachPerm);
7543 sus.loadedPermissions.remove(eachPerm);
7544 }
7545 }
7546 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007547 int newGids[] = globalGids;
7548 for (String eachPerm : sus.grantedPermissions) {
7549 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007550 if (bp != null) {
7551 newGids = appendInts(newGids, bp.gids);
7552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007553 }
7554 sus.gids = newGids;
7555 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557 private int removePackageLP(String name) {
7558 PackageSetting p = mPackages.get(name);
7559 if (p != null) {
7560 mPackages.remove(name);
7561 if (p.sharedUser != null) {
7562 p.sharedUser.packages.remove(p);
7563 if (p.sharedUser.packages.size() == 0) {
7564 mSharedUsers.remove(p.sharedUser.name);
7565 removeUserIdLP(p.sharedUser.userId);
7566 return p.sharedUser.userId;
7567 }
7568 } else {
7569 removeUserIdLP(p.userId);
7570 return p.userId;
7571 }
7572 }
7573 return -1;
7574 }
7575
7576 private boolean addUserIdLP(int uid, Object obj, Object name) {
7577 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7578 return false;
7579 }
7580
7581 if (uid >= FIRST_APPLICATION_UID) {
7582 int N = mUserIds.size();
7583 final int index = uid - FIRST_APPLICATION_UID;
7584 while (index >= N) {
7585 mUserIds.add(null);
7586 N++;
7587 }
7588 if (mUserIds.get(index) != null) {
7589 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007590 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591 + " name=" + name);
7592 return false;
7593 }
7594 mUserIds.set(index, obj);
7595 } else {
7596 if (mOtherUserIds.get(uid) != null) {
7597 reportSettingsProblem(Log.ERROR,
7598 "Adding duplicate shared id: " + uid
7599 + " name=" + name);
7600 return false;
7601 }
7602 mOtherUserIds.put(uid, obj);
7603 }
7604 return true;
7605 }
7606
7607 public Object getUserIdLP(int uid) {
7608 if (uid >= FIRST_APPLICATION_UID) {
7609 int N = mUserIds.size();
7610 final int index = uid - FIRST_APPLICATION_UID;
7611 return index < N ? mUserIds.get(index) : null;
7612 } else {
7613 return mOtherUserIds.get(uid);
7614 }
7615 }
7616
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007617 private Set<String> findPackagesWithFlag(int flag) {
7618 Set<String> ret = new HashSet<String>();
7619 for (PackageSetting ps : mPackages.values()) {
7620 // Has to match atleast all the flag bits set on flag
7621 if ((ps.pkgFlags & flag) == flag) {
7622 ret.add(ps.name);
7623 }
7624 }
7625 return ret;
7626 }
7627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628 private void removeUserIdLP(int uid) {
7629 if (uid >= FIRST_APPLICATION_UID) {
7630 int N = mUserIds.size();
7631 final int index = uid - FIRST_APPLICATION_UID;
7632 if (index < N) mUserIds.set(index, null);
7633 } else {
7634 mOtherUserIds.remove(uid);
7635 }
7636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007638 void writeLP() {
7639 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7640
7641 // Keep the old settings around until we know the new ones have
7642 // been successfully written.
7643 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007644 // Presence of backup settings file indicates that we failed
7645 // to persist settings earlier. So preserve the older
7646 // backup for future reference since the current settings
7647 // might have been corrupted.
7648 if (!mBackupSettingsFilename.exists()) {
7649 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7650 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7651 return;
7652 }
7653 } else {
7654 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 }
7657
7658 mPastSignatures.clear();
7659
7660 try {
7661 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7662
7663 //XmlSerializer serializer = XmlUtils.serializerInstance();
7664 XmlSerializer serializer = new FastXmlSerializer();
7665 serializer.setOutput(str, "utf-8");
7666 serializer.startDocument(null, true);
7667 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7668
7669 serializer.startTag(null, "packages");
7670
7671 serializer.startTag(null, "permission-trees");
7672 for (BasePermission bp : mPermissionTrees.values()) {
7673 writePermission(serializer, bp);
7674 }
7675 serializer.endTag(null, "permission-trees");
7676
7677 serializer.startTag(null, "permissions");
7678 for (BasePermission bp : mPermissions.values()) {
7679 writePermission(serializer, bp);
7680 }
7681 serializer.endTag(null, "permissions");
7682
7683 for (PackageSetting pkg : mPackages.values()) {
7684 writePackage(serializer, pkg);
7685 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7688 writeDisabledSysPackage(serializer, pkg);
7689 }
7690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007691 serializer.startTag(null, "preferred-activities");
7692 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7693 serializer.startTag(null, "item");
7694 pa.writeToXml(serializer);
7695 serializer.endTag(null, "item");
7696 }
7697 serializer.endTag(null, "preferred-activities");
7698
7699 for (SharedUserSetting usr : mSharedUsers.values()) {
7700 serializer.startTag(null, "shared-user");
7701 serializer.attribute(null, "name", usr.name);
7702 serializer.attribute(null, "userId",
7703 Integer.toString(usr.userId));
7704 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7705 serializer.startTag(null, "perms");
7706 for (String name : usr.grantedPermissions) {
7707 serializer.startTag(null, "item");
7708 serializer.attribute(null, "name", name);
7709 serializer.endTag(null, "item");
7710 }
7711 serializer.endTag(null, "perms");
7712 serializer.endTag(null, "shared-user");
7713 }
7714
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007715 if (mPackagesToBeCleaned.size() > 0) {
7716 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7717 serializer.startTag(null, "cleaning-package");
7718 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7719 serializer.endTag(null, "cleaning-package");
7720 }
7721 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007722
7723 if (mRenamedPackages.size() > 0) {
7724 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
7725 serializer.startTag(null, "renamed-package");
7726 serializer.attribute(null, "new", e.getKey());
7727 serializer.attribute(null, "old", e.getValue());
7728 serializer.endTag(null, "renamed-package");
7729 }
7730 }
7731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732 serializer.endTag(null, "packages");
7733
7734 serializer.endDocument();
7735
7736 str.flush();
7737 str.close();
7738
7739 // New settings successfully written, old ones are no longer
7740 // needed.
7741 mBackupSettingsFilename.delete();
7742 FileUtils.setPermissions(mSettingsFilename.toString(),
7743 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7744 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7745 |FileUtils.S_IROTH,
7746 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007747
7748 // Write package list file now, use a JournaledFile.
7749 //
7750 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
7751 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
7752
7753 str = new FileOutputStream(journal.chooseForWrite());
7754 try {
7755 StringBuilder sb = new StringBuilder();
7756 for (PackageSetting pkg : mPackages.values()) {
7757 ApplicationInfo ai = pkg.pkg.applicationInfo;
7758 String dataPath = ai.dataDir;
7759 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7760
7761 // Avoid any application that has a space in its path
7762 // or that is handled by the system.
7763 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
7764 continue;
7765
7766 // we store on each line the following information for now:
7767 //
7768 // pkgName - package name
7769 // userId - application-specific user id
7770 // debugFlag - 0 or 1 if the package is debuggable.
7771 // dataPath - path to package's data path
7772 //
7773 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
7774 //
7775 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
7776 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
7777 // system/core/run-as/run-as.c
7778 //
7779 sb.setLength(0);
7780 sb.append(ai.packageName);
7781 sb.append(" ");
7782 sb.append((int)ai.uid);
7783 sb.append(isDebug ? " 1 " : " 0 ");
7784 sb.append(dataPath);
7785 sb.append("\n");
7786 str.write(sb.toString().getBytes());
7787 }
7788 str.flush();
7789 str.close();
7790 journal.commit();
7791 }
7792 catch (Exception e) {
7793 journal.rollback();
7794 }
7795
7796 FileUtils.setPermissions(mPackageListFilename.toString(),
7797 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7798 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7799 |FileUtils.S_IROTH,
7800 -1, -1);
7801
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007802 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803
7804 } catch(XmlPullParserException e) {
7805 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 -08007806 } catch(java.io.IOException e) {
7807 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 -08007808 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007809 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007810 if (mSettingsFilename.exists()) {
7811 if (!mSettingsFilename.delete()) {
7812 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7813 }
7814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 //Debug.stopMethodTracing();
7816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007817
7818 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007819 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 serializer.startTag(null, "updated-package");
7821 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007822 if (pkg.realName != null) {
7823 serializer.attribute(null, "realName", pkg.realName);
7824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825 serializer.attribute(null, "codePath", pkg.codePathString);
7826 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007827 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7829 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7830 }
7831 if (pkg.sharedUser == null) {
7832 serializer.attribute(null, "userId",
7833 Integer.toString(pkg.userId));
7834 } else {
7835 serializer.attribute(null, "sharedUserId",
7836 Integer.toString(pkg.userId));
7837 }
7838 serializer.startTag(null, "perms");
7839 if (pkg.sharedUser == null) {
7840 // If this is a shared user, the permissions will
7841 // be written there. We still need to write an
7842 // empty permissions list so permissionsFixed will
7843 // be set.
7844 for (final String name : pkg.grantedPermissions) {
7845 BasePermission bp = mPermissions.get(name);
7846 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7847 // We only need to write signature or system permissions but this wont
7848 // match the semantics of grantedPermissions. So write all permissions.
7849 serializer.startTag(null, "item");
7850 serializer.attribute(null, "name", name);
7851 serializer.endTag(null, "item");
7852 }
7853 }
7854 }
7855 serializer.endTag(null, "perms");
7856 serializer.endTag(null, "updated-package");
7857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007858
7859 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007860 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 serializer.startTag(null, "package");
7862 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007863 if (pkg.realName != null) {
7864 serializer.attribute(null, "realName", pkg.realName);
7865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 serializer.attribute(null, "codePath", pkg.codePathString);
7867 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7868 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7869 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007870 serializer.attribute(null, "flags",
7871 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007873 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 if (pkg.sharedUser == null) {
7875 serializer.attribute(null, "userId",
7876 Integer.toString(pkg.userId));
7877 } else {
7878 serializer.attribute(null, "sharedUserId",
7879 Integer.toString(pkg.userId));
7880 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007881 if (pkg.uidError) {
7882 serializer.attribute(null, "uidError", "true");
7883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7885 serializer.attribute(null, "enabled",
7886 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7887 ? "true" : "false");
7888 }
7889 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7890 serializer.attribute(null, "installStatus", "false");
7891 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007892 if (pkg.installerPackageName != null) {
7893 serializer.attribute(null, "installer", pkg.installerPackageName);
7894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7896 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7897 serializer.startTag(null, "perms");
7898 if (pkg.sharedUser == null) {
7899 // If this is a shared user, the permissions will
7900 // be written there. We still need to write an
7901 // empty permissions list so permissionsFixed will
7902 // be set.
7903 for (final String name : pkg.grantedPermissions) {
7904 serializer.startTag(null, "item");
7905 serializer.attribute(null, "name", name);
7906 serializer.endTag(null, "item");
7907 }
7908 }
7909 serializer.endTag(null, "perms");
7910 }
7911 if (pkg.disabledComponents.size() > 0) {
7912 serializer.startTag(null, "disabled-components");
7913 for (final String name : pkg.disabledComponents) {
7914 serializer.startTag(null, "item");
7915 serializer.attribute(null, "name", name);
7916 serializer.endTag(null, "item");
7917 }
7918 serializer.endTag(null, "disabled-components");
7919 }
7920 if (pkg.enabledComponents.size() > 0) {
7921 serializer.startTag(null, "enabled-components");
7922 for (final String name : pkg.enabledComponents) {
7923 serializer.startTag(null, "item");
7924 serializer.attribute(null, "name", name);
7925 serializer.endTag(null, "item");
7926 }
7927 serializer.endTag(null, "enabled-components");
7928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 serializer.endTag(null, "package");
7931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 void writePermission(XmlSerializer serializer, BasePermission bp)
7934 throws XmlPullParserException, java.io.IOException {
7935 if (bp.type != BasePermission.TYPE_BUILTIN
7936 && bp.sourcePackage != null) {
7937 serializer.startTag(null, "item");
7938 serializer.attribute(null, "name", bp.name);
7939 serializer.attribute(null, "package", bp.sourcePackage);
7940 if (DEBUG_SETTINGS) Log.v(TAG,
7941 "Writing perm: name=" + bp.name + " type=" + bp.type);
7942 if (bp.type == BasePermission.TYPE_DYNAMIC) {
7943 PermissionInfo pi = bp.perm != null ? bp.perm.info
7944 : bp.pendingInfo;
7945 if (pi != null) {
7946 serializer.attribute(null, "type", "dynamic");
7947 if (pi.icon != 0) {
7948 serializer.attribute(null, "icon",
7949 Integer.toString(pi.icon));
7950 }
7951 if (pi.nonLocalizedLabel != null) {
7952 serializer.attribute(null, "label",
7953 pi.nonLocalizedLabel.toString());
7954 }
7955 if (pi.protectionLevel !=
7956 PermissionInfo.PROTECTION_NORMAL) {
7957 serializer.attribute(null, "protection",
7958 Integer.toString(pi.protectionLevel));
7959 }
7960 }
7961 }
7962 serializer.endTag(null, "item");
7963 }
7964 }
7965
7966 String getReadMessagesLP() {
7967 return mReadMessages.toString();
7968 }
7969
Oscar Montemayora8529f62009-11-18 10:14:20 -08007970 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
7972 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007973 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 while(its.hasNext()) {
7975 String key = its.next();
7976 PackageSetting ps = mPackages.get(key);
7977 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08007978 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 }
7980 }
7981 return ret;
7982 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 boolean readLP() {
7985 FileInputStream str = null;
7986 if (mBackupSettingsFilename.exists()) {
7987 try {
7988 str = new FileInputStream(mBackupSettingsFilename);
7989 mReadMessages.append("Reading from backup settings file\n");
7990 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007991 if (mSettingsFilename.exists()) {
7992 // If both the backup and settings file exist, we
7993 // ignore the settings since it might have been
7994 // corrupted.
7995 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
7996 mSettingsFilename.delete();
7997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 } catch (java.io.IOException e) {
7999 // We'll try for the normal settings file.
8000 }
8001 }
8002
8003 mPastSignatures.clear();
8004
8005 try {
8006 if (str == null) {
8007 if (!mSettingsFilename.exists()) {
8008 mReadMessages.append("No settings file found\n");
8009 Log.i(TAG, "No current settings file!");
8010 return false;
8011 }
8012 str = new FileInputStream(mSettingsFilename);
8013 }
8014 XmlPullParser parser = Xml.newPullParser();
8015 parser.setInput(str, null);
8016
8017 int type;
8018 while ((type=parser.next()) != XmlPullParser.START_TAG
8019 && type != XmlPullParser.END_DOCUMENT) {
8020 ;
8021 }
8022
8023 if (type != XmlPullParser.START_TAG) {
8024 mReadMessages.append("No start tag found in settings file\n");
8025 Log.e(TAG, "No start tag found in package manager settings");
8026 return false;
8027 }
8028
8029 int outerDepth = parser.getDepth();
8030 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8031 && (type != XmlPullParser.END_TAG
8032 || parser.getDepth() > outerDepth)) {
8033 if (type == XmlPullParser.END_TAG
8034 || type == XmlPullParser.TEXT) {
8035 continue;
8036 }
8037
8038 String tagName = parser.getName();
8039 if (tagName.equals("package")) {
8040 readPackageLP(parser);
8041 } else if (tagName.equals("permissions")) {
8042 readPermissionsLP(mPermissions, parser);
8043 } else if (tagName.equals("permission-trees")) {
8044 readPermissionsLP(mPermissionTrees, parser);
8045 } else if (tagName.equals("shared-user")) {
8046 readSharedUserLP(parser);
8047 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008048 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 } else if (tagName.equals("preferred-activities")) {
8050 readPreferredActivitiesLP(parser);
8051 } else if(tagName.equals("updated-package")) {
8052 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008053 } else if (tagName.equals("cleaning-package")) {
8054 String name = parser.getAttributeValue(null, "name");
8055 if (name != null) {
8056 mPackagesToBeCleaned.add(name);
8057 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008058 } else if (tagName.equals("renamed-package")) {
8059 String nname = parser.getAttributeValue(null, "new");
8060 String oname = parser.getAttributeValue(null, "old");
8061 if (nname != null && oname != null) {
8062 mRenamedPackages.put(nname, oname);
8063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 } else {
8065 Log.w(TAG, "Unknown element under <packages>: "
8066 + parser.getName());
8067 XmlUtils.skipCurrentTag(parser);
8068 }
8069 }
8070
8071 str.close();
8072
8073 } catch(XmlPullParserException e) {
8074 mReadMessages.append("Error reading: " + e.toString());
8075 Log.e(TAG, "Error reading package manager settings", e);
8076
8077 } catch(java.io.IOException e) {
8078 mReadMessages.append("Error reading: " + e.toString());
8079 Log.e(TAG, "Error reading package manager settings", e);
8080
8081 }
8082
8083 int N = mPendingPackages.size();
8084 for (int i=0; i<N; i++) {
8085 final PendingPackage pp = mPendingPackages.get(i);
8086 Object idObj = getUserIdLP(pp.sharedId);
8087 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008088 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008090 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008091 if (p == null) {
8092 Log.w(TAG, "Unable to create application package for "
8093 + pp.name);
8094 continue;
8095 }
8096 p.copyFrom(pp);
8097 } else if (idObj != null) {
8098 String msg = "Bad package setting: package " + pp.name
8099 + " has shared uid " + pp.sharedId
8100 + " that is not a shared uid\n";
8101 mReadMessages.append(msg);
8102 Log.e(TAG, msg);
8103 } else {
8104 String msg = "Bad package setting: package " + pp.name
8105 + " has shared uid " + pp.sharedId
8106 + " that is not defined\n";
8107 mReadMessages.append(msg);
8108 Log.e(TAG, msg);
8109 }
8110 }
8111 mPendingPackages.clear();
8112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 mReadMessages.append("Read completed successfully: "
8114 + mPackages.size() + " packages, "
8115 + mSharedUsers.size() + " shared uids\n");
8116
8117 return true;
8118 }
8119
8120 private int readInt(XmlPullParser parser, String ns, String name,
8121 int defValue) {
8122 String v = parser.getAttributeValue(ns, name);
8123 try {
8124 if (v == null) {
8125 return defValue;
8126 }
8127 return Integer.parseInt(v);
8128 } catch (NumberFormatException e) {
8129 reportSettingsProblem(Log.WARN,
8130 "Error in package manager settings: attribute " +
8131 name + " has bad integer value " + v + " at "
8132 + parser.getPositionDescription());
8133 }
8134 return defValue;
8135 }
8136
8137 private void readPermissionsLP(HashMap<String, BasePermission> out,
8138 XmlPullParser parser)
8139 throws IOException, XmlPullParserException {
8140 int outerDepth = parser.getDepth();
8141 int type;
8142 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8143 && (type != XmlPullParser.END_TAG
8144 || parser.getDepth() > outerDepth)) {
8145 if (type == XmlPullParser.END_TAG
8146 || type == XmlPullParser.TEXT) {
8147 continue;
8148 }
8149
8150 String tagName = parser.getName();
8151 if (tagName.equals("item")) {
8152 String name = parser.getAttributeValue(null, "name");
8153 String sourcePackage = parser.getAttributeValue(null, "package");
8154 String ptype = parser.getAttributeValue(null, "type");
8155 if (name != null && sourcePackage != null) {
8156 boolean dynamic = "dynamic".equals(ptype);
8157 BasePermission bp = new BasePermission(name, sourcePackage,
8158 dynamic
8159 ? BasePermission.TYPE_DYNAMIC
8160 : BasePermission.TYPE_NORMAL);
8161 if (dynamic) {
8162 PermissionInfo pi = new PermissionInfo();
8163 pi.packageName = sourcePackage.intern();
8164 pi.name = name.intern();
8165 pi.icon = readInt(parser, null, "icon", 0);
8166 pi.nonLocalizedLabel = parser.getAttributeValue(
8167 null, "label");
8168 pi.protectionLevel = readInt(parser, null, "protection",
8169 PermissionInfo.PROTECTION_NORMAL);
8170 bp.pendingInfo = pi;
8171 }
8172 out.put(bp.name, bp);
8173 } else {
8174 reportSettingsProblem(Log.WARN,
8175 "Error in package manager settings: permissions has"
8176 + " no name at " + parser.getPositionDescription());
8177 }
8178 } else {
8179 reportSettingsProblem(Log.WARN,
8180 "Unknown element reading permissions: "
8181 + parser.getName() + " at "
8182 + parser.getPositionDescription());
8183 }
8184 XmlUtils.skipCurrentTag(parser);
8185 }
8186 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008188 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008189 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008191 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 String codePathStr = parser.getAttributeValue(null, "codePath");
8193 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008194 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008195 resourcePathStr = codePathStr;
8196 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008197 String version = parser.getAttributeValue(null, "version");
8198 int versionCode = 0;
8199 if (version != null) {
8200 try {
8201 versionCode = Integer.parseInt(version);
8202 } catch (NumberFormatException e) {
8203 }
8204 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008206 int pkgFlags = 0;
8207 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008208 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008209 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008210 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008211 String timeStampStr = parser.getAttributeValue(null, "ts");
8212 if (timeStampStr != null) {
8213 try {
8214 long timeStamp = Long.parseLong(timeStampStr);
8215 ps.setTimeStamp(timeStamp, timeStampStr);
8216 } catch (NumberFormatException e) {
8217 }
8218 }
8219 String idStr = parser.getAttributeValue(null, "userId");
8220 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8221 if(ps.userId <= 0) {
8222 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8223 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8224 }
8225 int outerDepth = parser.getDepth();
8226 int type;
8227 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8228 && (type != XmlPullParser.END_TAG
8229 || parser.getDepth() > outerDepth)) {
8230 if (type == XmlPullParser.END_TAG
8231 || type == XmlPullParser.TEXT) {
8232 continue;
8233 }
8234
8235 String tagName = parser.getName();
8236 if (tagName.equals("perms")) {
8237 readGrantedPermissionsLP(parser,
8238 ps.grantedPermissions);
8239 } else {
8240 reportSettingsProblem(Log.WARN,
8241 "Unknown element under <updated-package>: "
8242 + parser.getName());
8243 XmlUtils.skipCurrentTag(parser);
8244 }
8245 }
8246 mDisabledSysPackages.put(name, ps);
8247 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008249 private void readPackageLP(XmlPullParser parser)
8250 throws XmlPullParserException, IOException {
8251 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008252 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008253 String idStr = null;
8254 String sharedIdStr = null;
8255 String codePathStr = null;
8256 String resourcePathStr = null;
8257 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008258 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008259 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008260 int pkgFlags = 0;
8261 String timeStampStr;
8262 long timeStamp = 0;
8263 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008264 String version = null;
8265 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008266 try {
8267 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008268 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008269 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008270 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008271 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8272 codePathStr = parser.getAttributeValue(null, "codePath");
8273 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008274 version = parser.getAttributeValue(null, "version");
8275 if (version != null) {
8276 try {
8277 versionCode = Integer.parseInt(version);
8278 } catch (NumberFormatException e) {
8279 }
8280 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008281 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008282
8283 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008285 try {
8286 pkgFlags = Integer.parseInt(systemStr);
8287 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008288 }
8289 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008290 // For backward compatibility
8291 systemStr = parser.getAttributeValue(null, "system");
8292 if (systemStr != null) {
8293 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8294 } else {
8295 // Old settings that don't specify system... just treat
8296 // them as system, good enough.
8297 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008299 }
8300 timeStampStr = parser.getAttributeValue(null, "ts");
8301 if (timeStampStr != null) {
8302 try {
8303 timeStamp = Long.parseLong(timeStampStr);
8304 } catch (NumberFormatException e) {
8305 }
8306 }
8307 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8308 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8309 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8310 if (resourcePathStr == null) {
8311 resourcePathStr = codePathStr;
8312 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008313 if (realName != null) {
8314 realName = realName.intern();
8315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008316 if (name == null) {
8317 reportSettingsProblem(Log.WARN,
8318 "Error in package manager settings: <package> has no name at "
8319 + parser.getPositionDescription());
8320 } else if (codePathStr == null) {
8321 reportSettingsProblem(Log.WARN,
8322 "Error in package manager settings: <package> has no codePath at "
8323 + parser.getPositionDescription());
8324 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008325 packageSetting = addPackageLP(name.intern(), realName,
8326 new File(codePathStr), new File(resourcePathStr),
8327 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008328 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8329 + ": userId=" + userId + " pkg=" + packageSetting);
8330 if (packageSetting == null) {
8331 reportSettingsProblem(Log.ERROR,
8332 "Failure adding uid " + userId
8333 + " while parsing settings at "
8334 + parser.getPositionDescription());
8335 } else {
8336 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8337 }
8338 } else if (sharedIdStr != null) {
8339 userId = sharedIdStr != null
8340 ? Integer.parseInt(sharedIdStr) : 0;
8341 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008342 packageSetting = new PendingPackage(name.intern(), realName,
8343 new File(codePathStr), new File(resourcePathStr),
8344 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008345 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8346 mPendingPackages.add((PendingPackage) packageSetting);
8347 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8348 + ": sharedUserId=" + userId + " pkg="
8349 + packageSetting);
8350 } else {
8351 reportSettingsProblem(Log.WARN,
8352 "Error in package manager settings: package "
8353 + name + " has bad sharedId " + sharedIdStr
8354 + " at " + parser.getPositionDescription());
8355 }
8356 } else {
8357 reportSettingsProblem(Log.WARN,
8358 "Error in package manager settings: package "
8359 + name + " has bad userId " + idStr + " at "
8360 + parser.getPositionDescription());
8361 }
8362 } catch (NumberFormatException e) {
8363 reportSettingsProblem(Log.WARN,
8364 "Error in package manager settings: package "
8365 + name + " has bad userId " + idStr + " at "
8366 + parser.getPositionDescription());
8367 }
8368 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008369 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008370 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371 final String enabledStr = parser.getAttributeValue(null, "enabled");
8372 if (enabledStr != null) {
8373 if (enabledStr.equalsIgnoreCase("true")) {
8374 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8375 } else if (enabledStr.equalsIgnoreCase("false")) {
8376 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8377 } else if (enabledStr.equalsIgnoreCase("default")) {
8378 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8379 } else {
8380 reportSettingsProblem(Log.WARN,
8381 "Error in package manager settings: package "
8382 + name + " has bad enabled value: " + idStr
8383 + " at " + parser.getPositionDescription());
8384 }
8385 } else {
8386 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8387 }
8388 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8389 if (installStatusStr != null) {
8390 if (installStatusStr.equalsIgnoreCase("false")) {
8391 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8392 } else {
8393 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8394 }
8395 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008397 int outerDepth = parser.getDepth();
8398 int type;
8399 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8400 && (type != XmlPullParser.END_TAG
8401 || parser.getDepth() > outerDepth)) {
8402 if (type == XmlPullParser.END_TAG
8403 || type == XmlPullParser.TEXT) {
8404 continue;
8405 }
8406
8407 String tagName = parser.getName();
8408 if (tagName.equals("disabled-components")) {
8409 readDisabledComponentsLP(packageSetting, parser);
8410 } else if (tagName.equals("enabled-components")) {
8411 readEnabledComponentsLP(packageSetting, parser);
8412 } else if (tagName.equals("sigs")) {
8413 packageSetting.signatures.readXml(parser, mPastSignatures);
8414 } else if (tagName.equals("perms")) {
8415 readGrantedPermissionsLP(parser,
8416 packageSetting.loadedPermissions);
8417 packageSetting.permissionsFixed = true;
8418 } else {
8419 reportSettingsProblem(Log.WARN,
8420 "Unknown element under <package>: "
8421 + parser.getName());
8422 XmlUtils.skipCurrentTag(parser);
8423 }
8424 }
8425 } else {
8426 XmlUtils.skipCurrentTag(parser);
8427 }
8428 }
8429
8430 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8431 XmlPullParser parser)
8432 throws IOException, XmlPullParserException {
8433 int outerDepth = parser.getDepth();
8434 int type;
8435 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8436 && (type != XmlPullParser.END_TAG
8437 || parser.getDepth() > outerDepth)) {
8438 if (type == XmlPullParser.END_TAG
8439 || type == XmlPullParser.TEXT) {
8440 continue;
8441 }
8442
8443 String tagName = parser.getName();
8444 if (tagName.equals("item")) {
8445 String name = parser.getAttributeValue(null, "name");
8446 if (name != null) {
8447 packageSetting.disabledComponents.add(name.intern());
8448 } else {
8449 reportSettingsProblem(Log.WARN,
8450 "Error in package manager settings: <disabled-components> has"
8451 + " no name at " + parser.getPositionDescription());
8452 }
8453 } else {
8454 reportSettingsProblem(Log.WARN,
8455 "Unknown element under <disabled-components>: "
8456 + parser.getName());
8457 }
8458 XmlUtils.skipCurrentTag(parser);
8459 }
8460 }
8461
8462 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8463 XmlPullParser parser)
8464 throws IOException, XmlPullParserException {
8465 int outerDepth = parser.getDepth();
8466 int type;
8467 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8468 && (type != XmlPullParser.END_TAG
8469 || parser.getDepth() > outerDepth)) {
8470 if (type == XmlPullParser.END_TAG
8471 || type == XmlPullParser.TEXT) {
8472 continue;
8473 }
8474
8475 String tagName = parser.getName();
8476 if (tagName.equals("item")) {
8477 String name = parser.getAttributeValue(null, "name");
8478 if (name != null) {
8479 packageSetting.enabledComponents.add(name.intern());
8480 } else {
8481 reportSettingsProblem(Log.WARN,
8482 "Error in package manager settings: <enabled-components> has"
8483 + " no name at " + parser.getPositionDescription());
8484 }
8485 } else {
8486 reportSettingsProblem(Log.WARN,
8487 "Unknown element under <enabled-components>: "
8488 + parser.getName());
8489 }
8490 XmlUtils.skipCurrentTag(parser);
8491 }
8492 }
8493
8494 private void readSharedUserLP(XmlPullParser parser)
8495 throws XmlPullParserException, IOException {
8496 String name = null;
8497 String idStr = null;
8498 int pkgFlags = 0;
8499 SharedUserSetting su = null;
8500 try {
8501 name = parser.getAttributeValue(null, "name");
8502 idStr = parser.getAttributeValue(null, "userId");
8503 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8504 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8505 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8506 }
8507 if (name == null) {
8508 reportSettingsProblem(Log.WARN,
8509 "Error in package manager settings: <shared-user> has no name at "
8510 + parser.getPositionDescription());
8511 } else if (userId == 0) {
8512 reportSettingsProblem(Log.WARN,
8513 "Error in package manager settings: shared-user "
8514 + name + " has bad userId " + idStr + " at "
8515 + parser.getPositionDescription());
8516 } else {
8517 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8518 reportSettingsProblem(Log.ERROR,
8519 "Occurred while parsing settings at "
8520 + parser.getPositionDescription());
8521 }
8522 }
8523 } catch (NumberFormatException e) {
8524 reportSettingsProblem(Log.WARN,
8525 "Error in package manager settings: package "
8526 + name + " has bad userId " + idStr + " at "
8527 + parser.getPositionDescription());
8528 };
8529
8530 if (su != null) {
8531 int outerDepth = parser.getDepth();
8532 int type;
8533 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8534 && (type != XmlPullParser.END_TAG
8535 || parser.getDepth() > outerDepth)) {
8536 if (type == XmlPullParser.END_TAG
8537 || type == XmlPullParser.TEXT) {
8538 continue;
8539 }
8540
8541 String tagName = parser.getName();
8542 if (tagName.equals("sigs")) {
8543 su.signatures.readXml(parser, mPastSignatures);
8544 } else if (tagName.equals("perms")) {
8545 readGrantedPermissionsLP(parser, su.loadedPermissions);
8546 } else {
8547 reportSettingsProblem(Log.WARN,
8548 "Unknown element under <shared-user>: "
8549 + parser.getName());
8550 XmlUtils.skipCurrentTag(parser);
8551 }
8552 }
8553
8554 } else {
8555 XmlUtils.skipCurrentTag(parser);
8556 }
8557 }
8558
8559 private void readGrantedPermissionsLP(XmlPullParser parser,
8560 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8561 int outerDepth = parser.getDepth();
8562 int type;
8563 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8564 && (type != XmlPullParser.END_TAG
8565 || parser.getDepth() > outerDepth)) {
8566 if (type == XmlPullParser.END_TAG
8567 || type == XmlPullParser.TEXT) {
8568 continue;
8569 }
8570
8571 String tagName = parser.getName();
8572 if (tagName.equals("item")) {
8573 String name = parser.getAttributeValue(null, "name");
8574 if (name != null) {
8575 outPerms.add(name.intern());
8576 } else {
8577 reportSettingsProblem(Log.WARN,
8578 "Error in package manager settings: <perms> has"
8579 + " no name at " + parser.getPositionDescription());
8580 }
8581 } else {
8582 reportSettingsProblem(Log.WARN,
8583 "Unknown element under <perms>: "
8584 + parser.getName());
8585 }
8586 XmlUtils.skipCurrentTag(parser);
8587 }
8588 }
8589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 private void readPreferredActivitiesLP(XmlPullParser parser)
8591 throws XmlPullParserException, IOException {
8592 int outerDepth = parser.getDepth();
8593 int type;
8594 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8595 && (type != XmlPullParser.END_TAG
8596 || parser.getDepth() > outerDepth)) {
8597 if (type == XmlPullParser.END_TAG
8598 || type == XmlPullParser.TEXT) {
8599 continue;
8600 }
8601
8602 String tagName = parser.getName();
8603 if (tagName.equals("item")) {
8604 PreferredActivity pa = new PreferredActivity(parser);
8605 if (pa.mParseError == null) {
8606 mPreferredActivities.addFilter(pa);
8607 } else {
8608 reportSettingsProblem(Log.WARN,
8609 "Error in package manager settings: <preferred-activity> "
8610 + pa.mParseError + " at "
8611 + parser.getPositionDescription());
8612 }
8613 } else {
8614 reportSettingsProblem(Log.WARN,
8615 "Unknown element under <preferred-activities>: "
8616 + parser.getName());
8617 XmlUtils.skipCurrentTag(parser);
8618 }
8619 }
8620 }
8621
8622 // Returns -1 if we could not find an available UserId to assign
8623 private int newUserIdLP(Object obj) {
8624 // Let's be stupidly inefficient for now...
8625 final int N = mUserIds.size();
8626 for (int i=0; i<N; i++) {
8627 if (mUserIds.get(i) == null) {
8628 mUserIds.set(i, obj);
8629 return FIRST_APPLICATION_UID + i;
8630 }
8631 }
8632
8633 // None left?
8634 if (N >= MAX_APPLICATION_UIDS) {
8635 return -1;
8636 }
8637
8638 mUserIds.add(obj);
8639 return FIRST_APPLICATION_UID + N;
8640 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008642 public PackageSetting getDisabledSystemPkg(String name) {
8643 synchronized(mPackages) {
8644 PackageSetting ps = mDisabledSysPackages.get(name);
8645 return ps;
8646 }
8647 }
8648
8649 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8650 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8651 if (Config.LOGV) {
8652 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8653 + " componentName = " + componentInfo.name);
8654 Log.v(TAG, "enabledComponents: "
8655 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8656 Log.v(TAG, "disabledComponents: "
8657 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8658 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008659 if (packageSettings == null) {
8660 if (false) {
8661 Log.w(TAG, "WAITING FOR DEBUGGER");
8662 Debug.waitForDebugger();
8663 Log.i(TAG, "We will crash!");
8664 }
8665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008666 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8667 || ((componentInfo.enabled
8668 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8669 || (componentInfo.applicationInfo.enabled
8670 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8671 && !packageSettings.disabledComponents.contains(componentInfo.name))
8672 || packageSettings.enabledComponents.contains(componentInfo.name));
8673 }
8674 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008675
8676 // ------- apps on sdcard specific code -------
8677 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008678 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008679 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008680 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008681 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008682
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008683 private String getEncryptKey() {
8684 try {
8685 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8686 if (sdEncKey == null) {
8687 sdEncKey = SystemKeyStore.getInstance().
8688 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8689 if (sdEncKey == null) {
8690 Log.e(TAG, "Failed to create encryption keys");
8691 return null;
8692 }
8693 }
8694 return sdEncKey;
8695 } catch (NoSuchAlgorithmException nsae) {
8696 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8697 return null;
8698 }
8699 }
8700
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008701 static String getTempContainerId() {
8702 String prefix = "smdl1tmp";
8703 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008704 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008705 if (list != null) {
8706 int idx = 0;
8707 int idList[] = new int[MAX_CONTAINERS];
8708 boolean neverFound = true;
8709 for (String name : list) {
8710 // Ignore null entries
8711 if (name == null) {
8712 continue;
8713 }
8714 int sidx = name.indexOf(prefix);
8715 if (sidx == -1) {
8716 // Not a temp file. just ignore
8717 continue;
8718 }
8719 String subStr = name.substring(sidx + prefix.length());
8720 idList[idx] = -1;
8721 if (subStr != null) {
8722 try {
8723 int cid = Integer.parseInt(subStr);
8724 idList[idx++] = cid;
8725 neverFound = false;
8726 } catch (NumberFormatException e) {
8727 }
8728 }
8729 }
8730 if (!neverFound) {
8731 // Sort idList
8732 Arrays.sort(idList);
8733 for (int j = 1; j <= idList.length; j++) {
8734 if (idList[j-1] != j) {
8735 tmpIdx = j;
8736 break;
8737 }
8738 }
8739 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008740 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008741 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008742 }
8743
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008744 public void updateExternalMediaStatus(final boolean mediaStatus) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008745 synchronized (mPackages) {
8746 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8747 mediaStatus+", mMediaMounted=" + mMediaMounted);
8748 if (mediaStatus == mMediaMounted) {
8749 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008750 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008751 mMediaMounted = mediaStatus;
8752 // Queue up an async operation since the package installation may take a little while.
8753 mHandler.post(new Runnable() {
8754 public void run() {
8755 mHandler.removeCallbacks(this);
8756 updateExternalMediaStatusInner(mediaStatus);
8757 }
8758 });
8759 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008760 }
8761
8762 void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008763 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008764 if (list == null || list.length == 0) {
8765 return;
8766 }
8767 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8768 int uidList[] = new int[list.length];
8769 int num = 0;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008770 synchronized (mPackages) {
8771 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8772 for (String cid : list) {
8773 SdInstallArgs args = new SdInstallArgs(cid);
8774 String removeEntry = null;
8775 for (String app : appList) {
8776 if (args.matchContainer(app)) {
8777 removeEntry = app;
8778 break;
8779 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008780 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008781 if (removeEntry == null) {
8782 // No matching app on device. Skip entry or may be cleanup?
8783 // Ignore default package
8784 continue;
8785 }
8786 appList.remove(removeEntry);
8787 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8788 processCids.put(args, ps.codePathString);
8789 int uid = ps.userId;
8790 if (uid != -1) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008791 uidList[num++] = uid;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008792 }
8793 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008794 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008795 int uidArr[] = null;
8796 if (num > 0) {
8797 // Sort uid list
8798 Arrays.sort(uidList, 0, num);
8799 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008800 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008801 uidArr[0] = uidList[0];
8802 int di = 0;
8803 for (int i = 1; i < num; i++) {
8804 if (uidList[i-1] != uidList[i]) {
8805 uidArr[di++] = uidList[i];
8806 }
8807 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008808 }
8809 if (mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008810 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008811 loadMediaPackages(processCids, uidArr);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008812 startCleaningPackages();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008813 } else {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008814 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008815 unloadMediaPackages(processCids, uidArr);
8816 }
8817 }
8818
8819 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8820 ArrayList<String> pkgList, int uidArr[]) {
8821 int size = pkgList.size();
8822 if (size > 0) {
8823 // Send broadcasts here
8824 Bundle extras = new Bundle();
8825 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8826 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008827 if (uidArr != null) {
8828 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8829 }
8830 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8831 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008832 sendPackageBroadcast(action, null, extras);
8833 }
8834 }
8835
8836 void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8837 ArrayList<String> pkgList = new ArrayList<String>();
8838 Set<SdInstallArgs> keys = processCids.keySet();
8839 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008840 String codePath = processCids.get(args);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008841 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install pkg : "
8842 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008843 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008844 Log.e(TAG, "Failed to install package: " + codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008845 continue;
8846 }
8847 // Parse package
8848 int parseFlags = PackageParser.PARSE_CHATTY |
8849 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8850 PackageParser pp = new PackageParser(codePath);
8851 pp.setSeparateProcesses(mSeparateProcesses);
8852 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
8853 codePath, mMetrics, parseFlags);
8854 if (pkg == null) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008855 Log.e(TAG, "Trying to install pkg : "
8856 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008857 continue;
8858 }
8859 setApplicationInfoPaths(pkg, codePath, codePath);
8860 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8861 synchronized (mInstallLock) {
8862 // Scan the package
8863 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
8864 synchronized (mPackages) {
8865 // Grant permissions
8866 grantPermissionsLP(pkg, false);
8867 // Persist settings
8868 mSettings.writeLP();
8869 retCode = PackageManager.INSTALL_SUCCEEDED;
8870 pkgList.add(pkg.packageName);
8871 }
8872 } else {
8873 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
8874 }
8875 }
8876 args.doPostInstall(retCode);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008877 }
8878 // Send broadcasts first
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008879 if (pkgList.size() > 0) {
8880 sendResourcesChangedBroadcast(true, pkgList, uidArr);
8881 Runtime.getRuntime().gc();
8882 // If something failed do we clean up here or next install?
8883 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008884 }
8885
8886 void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008887 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008888 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008889 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008890 Set<SdInstallArgs> keys = processCids.keySet();
8891 for (SdInstallArgs args : keys) {
8892 String cid = args.cid;
8893 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008894 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008895 // Delete package internally
8896 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8897 synchronized (mInstallLock) {
8898 boolean res = deletePackageLI(pkgName, false,
8899 PackageManager.DONT_DELETE_DATA, outInfo);
8900 if (res) {
8901 pkgList.add(pkgName);
8902 } else {
8903 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008904 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008905 }
8906 }
8907 }
8908 // Send broadcasts
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008909 if (pkgList.size() > 0) {
8910 sendResourcesChangedBroadcast(false, pkgList, uidArr);
8911 Runtime.getRuntime().gc();
8912 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008913 // Do clean up. Just unmount
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008914 for (SdInstallArgs args : failedList) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008915 synchronized (mInstallLock) {
8916 args.doPostDeleteLI(false);
8917 }
8918 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008919 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08008920
8921 public void movePackage(final String packageName,
8922 final IPackageMoveObserver observer, final int flags) {
8923 if (packageName == null) {
8924 return;
8925 }
8926 mContext.enforceCallingOrSelfPermission(
8927 android.Manifest.permission.MOVE_PACKAGE, null);
8928 int returnCode = PackageManager.MOVE_SUCCEEDED;
8929 int currFlags = 0;
8930 int newFlags = 0;
8931 synchronized (mPackages) {
8932 PackageParser.Package pkg = mPackages.get(packageName);
8933 if (pkg == null) {
8934 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
8935 }
8936 // Disable moving fwd locked apps and system packages
8937 if (pkg.applicationInfo != null &&
8938 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8939 Log.w(TAG, "Cannot move system application");
8940 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
8941 } else if (pkg.applicationInfo != null &&
8942 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
8943 Log.w(TAG, "Cannot move forward locked app.");
8944 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
8945 } else {
8946 // Find install location first
8947 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
8948 (flags & PackageManager.MOVE_INTERNAL) != 0) {
8949 Log.w(TAG, "Ambigous flags specified for move location.");
8950 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
8951 } else {
8952 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
8953 PackageManager.INSTALL_EXTERNAL : 0;
8954 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0 ?
8955 PackageManager.INSTALL_EXTERNAL : 0;
8956 if (newFlags == currFlags) {
8957 Log.w(TAG, "No move required. Trying to move to same location");
8958 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
8959 }
8960 }
8961 }
8962 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
8963 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
8964 } else {
8965 Message msg = mHandler.obtainMessage(INIT_COPY);
8966 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
8967 pkg.applicationInfo.publicSourceDir);
8968 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
8969 packageName);
8970 msg.obj = mp;
8971 mHandler.sendMessage(msg);
8972 }
8973 }
8974 }
8975
8976 private void processPendingMove(final MoveParams mp, final int currentStatus) {
8977 // Queue up an async operation since the package deletion may take a little while.
8978 mHandler.post(new Runnable() {
8979 public void run() {
8980 mHandler.removeCallbacks(this);
8981 int returnCode = currentStatus;
8982 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
8983 if (moveSucceeded) {
8984 int uid = -1;
8985 synchronized (mPackages) {
8986 uid = mPackages.get(mp.packageName).applicationInfo.uid;
8987 }
8988 ArrayList<String> pkgList = new ArrayList<String>();
8989 pkgList.add(mp.packageName);
8990 int uidArr[] = new int[] { uid };
8991 // Send resources unavailable broadcast
8992 sendResourcesChangedBroadcast(false, pkgList, uidArr);
8993
8994 // Update package code and resource paths
8995 synchronized (mPackages) {
8996 PackageParser.Package pkg = mPackages.get(mp.packageName);
8997 if (pkg != null) {
8998 String oldCodePath = pkg.mPath;
8999 String newCodePath = mp.targetArgs.getCodePath();
9000 String newResPath = mp.targetArgs.getResourcePath();
9001 pkg.mPath = newCodePath;
9002 // Move dex files around
9003 if (moveDexFiles(pkg)
9004 != PackageManager.INSTALL_SUCCEEDED) {
9005 // Moving of dex files failed. Set
9006 // error code and abort move.
9007 pkg.mPath = pkg.mScanPath;
9008 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9009 moveSucceeded = false;
9010 } else {
9011 pkg.mScanPath = newCodePath;
9012 pkg.applicationInfo.sourceDir = newCodePath;
9013 pkg.applicationInfo.publicSourceDir = newResPath;
9014 PackageSetting ps = (PackageSetting) pkg.mExtras;
9015 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9016 ps.codePathString = ps.codePath.getPath();
9017 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9018 ps.resourcePathString = ps.resourcePath.getPath();
9019 // Set the application info flag correctly.
9020 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9021 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_ON_SDCARD;
9022 } else {
9023 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_ON_SDCARD;
9024 }
9025 ps.setFlags(pkg.applicationInfo.flags);
9026 mAppDirs.remove(oldCodePath);
9027 mAppDirs.put(newCodePath, pkg);
9028 // Persist settings
9029 mSettings.writeLP();
9030 }
9031 }
9032 }
9033 if (moveSucceeded) {
9034 // Delete older code
9035 synchronized (mInstallLock) {
9036 mp.srcArgs.cleanUpResourcesLI();
9037 }
9038 // Send resources available broadcast
9039 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9040 Runtime.getRuntime().gc();
9041 }
9042 }
9043 if (!moveSucceeded){
9044 // Clean up failed installation
9045 if (mp.targetArgs != null) {
9046 mp.targetArgs.doPostInstall(
9047 PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
9048 }
9049 }
9050 IPackageMoveObserver observer = mp.observer;
9051 if (observer != null) {
9052 try {
9053 observer.packageMoved(mp.packageName, returnCode);
9054 } catch (RemoteException e) {
9055 Log.i(TAG, "Observer no longer exists.");
9056 }
9057 }
9058 }
9059 });
9060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061}