blob: 812ff64465752992c8a7b5a52fa77e0a64da73c0 [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;
47import android.content.pm.IPackageStatsObserver;
48import android.content.pm.InstrumentationInfo;
49import android.content.pm.PackageInfo;
50import android.content.pm.PackageManager;
51import android.content.pm.PackageStats;
52import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
53import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
54import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
55import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
56import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
57import android.content.pm.PackageParser;
58import android.content.pm.PermissionInfo;
59import android.content.pm.PermissionGroupInfo;
60import android.content.pm.ProviderInfo;
61import android.content.pm.ResolveInfo;
62import android.content.pm.ServiceInfo;
63import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.Uri;
65import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070066import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080068import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080070import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070071import android.os.Looper;
72import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.Parcel;
74import android.os.RemoteException;
75import android.os.Environment;
76import android.os.FileObserver;
77import android.os.FileUtils;
78import android.os.Handler;
San Mehatb1043402010-02-05 08:26:50 -080079import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.ParcelFileDescriptor;
81import android.os.Process;
82import android.os.ServiceManager;
83import android.os.SystemClock;
84import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080085import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.util.*;
87import android.view.Display;
88import android.view.WindowManager;
89
90import java.io.File;
91import java.io.FileDescriptor;
92import java.io.FileInputStream;
93import java.io.FileNotFoundException;
94import java.io.FileOutputStream;
95import java.io.FileReader;
96import java.io.FilenameFilter;
97import java.io.IOException;
98import java.io.InputStream;
99import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800100import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800101import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import java.util.ArrayList;
103import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700104import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.Collections;
106import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800107import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.Enumeration;
109import java.util.HashMap;
110import java.util.HashSet;
111import java.util.Iterator;
112import java.util.List;
113import java.util.Map;
114import java.util.Set;
115import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800116import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import java.util.zip.ZipFile;
118import java.util.zip.ZipOutputStream;
119
120class PackageManagerService extends IPackageManager.Stub {
121 private static final String TAG = "PackageManager";
122 private static final boolean DEBUG_SETTINGS = false;
123 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800124 private static final boolean DEBUG_UPGRADE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
126 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
127 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400128 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 private static final int FIRST_APPLICATION_UID =
130 Process.FIRST_APPLICATION_UID;
131 private static final int MAX_APPLICATION_UIDS = 1000;
132
133 private static final boolean SHOW_INFO = false;
134
135 private static final boolean GET_CERTIFICATES = true;
136
Oscar Montemayora8529f62009-11-18 10:14:20 -0800137 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 private static final int REMOVE_EVENTS =
140 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
141 private static final int ADD_EVENTS =
142 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
143
144 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
145
146 static final int SCAN_MONITOR = 1<<0;
147 static final int SCAN_NO_DEX = 1<<1;
148 static final int SCAN_FORCE_DEX = 1<<2;
149 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800150 static final int SCAN_NEW_INSTALL = 1<<4;
151 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800153 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
154 "com.android.defcontainer",
155 "com.android.defcontainer.DefaultContainerService");
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
158 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700159 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
Dianne Hackborn851a5412009-05-08 12:06:44 -0700161 final int mSdkVersion = Build.VERSION.SDK_INT;
162 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
163 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 final Context mContext;
166 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700167 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 final DisplayMetrics mMetrics;
169 final int mDefParseFlags;
170 final String[] mSeparateProcesses;
171
172 // This is where all application persistent data goes.
173 final File mAppDataDir;
174
Oscar Montemayora8529f62009-11-18 10:14:20 -0800175 // If Encrypted File System feature is enabled, all application persistent data
176 // should go here instead.
177 final File mSecureAppDataDir;
178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 // This is the object monitoring the framework dir.
180 final FileObserver mFrameworkInstallObserver;
181
182 // This is the object monitoring the system app dir.
183 final FileObserver mSystemInstallObserver;
184
185 // This is the object monitoring mAppInstallDir.
186 final FileObserver mAppInstallObserver;
187
188 // This is the object monitoring mDrmAppPrivateInstallDir.
189 final FileObserver mDrmAppInstallObserver;
190
191 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
192 // LOCK HELD. Can be called with mInstallLock held.
193 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 final File mFrameworkDir;
196 final File mSystemAppDir;
197 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700198 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
200 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
201 // apps.
202 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 // Lock for state used when installing and doing other long running
207 // operations. Methods that must be called with this lock held have
208 // the prefix "LI".
209 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 // These are the directories in the 3rd party applications installed dir
212 // that we have currently loaded packages from. Keys are the application's
213 // installed zip file (absolute codePath), and values are Package.
214 final HashMap<String, PackageParser.Package> mAppDirs =
215 new HashMap<String, PackageParser.Package>();
216
217 // Information for the parser to write more useful error messages.
218 File mScanningPath;
219 int mLastScanError;
220
221 final int[] mOutPermissions = new int[3];
222
223 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 // Keys are String (package name), values are Package. This also serves
226 // as the lock for the global state. Methods that must be called with
227 // this lock held have the prefix "LP".
228 final HashMap<String, PackageParser.Package> mPackages =
229 new HashMap<String, PackageParser.Package>();
230
231 final Settings mSettings;
232 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233
234 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
235 int[] mGlobalGids;
236
237 // These are the built-in uid -> permission mappings that were read from the
238 // etc/permissions.xml file.
239 final SparseArray<HashSet<String>> mSystemPermissions =
240 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 // These are the built-in shared libraries that were read from the
243 // etc/permissions.xml file.
244 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800245
Dianne Hackborn49237342009-08-27 20:08:01 -0700246 // Temporary for building the final shared libraries for an .apk.
247 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800248
Dianne Hackborn49237342009-08-27 20:08:01 -0700249 // These are the features this devices supports that were read from the
250 // etc/permissions.xml file.
251 final HashMap<String, FeatureInfo> mAvailableFeatures =
252 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // All available activities, for your resolving pleasure.
255 final ActivityIntentResolver mActivities =
256 new ActivityIntentResolver();
257
258 // All available receivers, for your resolving pleasure.
259 final ActivityIntentResolver mReceivers =
260 new ActivityIntentResolver();
261
262 // All available services, for your resolving pleasure.
263 final ServiceIntentResolver mServices = new ServiceIntentResolver();
264
265 // Keys are String (provider class name), values are Provider.
266 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
267 new HashMap<ComponentName, PackageParser.Provider>();
268
269 // Mapping from provider base names (first directory in content URI codePath)
270 // to the provider information.
271 final HashMap<String, PackageParser.Provider> mProviders =
272 new HashMap<String, PackageParser.Provider>();
273
274 // Mapping from instrumentation class names to info about them.
275 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
276 new HashMap<ComponentName, PackageParser.Instrumentation>();
277
278 // Mapping from permission names to info about them.
279 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
280 new HashMap<String, PackageParser.PermissionGroup>();
281
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800282 // Packages whose data we have transfered into another package, thus
283 // should no longer exist.
284 final HashSet<String> mTransferedPackages = new HashSet<String>();
285
Dianne Hackborn854060af2009-07-09 18:14:31 -0700286 // Broadcast actions that are only available to the system.
287 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 boolean mSystemReady;
290 boolean mSafeMode;
291 boolean mHasSystemUidErrors;
292
293 ApplicationInfo mAndroidApplication;
294 final ActivityInfo mResolveActivity = new ActivityInfo();
295 final ResolveInfo mResolveInfo = new ResolveInfo();
296 ComponentName mResolveComponentName;
297 PackageParser.Package mPlatformPackage;
298
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700299 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800300 final HashMap<String, ArrayList<String>> mPendingBroadcasts
301 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700302 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800303 static final int MCS_BOUND = 3;
304 static final int END_COPY = 4;
305 static final int INIT_COPY = 5;
306 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800307 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800308 static final int FIND_INSTALL_LOC = 8;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700309 // Delay time in millisecs
310 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800311 private ServiceConnection mDefContainerConn = new ServiceConnection() {
312 public void onServiceConnected(ComponentName name, IBinder service) {
313 IMediaContainerService imcs =
314 IMediaContainerService.Stub.asInterface(service);
315 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
316 mHandler.sendMessage(msg);
317 }
318
319 public void onServiceDisconnected(ComponentName name) {
320 }
321 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700322
323 class PackageHandler extends Handler {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800324 final ArrayList<InstallParams> mPendingInstalls =
325 new ArrayList<InstallParams>();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800326 // Service Connection to remote media container service to copy
327 // package uri's from external media onto secure containers
328 // or internal storage.
329 private IMediaContainerService mContainerService = null;
330
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700331 PackageHandler(Looper looper) {
332 super(looper);
333 }
334 public void handleMessage(Message msg) {
335 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800336 case INIT_COPY: {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800337 InstallParams params = (InstallParams) msg.obj;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800338 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800339 if (mContainerService != null) {
340 // No need to add to pending list. Use remote stub directly
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800341 handleStartCopy(params);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800342 } else {
343 if (mContext.bindService(service, mDefContainerConn,
344 Context.BIND_AUTO_CREATE)) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800345 mPendingInstalls.add(params);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800346 } else {
347 Log.e(TAG, "Failed to bind to media container service");
348 // Indicate install failure TODO add new error code
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800349 processPendingInstall(createInstallArgs(params),
350 PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800351 }
352 }
353 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800354 }
355 case MCS_BOUND: {
356 // Initialize mContainerService if needed.
357 if (msg.obj != null) {
358 mContainerService = (IMediaContainerService) msg.obj;
359 }
360 if (mPendingInstalls.size() > 0) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800361 InstallParams params = mPendingInstalls.remove(0);
362 if (params != null) {
363 handleStartCopy(params);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800364 }
365 }
366 break;
367 }
368 case MCS_UNBIND : {
369 if (mPendingInstalls.size() == 0) {
370 mContext.unbindService(mDefContainerConn);
371 mContainerService = null;
372 }
373 break;
374 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700375 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800376 String packages[];
377 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700379 int uids[];
380 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800381 if (mPendingBroadcasts == null) {
382 return;
383 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700384 size = mPendingBroadcasts.size();
385 if (size <= 0) {
386 // Nothing to be done. Just return
387 return;
388 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800389 packages = new String[size];
390 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700391 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800392 Iterator<HashMap.Entry<String, ArrayList<String>>>
393 it = mPendingBroadcasts.entrySet().iterator();
394 int i = 0;
395 while (it.hasNext() && i < size) {
396 HashMap.Entry<String, ArrayList<String>> ent = it.next();
397 packages[i] = ent.getKey();
398 components[i] = ent.getValue();
399 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700400 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800401 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700402 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800403 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700404 mPendingBroadcasts.clear();
405 }
406 // Send broadcasts
407 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800408 sendPackageChangedBroadcast(packages[i], true,
409 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700410 }
411 break;
412 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800413 case START_CLEANING_PACKAGE: {
414 String packageName = (String)msg.obj;
415 synchronized (mPackages) {
416 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
417 mSettings.mPackagesToBeCleaned.add(packageName);
418 }
419 }
420 startCleaningPackages();
421 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700422 }
423 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800424
425 // Utility method to initiate copying apk via media
426 // container service.
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800427 private void handleStartCopy(InstallParams params) {
428 int ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
429 if (mContainerService != null) {
430 // Remote call to find out default install location
431 int loc = params.getInstallLocation(mContainerService);
432 // Use install location to create InstallArgs and temporary
433 // install location
434 if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
435 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
436 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
437 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
438 } else {
439 if ((params.flags & PackageManager.INSTALL_EXTERNAL) == 0){
440 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
441 // Set the flag to install on external media.
442 params.flags |= PackageManager.INSTALL_EXTERNAL;
443 } else {
444 // Make sure the flag for installing on external
445 // media is unset
446 params.flags &= ~PackageManager.INSTALL_EXTERNAL;
447 }
448 }
449 // Disable forward locked apps on sdcard.
450 if ((params.flags & PackageManager.INSTALL_FORWARD_LOCK) != 0 &&
451 (params.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
452 // Make sure forward locked apps can only be installed
453 // on internal storage
454 Log.w(TAG, "Cannot install protected apps on sdcard");
455 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
456 } else {
457 ret = PackageManager.INSTALL_SUCCEEDED;
458 }
459 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800460 }
461 mHandler.sendEmptyMessage(MCS_UNBIND);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800462 // Create the file args now.
463 InstallArgs args = createInstallArgs(params);
464 if (ret == PackageManager.INSTALL_SUCCEEDED) {
465 // Create copy only if we are not in an erroneous state.
466 args.createCopyFile();
467 // Remote call to initiate copy
468 ret = args.copyApk(mContainerService);
469 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800470 processPendingInstall(args, ret);
471 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700472 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800473
474 static boolean installOnSd(int flags) {
475 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800476 ((flags & PackageManager.INSTALL_EXTERNAL) == 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800477 return false;
478 }
479 return true;
480 }
481
482 static boolean isFwdLocked(int flags) {
483 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
484 return true;
485 }
486 return false;
487 }
488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 public static final IPackageManager main(Context context, boolean factoryTest) {
490 PackageManagerService m = new PackageManagerService(context, factoryTest);
491 ServiceManager.addService("package", m);
492 return m;
493 }
494
495 static String[] splitString(String str, char sep) {
496 int count = 1;
497 int i = 0;
498 while ((i=str.indexOf(sep, i)) >= 0) {
499 count++;
500 i++;
501 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 String[] res = new String[count];
504 i=0;
505 count = 0;
506 int lastI=0;
507 while ((i=str.indexOf(sep, i)) >= 0) {
508 res[count] = str.substring(lastI, i);
509 count++;
510 i++;
511 lastI = i;
512 }
513 res[count] = str.substring(lastI, str.length());
514 return res;
515 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800518 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 if (mSdkVersion <= 0) {
522 Log.w(TAG, "**** ro.build.version.sdk not set!");
523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 mContext = context;
526 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700527 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 mMetrics = new DisplayMetrics();
529 mSettings = new Settings();
530 mSettings.addSharedUserLP("android.uid.system",
531 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
532 mSettings.addSharedUserLP("android.uid.phone",
533 MULTIPLE_APPLICATION_UIDS
534 ? RADIO_UID : FIRST_APPLICATION_UID,
535 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400536 mSettings.addSharedUserLP("android.uid.log",
537 MULTIPLE_APPLICATION_UIDS
538 ? LOG_UID : FIRST_APPLICATION_UID,
539 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540
541 String separateProcesses = SystemProperties.get("debug.separate_processes");
542 if (separateProcesses != null && separateProcesses.length() > 0) {
543 if ("*".equals(separateProcesses)) {
544 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
545 mSeparateProcesses = null;
546 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
547 } else {
548 mDefParseFlags = 0;
549 mSeparateProcesses = separateProcesses.split(",");
550 Log.w(TAG, "Running with debug.separate_processes: "
551 + separateProcesses);
552 }
553 } else {
554 mDefParseFlags = 0;
555 mSeparateProcesses = null;
556 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 Installer installer = new Installer();
559 // Little hacky thing to check if installd is here, to determine
560 // whether we are running on the simulator and thus need to take
561 // care of building the /data file structure ourself.
562 // (apparently the sim now has a working installer)
563 if (installer.ping() && Process.supportsProcesses()) {
564 mInstaller = installer;
565 } else {
566 mInstaller = null;
567 }
568
569 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
570 Display d = wm.getDefaultDisplay();
571 d.getMetrics(mMetrics);
572
573 synchronized (mInstallLock) {
574 synchronized (mPackages) {
575 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700576 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 File dataDir = Environment.getDataDirectory();
579 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800580 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
582
583 if (mInstaller == null) {
584 // Make sure these dirs exist, when we are running in
585 // the simulator.
586 // Make a wide-open directory for random misc stuff.
587 File miscDir = new File(dataDir, "misc");
588 miscDir.mkdirs();
589 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800590 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 mDrmAppPrivateInstallDir.mkdirs();
592 }
593
594 readPermissions();
595
596 mRestoredSettings = mSettings.readLP();
597 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800598
599 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800601
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800602 // Set flag to monitor and not change apk file paths when
603 // scanning install directories.
604 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700605 if (mNoDexOpt) {
606 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800607 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700608 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700613 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700616 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 /**
619 * Out of paranoia, ensure that everything in the boot class
620 * path has been dexed.
621 */
622 String bootClassPath = System.getProperty("java.boot.class.path");
623 if (bootClassPath != null) {
624 String[] paths = splitString(bootClassPath, ':');
625 for (int i=0; i<paths.length; i++) {
626 try {
627 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
628 libFiles.add(paths[i]);
629 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700630 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 }
632 } catch (FileNotFoundException e) {
633 Log.w(TAG, "Boot class path not found: " + paths[i]);
634 } catch (IOException e) {
635 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
636 }
637 }
638 } else {
639 Log.w(TAG, "No BOOTCLASSPATH found!");
640 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 /**
643 * Also ensure all external libraries have had dexopt run on them.
644 */
645 if (mSharedLibraries.size() > 0) {
646 Iterator<String> libs = mSharedLibraries.values().iterator();
647 while (libs.hasNext()) {
648 String lib = libs.next();
649 try {
650 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
651 libFiles.add(lib);
652 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700653 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 }
655 } catch (FileNotFoundException e) {
656 Log.w(TAG, "Library not found: " + lib);
657 } catch (IOException e) {
658 Log.w(TAG, "Exception reading library: " + lib, e);
659 }
660 }
661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 // Gross hack for now: we know this file doesn't contain any
664 // code, so don't dexopt it to avoid the resulting log spew.
665 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 /**
668 * And there are a number of commands implemented in Java, which
669 * we currently need to do the dexopt on so that they can be
670 * run from a non-root shell.
671 */
672 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700673 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 for (int i=0; i<frameworkFiles.length; i++) {
675 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
676 String path = libPath.getPath();
677 // Skip the file if we alrady did it.
678 if (libFiles.contains(path)) {
679 continue;
680 }
681 // Skip the file if it is not a type we want to dexopt.
682 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
683 continue;
684 }
685 try {
686 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
687 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700688 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 }
690 } catch (FileNotFoundException e) {
691 Log.w(TAG, "Jar not found: " + path);
692 } catch (IOException e) {
693 Log.w(TAG, "Exception reading jar: " + path, e);
694 }
695 }
696 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800697
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700698 if (didDexOpt) {
699 // If we had to do a dexopt of one of the previous
700 // things, then something on the system has changed.
701 // Consider this significant, and wipe away all other
702 // existing dexopt files to ensure we don't leave any
703 // dangling around.
704 String[] files = mDalvikCacheDir.list();
705 if (files != null) {
706 for (int i=0; i<files.length; i++) {
707 String fn = files[i];
708 if (fn.startsWith("data@app@")
709 || fn.startsWith("data@app-private@")) {
710 Log.i(TAG, "Pruning dalvik file: " + fn);
711 (new File(mDalvikCacheDir, fn)).delete();
712 }
713 }
714 }
715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800717
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800718 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 mFrameworkInstallObserver = new AppDirObserver(
720 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
721 mFrameworkInstallObserver.startWatching();
722 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800723 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800724
725 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
727 mSystemInstallObserver = new AppDirObserver(
728 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
729 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800730 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800731
732 if (mInstaller != null) {
733 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
734 mInstaller.moveFiles();
735 }
736
737 // Prune any system packages that no longer exist.
738 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
739 while (psit.hasNext()) {
740 PackageSetting ps = psit.next();
741 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800742 && !mPackages.containsKey(ps.name)
743 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800744 psit.remove();
745 String msg = "System package " + ps.name
746 + " no longer exists; wiping its data";
747 reportSettingsProblem(Log.WARN, msg);
748 if (mInstaller != null) {
749 // XXX how to set useEncryptedFSDir for packages that
750 // are not encrypted?
751 mInstaller.remove(ps.name, true);
752 }
753 }
754 }
755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 mAppInstallDir = new File(dataDir, "app");
757 if (mInstaller == null) {
758 // Make sure these dirs exist, when we are running in
759 // the simulator.
760 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
761 }
762 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800763 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 //clean up list
765 for(int i = 0; i < deletePkgsList.size(); i++) {
766 //clean up here
767 cleanupInstallFailedPackage(deletePkgsList.get(i));
768 }
769 //delete tmp files
770 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800771
772 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 SystemClock.uptimeMillis());
774 mAppInstallObserver = new AppDirObserver(
775 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
776 mAppInstallObserver.startWatching();
777 scanDirLI(mAppInstallDir, 0, scanMode);
778
779 mDrmAppInstallObserver = new AppDirObserver(
780 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
781 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800782 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800784 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 SystemClock.uptimeMillis());
786 Log.i(TAG, "Time to scan packages: "
787 + ((SystemClock.uptimeMillis()-startTime)/1000f)
788 + " seconds");
789
790 updatePermissionsLP();
791
792 mSettings.writeLP();
793
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800794 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 // Now after opening every single application zip, make sure they
798 // are all flushed. Not really needed, but keeps things nice and
799 // tidy.
800 Runtime.getRuntime().gc();
801 } // synchronized (mPackages)
802 } // synchronized (mInstallLock)
803 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 @Override
806 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
807 throws RemoteException {
808 try {
809 return super.onTransact(code, data, reply, flags);
810 } catch (RuntimeException e) {
811 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
812 Log.e(TAG, "Package Manager Crash", e);
813 }
814 throw e;
815 }
816 }
817
Dianne Hackborne6620b22010-01-22 14:46:21 -0800818 void cleanupInstallFailedPackage(PackageSetting ps) {
819 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800821 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
822 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 if (retCode < 0) {
824 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800825 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
827 } else {
828 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800829 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 File dataDir = new File(pkg.applicationInfo.dataDir);
831 dataDir.delete();
832 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800833 if (ps.codePath != null) {
834 if (!ps.codePath.delete()) {
835 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
836 }
837 }
838 if (ps.resourcePath != null) {
839 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
840 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
841 }
842 }
843 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845
846 void readPermissions() {
847 // Read permissions from .../etc/permission directory.
848 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
849 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
850 Log.w(TAG, "No directory " + libraryDir + ", skipping");
851 return;
852 }
853 if (!libraryDir.canRead()) {
854 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
855 return;
856 }
857
858 // Iterate over the files in the directory and scan .xml files
859 for (File f : libraryDir.listFiles()) {
860 // We'll read platform.xml last
861 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
862 continue;
863 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 if (!f.getPath().endsWith(".xml")) {
866 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
867 continue;
868 }
869 if (!f.canRead()) {
870 Log.w(TAG, "Permissions library file " + f + " cannot be read");
871 continue;
872 }
873
874 readPermissionsFromXml(f);
875 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
878 final File permFile = new File(Environment.getRootDirectory(),
879 "etc/permissions/platform.xml");
880 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800881
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700882 StringBuilder sb = new StringBuilder(128);
883 sb.append("Libs:");
884 Iterator<String> it = mSharedLibraries.keySet().iterator();
885 while (it.hasNext()) {
886 sb.append(' ');
887 String name = it.next();
888 sb.append(name);
889 sb.append(':');
890 sb.append(mSharedLibraries.get(name));
891 }
892 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700894 sb.setLength(0);
895 sb.append("Features:");
896 it = mAvailableFeatures.keySet().iterator();
897 while (it.hasNext()) {
898 sb.append(' ');
899 sb.append(it.next());
900 }
901 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800903
904 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 FileReader permReader = null;
906 try {
907 permReader = new FileReader(permFile);
908 } catch (FileNotFoundException e) {
909 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
910 return;
911 }
912
913 try {
914 XmlPullParser parser = Xml.newPullParser();
915 parser.setInput(permReader);
916
917 XmlUtils.beginDocument(parser, "permissions");
918
919 while (true) {
920 XmlUtils.nextElement(parser);
921 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
922 break;
923 }
924
925 String name = parser.getName();
926 if ("group".equals(name)) {
927 String gidStr = parser.getAttributeValue(null, "gid");
928 if (gidStr != null) {
929 int gid = Integer.parseInt(gidStr);
930 mGlobalGids = appendInt(mGlobalGids, gid);
931 } else {
932 Log.w(TAG, "<group> without gid at "
933 + parser.getPositionDescription());
934 }
935
936 XmlUtils.skipCurrentTag(parser);
937 continue;
938 } else if ("permission".equals(name)) {
939 String perm = parser.getAttributeValue(null, "name");
940 if (perm == null) {
941 Log.w(TAG, "<permission> without name at "
942 + parser.getPositionDescription());
943 XmlUtils.skipCurrentTag(parser);
944 continue;
945 }
946 perm = perm.intern();
947 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 } else if ("assign-permission".equals(name)) {
950 String perm = parser.getAttributeValue(null, "name");
951 if (perm == null) {
952 Log.w(TAG, "<assign-permission> without name at "
953 + parser.getPositionDescription());
954 XmlUtils.skipCurrentTag(parser);
955 continue;
956 }
957 String uidStr = parser.getAttributeValue(null, "uid");
958 if (uidStr == null) {
959 Log.w(TAG, "<assign-permission> without uid at "
960 + parser.getPositionDescription());
961 XmlUtils.skipCurrentTag(parser);
962 continue;
963 }
964 int uid = Process.getUidForName(uidStr);
965 if (uid < 0) {
966 Log.w(TAG, "<assign-permission> with unknown uid \""
967 + uidStr + "\" at "
968 + parser.getPositionDescription());
969 XmlUtils.skipCurrentTag(parser);
970 continue;
971 }
972 perm = perm.intern();
973 HashSet<String> perms = mSystemPermissions.get(uid);
974 if (perms == null) {
975 perms = new HashSet<String>();
976 mSystemPermissions.put(uid, perms);
977 }
978 perms.add(perm);
979 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 } else if ("library".equals(name)) {
982 String lname = parser.getAttributeValue(null, "name");
983 String lfile = parser.getAttributeValue(null, "file");
984 if (lname == null) {
985 Log.w(TAG, "<library> without name at "
986 + parser.getPositionDescription());
987 } else if (lfile == null) {
988 Log.w(TAG, "<library> without file at "
989 + parser.getPositionDescription());
990 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700991 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700992 mSharedLibraries.put(lname, lfile);
993 }
994 XmlUtils.skipCurrentTag(parser);
995 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800996
Dianne Hackborn49237342009-08-27 20:08:01 -0700997 } else if ("feature".equals(name)) {
998 String fname = parser.getAttributeValue(null, "name");
999 if (fname == null) {
1000 Log.w(TAG, "<feature> without name at "
1001 + parser.getPositionDescription());
1002 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001003 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001004 FeatureInfo fi = new FeatureInfo();
1005 fi.name = fname;
1006 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008 XmlUtils.skipCurrentTag(parser);
1009 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 } else {
1012 XmlUtils.skipCurrentTag(parser);
1013 continue;
1014 }
1015
1016 }
1017 } catch (XmlPullParserException e) {
1018 Log.w(TAG, "Got execption parsing permissions.", e);
1019 } catch (IOException e) {
1020 Log.w(TAG, "Got execption parsing permissions.", e);
1021 }
1022 }
1023
1024 void readPermission(XmlPullParser parser, String name)
1025 throws IOException, XmlPullParserException {
1026
1027 name = name.intern();
1028
1029 BasePermission bp = mSettings.mPermissions.get(name);
1030 if (bp == null) {
1031 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1032 mSettings.mPermissions.put(name, bp);
1033 }
1034 int outerDepth = parser.getDepth();
1035 int type;
1036 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1037 && (type != XmlPullParser.END_TAG
1038 || parser.getDepth() > outerDepth)) {
1039 if (type == XmlPullParser.END_TAG
1040 || type == XmlPullParser.TEXT) {
1041 continue;
1042 }
1043
1044 String tagName = parser.getName();
1045 if ("group".equals(tagName)) {
1046 String gidStr = parser.getAttributeValue(null, "gid");
1047 if (gidStr != null) {
1048 int gid = Process.getGidForName(gidStr);
1049 bp.gids = appendInt(bp.gids, gid);
1050 } else {
1051 Log.w(TAG, "<group> without gid at "
1052 + parser.getPositionDescription());
1053 }
1054 }
1055 XmlUtils.skipCurrentTag(parser);
1056 }
1057 }
1058
1059 static int[] appendInt(int[] cur, int val) {
1060 if (cur == null) {
1061 return new int[] { val };
1062 }
1063 final int N = cur.length;
1064 for (int i=0; i<N; i++) {
1065 if (cur[i] == val) {
1066 return cur;
1067 }
1068 }
1069 int[] ret = new int[N+1];
1070 System.arraycopy(cur, 0, ret, 0, N);
1071 ret[N] = val;
1072 return ret;
1073 }
1074
1075 static int[] appendInts(int[] cur, int[] add) {
1076 if (add == null) return cur;
1077 if (cur == null) return add;
1078 final int N = add.length;
1079 for (int i=0; i<N; i++) {
1080 cur = appendInt(cur, add[i]);
1081 }
1082 return cur;
1083 }
1084
1085 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001086 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1087 // The package has been uninstalled but has retained data and resources.
1088 return PackageParser.generatePackageInfo(p, null, flags);
1089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 final PackageSetting ps = (PackageSetting)p.mExtras;
1091 if (ps == null) {
1092 return null;
1093 }
1094 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1095 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1096 }
1097
1098 public PackageInfo getPackageInfo(String packageName, int flags) {
1099 synchronized (mPackages) {
1100 PackageParser.Package p = mPackages.get(packageName);
1101 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001102 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 + ": " + p);
1104 if (p != null) {
1105 return generatePackageInfo(p, flags);
1106 }
1107 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1108 return generatePackageInfoFromSettingsLP(packageName, flags);
1109 }
1110 }
1111 return null;
1112 }
1113
Dianne Hackborn47096932010-02-11 15:57:09 -08001114 public String[] currentToCanonicalPackageNames(String[] names) {
1115 String[] out = new String[names.length];
1116 synchronized (mPackages) {
1117 for (int i=names.length-1; i>=0; i--) {
1118 PackageSetting ps = mSettings.mPackages.get(names[i]);
1119 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1120 }
1121 }
1122 return out;
1123 }
1124
1125 public String[] canonicalToCurrentPackageNames(String[] names) {
1126 String[] out = new String[names.length];
1127 synchronized (mPackages) {
1128 for (int i=names.length-1; i>=0; i--) {
1129 String cur = mSettings.mRenamedPackages.get(names[i]);
1130 out[i] = cur != null ? cur : names[i];
1131 }
1132 }
1133 return out;
1134 }
1135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 public int getPackageUid(String packageName) {
1137 synchronized (mPackages) {
1138 PackageParser.Package p = mPackages.get(packageName);
1139 if(p != null) {
1140 return p.applicationInfo.uid;
1141 }
1142 PackageSetting ps = mSettings.mPackages.get(packageName);
1143 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1144 return -1;
1145 }
1146 p = ps.pkg;
1147 return p != null ? p.applicationInfo.uid : -1;
1148 }
1149 }
1150
1151 public int[] getPackageGids(String packageName) {
1152 synchronized (mPackages) {
1153 PackageParser.Package p = mPackages.get(packageName);
1154 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001155 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 + ": " + p);
1157 if (p != null) {
1158 final PackageSetting ps = (PackageSetting)p.mExtras;
1159 final SharedUserSetting suid = ps.sharedUser;
1160 return suid != null ? suid.gids : ps.gids;
1161 }
1162 }
1163 // stupid thing to indicate an error.
1164 return new int[0];
1165 }
1166
1167 public PermissionInfo getPermissionInfo(String name, int flags) {
1168 synchronized (mPackages) {
1169 final BasePermission p = mSettings.mPermissions.get(name);
1170 if (p != null && p.perm != null) {
1171 return PackageParser.generatePermissionInfo(p.perm, flags);
1172 }
1173 return null;
1174 }
1175 }
1176
1177 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1178 synchronized (mPackages) {
1179 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1180 for (BasePermission p : mSettings.mPermissions.values()) {
1181 if (group == null) {
1182 if (p.perm.info.group == null) {
1183 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1184 }
1185 } else {
1186 if (group.equals(p.perm.info.group)) {
1187 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1188 }
1189 }
1190 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 if (out.size() > 0) {
1193 return out;
1194 }
1195 return mPermissionGroups.containsKey(group) ? out : null;
1196 }
1197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1200 synchronized (mPackages) {
1201 return PackageParser.generatePermissionGroupInfo(
1202 mPermissionGroups.get(name), flags);
1203 }
1204 }
1205
1206 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1207 synchronized (mPackages) {
1208 final int N = mPermissionGroups.size();
1209 ArrayList<PermissionGroupInfo> out
1210 = new ArrayList<PermissionGroupInfo>(N);
1211 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1212 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1213 }
1214 return out;
1215 }
1216 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1219 PackageSetting ps = mSettings.mPackages.get(packageName);
1220 if(ps != null) {
1221 if(ps.pkg == null) {
1222 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1223 if(pInfo != null) {
1224 return pInfo.applicationInfo;
1225 }
1226 return null;
1227 }
1228 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1229 }
1230 return null;
1231 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1234 PackageSetting ps = mSettings.mPackages.get(packageName);
1235 if(ps != null) {
1236 if(ps.pkg == null) {
1237 ps.pkg = new PackageParser.Package(packageName);
1238 ps.pkg.applicationInfo.packageName = packageName;
1239 }
1240 return generatePackageInfo(ps.pkg, flags);
1241 }
1242 return null;
1243 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1246 synchronized (mPackages) {
1247 PackageParser.Package p = mPackages.get(packageName);
1248 if (Config.LOGV) Log.v(
1249 TAG, "getApplicationInfo " + packageName
1250 + ": " + p);
1251 if (p != null) {
1252 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001253 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 }
1255 if ("android".equals(packageName)||"system".equals(packageName)) {
1256 return mAndroidApplication;
1257 }
1258 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1259 return generateApplicationInfoFromSettingsLP(packageName, flags);
1260 }
1261 }
1262 return null;
1263 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001264
1265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1267 mContext.enforceCallingOrSelfPermission(
1268 android.Manifest.permission.CLEAR_APP_CACHE, null);
1269 // Queue up an async operation since clearing cache may take a little while.
1270 mHandler.post(new Runnable() {
1271 public void run() {
1272 mHandler.removeCallbacks(this);
1273 int retCode = -1;
1274 if (mInstaller != null) {
1275 retCode = mInstaller.freeCache(freeStorageSize);
1276 if (retCode < 0) {
1277 Log.w(TAG, "Couldn't clear application caches");
1278 }
1279 } //end if mInstaller
1280 if (observer != null) {
1281 try {
1282 observer.onRemoveCompleted(null, (retCode >= 0));
1283 } catch (RemoteException e) {
1284 Log.w(TAG, "RemoveException when invoking call back");
1285 }
1286 }
1287 }
1288 });
1289 }
1290
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001291 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001292 mContext.enforceCallingOrSelfPermission(
1293 android.Manifest.permission.CLEAR_APP_CACHE, null);
1294 // Queue up an async operation since clearing cache may take a little while.
1295 mHandler.post(new Runnable() {
1296 public void run() {
1297 mHandler.removeCallbacks(this);
1298 int retCode = -1;
1299 if (mInstaller != null) {
1300 retCode = mInstaller.freeCache(freeStorageSize);
1301 if (retCode < 0) {
1302 Log.w(TAG, "Couldn't clear application caches");
1303 }
1304 }
1305 if(pi != null) {
1306 try {
1307 // Callback via pending intent
1308 int code = (retCode >= 0) ? 1 : 0;
1309 pi.sendIntent(null, code, null,
1310 null, null);
1311 } catch (SendIntentException e1) {
1312 Log.i(TAG, "Failed to send pending intent");
1313 }
1314 }
1315 }
1316 });
1317 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1320 synchronized (mPackages) {
1321 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001322
1323 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001325 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 }
1327 if (mResolveComponentName.equals(component)) {
1328 return mResolveActivity;
1329 }
1330 }
1331 return null;
1332 }
1333
1334 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1335 synchronized (mPackages) {
1336 PackageParser.Activity a = mReceivers.mActivities.get(component);
1337 if (Config.LOGV) Log.v(
1338 TAG, "getReceiverInfo " + component + ": " + a);
1339 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1340 return PackageParser.generateActivityInfo(a, flags);
1341 }
1342 }
1343 return null;
1344 }
1345
1346 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1347 synchronized (mPackages) {
1348 PackageParser.Service s = mServices.mServices.get(component);
1349 if (Config.LOGV) Log.v(
1350 TAG, "getServiceInfo " + component + ": " + s);
1351 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1352 return PackageParser.generateServiceInfo(s, flags);
1353 }
1354 }
1355 return null;
1356 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 public String[] getSystemSharedLibraryNames() {
1359 Set<String> libSet;
1360 synchronized (mPackages) {
1361 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001362 int size = libSet.size();
1363 if (size > 0) {
1364 String[] libs = new String[size];
1365 libSet.toArray(libs);
1366 return libs;
1367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001369 return null;
1370 }
1371
1372 public FeatureInfo[] getSystemAvailableFeatures() {
1373 Collection<FeatureInfo> featSet;
1374 synchronized (mPackages) {
1375 featSet = mAvailableFeatures.values();
1376 int size = featSet.size();
1377 if (size > 0) {
1378 FeatureInfo[] features = new FeatureInfo[size+1];
1379 featSet.toArray(features);
1380 FeatureInfo fi = new FeatureInfo();
1381 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1382 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1383 features[size] = fi;
1384 return features;
1385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 }
1387 return null;
1388 }
1389
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001390 public boolean hasSystemFeature(String name) {
1391 synchronized (mPackages) {
1392 return mAvailableFeatures.containsKey(name);
1393 }
1394 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 public int checkPermission(String permName, String pkgName) {
1397 synchronized (mPackages) {
1398 PackageParser.Package p = mPackages.get(pkgName);
1399 if (p != null && p.mExtras != null) {
1400 PackageSetting ps = (PackageSetting)p.mExtras;
1401 if (ps.sharedUser != null) {
1402 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1403 return PackageManager.PERMISSION_GRANTED;
1404 }
1405 } else if (ps.grantedPermissions.contains(permName)) {
1406 return PackageManager.PERMISSION_GRANTED;
1407 }
1408 }
1409 }
1410 return PackageManager.PERMISSION_DENIED;
1411 }
1412
1413 public int checkUidPermission(String permName, int uid) {
1414 synchronized (mPackages) {
1415 Object obj = mSettings.getUserIdLP(uid);
1416 if (obj != null) {
1417 if (obj instanceof SharedUserSetting) {
1418 SharedUserSetting sus = (SharedUserSetting)obj;
1419 if (sus.grantedPermissions.contains(permName)) {
1420 return PackageManager.PERMISSION_GRANTED;
1421 }
1422 } else if (obj instanceof PackageSetting) {
1423 PackageSetting ps = (PackageSetting)obj;
1424 if (ps.grantedPermissions.contains(permName)) {
1425 return PackageManager.PERMISSION_GRANTED;
1426 }
1427 }
1428 } else {
1429 HashSet<String> perms = mSystemPermissions.get(uid);
1430 if (perms != null && perms.contains(permName)) {
1431 return PackageManager.PERMISSION_GRANTED;
1432 }
1433 }
1434 }
1435 return PackageManager.PERMISSION_DENIED;
1436 }
1437
1438 private BasePermission findPermissionTreeLP(String permName) {
1439 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1440 if (permName.startsWith(bp.name) &&
1441 permName.length() > bp.name.length() &&
1442 permName.charAt(bp.name.length()) == '.') {
1443 return bp;
1444 }
1445 }
1446 return null;
1447 }
1448
1449 private BasePermission checkPermissionTreeLP(String permName) {
1450 if (permName != null) {
1451 BasePermission bp = findPermissionTreeLP(permName);
1452 if (bp != null) {
1453 if (bp.uid == Binder.getCallingUid()) {
1454 return bp;
1455 }
1456 throw new SecurityException("Calling uid "
1457 + Binder.getCallingUid()
1458 + " is not allowed to add to permission tree "
1459 + bp.name + " owned by uid " + bp.uid);
1460 }
1461 }
1462 throw new SecurityException("No permission tree found for " + permName);
1463 }
1464
1465 public boolean addPermission(PermissionInfo info) {
1466 synchronized (mPackages) {
1467 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1468 throw new SecurityException("Label must be specified in permission");
1469 }
1470 BasePermission tree = checkPermissionTreeLP(info.name);
1471 BasePermission bp = mSettings.mPermissions.get(info.name);
1472 boolean added = bp == null;
1473 if (added) {
1474 bp = new BasePermission(info.name, tree.sourcePackage,
1475 BasePermission.TYPE_DYNAMIC);
1476 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1477 throw new SecurityException(
1478 "Not allowed to modify non-dynamic permission "
1479 + info.name);
1480 }
1481 bp.perm = new PackageParser.Permission(tree.perm.owner,
1482 new PermissionInfo(info));
1483 bp.perm.info.packageName = tree.perm.info.packageName;
1484 bp.uid = tree.uid;
1485 if (added) {
1486 mSettings.mPermissions.put(info.name, bp);
1487 }
1488 mSettings.writeLP();
1489 return added;
1490 }
1491 }
1492
1493 public void removePermission(String name) {
1494 synchronized (mPackages) {
1495 checkPermissionTreeLP(name);
1496 BasePermission bp = mSettings.mPermissions.get(name);
1497 if (bp != null) {
1498 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1499 throw new SecurityException(
1500 "Not allowed to modify non-dynamic permission "
1501 + name);
1502 }
1503 mSettings.mPermissions.remove(name);
1504 mSettings.writeLP();
1505 }
1506 }
1507 }
1508
Dianne Hackborn854060af2009-07-09 18:14:31 -07001509 public boolean isProtectedBroadcast(String actionName) {
1510 synchronized (mPackages) {
1511 return mProtectedBroadcasts.contains(actionName);
1512 }
1513 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 public int checkSignatures(String pkg1, String pkg2) {
1516 synchronized (mPackages) {
1517 PackageParser.Package p1 = mPackages.get(pkg1);
1518 PackageParser.Package p2 = mPackages.get(pkg2);
1519 if (p1 == null || p1.mExtras == null
1520 || p2 == null || p2.mExtras == null) {
1521 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1522 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001523 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 }
1525 }
1526
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001527 public int checkUidSignatures(int uid1, int uid2) {
1528 synchronized (mPackages) {
1529 Signature[] s1;
1530 Signature[] s2;
1531 Object obj = mSettings.getUserIdLP(uid1);
1532 if (obj != null) {
1533 if (obj instanceof SharedUserSetting) {
1534 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1535 } else if (obj instanceof PackageSetting) {
1536 s1 = ((PackageSetting)obj).signatures.mSignatures;
1537 } else {
1538 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1539 }
1540 } else {
1541 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1542 }
1543 obj = mSettings.getUserIdLP(uid2);
1544 if (obj != null) {
1545 if (obj instanceof SharedUserSetting) {
1546 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1547 } else if (obj instanceof PackageSetting) {
1548 s2 = ((PackageSetting)obj).signatures.mSignatures;
1549 } else {
1550 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1551 }
1552 } else {
1553 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1554 }
1555 return checkSignaturesLP(s1, s2);
1556 }
1557 }
1558
1559 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1560 if (s1 == null) {
1561 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1563 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1564 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001565 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1567 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001568 final int N1 = s1.length;
1569 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 for (int i=0; i<N1; i++) {
1571 boolean match = false;
1572 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001573 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 match = true;
1575 break;
1576 }
1577 }
1578 if (!match) {
1579 return PackageManager.SIGNATURE_NO_MATCH;
1580 }
1581 }
1582 return PackageManager.SIGNATURE_MATCH;
1583 }
1584
1585 public String[] getPackagesForUid(int uid) {
1586 synchronized (mPackages) {
1587 Object obj = mSettings.getUserIdLP(uid);
1588 if (obj instanceof SharedUserSetting) {
1589 SharedUserSetting sus = (SharedUserSetting)obj;
1590 final int N = sus.packages.size();
1591 String[] res = new String[N];
1592 Iterator<PackageSetting> it = sus.packages.iterator();
1593 int i=0;
1594 while (it.hasNext()) {
1595 res[i++] = it.next().name;
1596 }
1597 return res;
1598 } else if (obj instanceof PackageSetting) {
1599 PackageSetting ps = (PackageSetting)obj;
1600 return new String[] { ps.name };
1601 }
1602 }
1603 return null;
1604 }
1605
1606 public String getNameForUid(int uid) {
1607 synchronized (mPackages) {
1608 Object obj = mSettings.getUserIdLP(uid);
1609 if (obj instanceof SharedUserSetting) {
1610 SharedUserSetting sus = (SharedUserSetting)obj;
1611 return sus.name + ":" + sus.userId;
1612 } else if (obj instanceof PackageSetting) {
1613 PackageSetting ps = (PackageSetting)obj;
1614 return ps.name;
1615 }
1616 }
1617 return null;
1618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 public int getUidForSharedUser(String sharedUserName) {
1621 if(sharedUserName == null) {
1622 return -1;
1623 }
1624 synchronized (mPackages) {
1625 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1626 if(suid == null) {
1627 return -1;
1628 }
1629 return suid.userId;
1630 }
1631 }
1632
1633 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1634 int flags) {
1635 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001636 return chooseBestActivity(intent, resolvedType, flags, query);
1637 }
1638
Mihai Predaeae850c2009-05-13 10:13:48 +02001639 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1640 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 if (query != null) {
1642 final int N = query.size();
1643 if (N == 1) {
1644 return query.get(0);
1645 } else if (N > 1) {
1646 // If there is more than one activity with the same priority,
1647 // then let the user decide between them.
1648 ResolveInfo r0 = query.get(0);
1649 ResolveInfo r1 = query.get(1);
1650 if (false) {
1651 System.out.println(r0.activityInfo.name +
1652 "=" + r0.priority + " vs " +
1653 r1.activityInfo.name +
1654 "=" + r1.priority);
1655 }
1656 // If the first activity has a higher priority, or a different
1657 // default, then it is always desireable to pick it.
1658 if (r0.priority != r1.priority
1659 || r0.preferredOrder != r1.preferredOrder
1660 || r0.isDefault != r1.isDefault) {
1661 return query.get(0);
1662 }
1663 // If we have saved a preference for a preferred activity for
1664 // this Intent, use that.
1665 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1666 flags, query, r0.priority);
1667 if (ri != null) {
1668 return ri;
1669 }
1670 return mResolveInfo;
1671 }
1672 }
1673 return null;
1674 }
1675
1676 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1677 int flags, List<ResolveInfo> query, int priority) {
1678 synchronized (mPackages) {
1679 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1680 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001681 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1683 if (prefs != null && prefs.size() > 0) {
1684 // First figure out how good the original match set is.
1685 // We will only allow preferred activities that came
1686 // from the same match quality.
1687 int match = 0;
1688 final int N = query.size();
1689 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1690 for (int j=0; j<N; j++) {
1691 ResolveInfo ri = query.get(j);
1692 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1693 + ": 0x" + Integer.toHexString(match));
1694 if (ri.match > match) match = ri.match;
1695 }
1696 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1697 + Integer.toHexString(match));
1698 match &= IntentFilter.MATCH_CATEGORY_MASK;
1699 final int M = prefs.size();
1700 for (int i=0; i<M; i++) {
1701 PreferredActivity pa = prefs.get(i);
1702 if (pa.mMatch != match) {
1703 continue;
1704 }
1705 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1706 if (DEBUG_PREFERRED) {
1707 Log.v(TAG, "Got preferred activity:");
1708 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1709 }
1710 if (ai != null) {
1711 for (int j=0; j<N; j++) {
1712 ResolveInfo ri = query.get(j);
1713 if (!ri.activityInfo.applicationInfo.packageName
1714 .equals(ai.applicationInfo.packageName)) {
1715 continue;
1716 }
1717 if (!ri.activityInfo.name.equals(ai.name)) {
1718 continue;
1719 }
1720
1721 // Okay we found a previously set preferred app.
1722 // If the result set is different from when this
1723 // was created, we need to clear it and re-ask the
1724 // user their preference.
1725 if (!pa.sameSet(query, priority)) {
1726 Log.i(TAG, "Result set changed, dropping preferred activity for "
1727 + intent + " type " + resolvedType);
1728 mSettings.mPreferredActivities.removeFilter(pa);
1729 return null;
1730 }
1731
1732 // Yay!
1733 return ri;
1734 }
1735 }
1736 }
1737 }
1738 }
1739 return null;
1740 }
1741
1742 public List<ResolveInfo> queryIntentActivities(Intent intent,
1743 String resolvedType, int flags) {
1744 ComponentName comp = intent.getComponent();
1745 if (comp != null) {
1746 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1747 ActivityInfo ai = getActivityInfo(comp, flags);
1748 if (ai != null) {
1749 ResolveInfo ri = new ResolveInfo();
1750 ri.activityInfo = ai;
1751 list.add(ri);
1752 }
1753 return list;
1754 }
1755
1756 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001757 String pkgName = intent.getPackage();
1758 if (pkgName == null) {
1759 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1760 resolvedType, flags);
1761 }
1762 PackageParser.Package pkg = mPackages.get(pkgName);
1763 if (pkg != null) {
1764 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1765 resolvedType, flags, pkg.activities);
1766 }
1767 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769 }
1770
1771 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1772 Intent[] specifics, String[] specificTypes, Intent intent,
1773 String resolvedType, int flags) {
1774 final String resultsAction = intent.getAction();
1775
1776 List<ResolveInfo> results = queryIntentActivities(
1777 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1778 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1779
1780 int specificsPos = 0;
1781 int N;
1782
1783 // todo: note that the algorithm used here is O(N^2). This
1784 // isn't a problem in our current environment, but if we start running
1785 // into situations where we have more than 5 or 10 matches then this
1786 // should probably be changed to something smarter...
1787
1788 // First we go through and resolve each of the specific items
1789 // that were supplied, taking care of removing any corresponding
1790 // duplicate items in the generic resolve list.
1791 if (specifics != null) {
1792 for (int i=0; i<specifics.length; i++) {
1793 final Intent sintent = specifics[i];
1794 if (sintent == null) {
1795 continue;
1796 }
1797
1798 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1799 String action = sintent.getAction();
1800 if (resultsAction != null && resultsAction.equals(action)) {
1801 // If this action was explicitly requested, then don't
1802 // remove things that have it.
1803 action = null;
1804 }
1805 ComponentName comp = sintent.getComponent();
1806 ResolveInfo ri = null;
1807 ActivityInfo ai = null;
1808 if (comp == null) {
1809 ri = resolveIntent(
1810 sintent,
1811 specificTypes != null ? specificTypes[i] : null,
1812 flags);
1813 if (ri == null) {
1814 continue;
1815 }
1816 if (ri == mResolveInfo) {
1817 // ACK! Must do something better with this.
1818 }
1819 ai = ri.activityInfo;
1820 comp = new ComponentName(ai.applicationInfo.packageName,
1821 ai.name);
1822 } else {
1823 ai = getActivityInfo(comp, flags);
1824 if (ai == null) {
1825 continue;
1826 }
1827 }
1828
1829 // Look for any generic query activities that are duplicates
1830 // of this specific one, and remove them from the results.
1831 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1832 N = results.size();
1833 int j;
1834 for (j=specificsPos; j<N; j++) {
1835 ResolveInfo sri = results.get(j);
1836 if ((sri.activityInfo.name.equals(comp.getClassName())
1837 && sri.activityInfo.applicationInfo.packageName.equals(
1838 comp.getPackageName()))
1839 || (action != null && sri.filter.matchAction(action))) {
1840 results.remove(j);
1841 if (Config.LOGV) Log.v(
1842 TAG, "Removing duplicate item from " + j
1843 + " due to specific " + specificsPos);
1844 if (ri == null) {
1845 ri = sri;
1846 }
1847 j--;
1848 N--;
1849 }
1850 }
1851
1852 // Add this specific item to its proper place.
1853 if (ri == null) {
1854 ri = new ResolveInfo();
1855 ri.activityInfo = ai;
1856 }
1857 results.add(specificsPos, ri);
1858 ri.specificIndex = i;
1859 specificsPos++;
1860 }
1861 }
1862
1863 // Now we go through the remaining generic results and remove any
1864 // duplicate actions that are found here.
1865 N = results.size();
1866 for (int i=specificsPos; i<N-1; i++) {
1867 final ResolveInfo rii = results.get(i);
1868 if (rii.filter == null) {
1869 continue;
1870 }
1871
1872 // Iterate over all of the actions of this result's intent
1873 // filter... typically this should be just one.
1874 final Iterator<String> it = rii.filter.actionsIterator();
1875 if (it == null) {
1876 continue;
1877 }
1878 while (it.hasNext()) {
1879 final String action = it.next();
1880 if (resultsAction != null && resultsAction.equals(action)) {
1881 // If this action was explicitly requested, then don't
1882 // remove things that have it.
1883 continue;
1884 }
1885 for (int j=i+1; j<N; j++) {
1886 final ResolveInfo rij = results.get(j);
1887 if (rij.filter != null && rij.filter.hasAction(action)) {
1888 results.remove(j);
1889 if (Config.LOGV) Log.v(
1890 TAG, "Removing duplicate item from " + j
1891 + " due to action " + action + " at " + i);
1892 j--;
1893 N--;
1894 }
1895 }
1896 }
1897
1898 // If the caller didn't request filter information, drop it now
1899 // so we don't have to marshall/unmarshall it.
1900 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1901 rii.filter = null;
1902 }
1903 }
1904
1905 // Filter out the caller activity if so requested.
1906 if (caller != null) {
1907 N = results.size();
1908 for (int i=0; i<N; i++) {
1909 ActivityInfo ainfo = results.get(i).activityInfo;
1910 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1911 && caller.getClassName().equals(ainfo.name)) {
1912 results.remove(i);
1913 break;
1914 }
1915 }
1916 }
1917
1918 // If the caller didn't request filter information,
1919 // drop them now so we don't have to
1920 // marshall/unmarshall it.
1921 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1922 N = results.size();
1923 for (int i=0; i<N; i++) {
1924 results.get(i).filter = null;
1925 }
1926 }
1927
1928 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1929 return results;
1930 }
1931
1932 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1933 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001934 ComponentName comp = intent.getComponent();
1935 if (comp != null) {
1936 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1937 ActivityInfo ai = getReceiverInfo(comp, flags);
1938 if (ai != null) {
1939 ResolveInfo ri = new ResolveInfo();
1940 ri.activityInfo = ai;
1941 list.add(ri);
1942 }
1943 return list;
1944 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001947 String pkgName = intent.getPackage();
1948 if (pkgName == null) {
1949 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1950 resolvedType, flags);
1951 }
1952 PackageParser.Package pkg = mPackages.get(pkgName);
1953 if (pkg != null) {
1954 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1955 resolvedType, flags, pkg.receivers);
1956 }
1957 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 }
1959 }
1960
1961 public ResolveInfo resolveService(Intent intent, String resolvedType,
1962 int flags) {
1963 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1964 flags);
1965 if (query != null) {
1966 if (query.size() >= 1) {
1967 // If there is more than one service with the same priority,
1968 // just arbitrarily pick the first one.
1969 return query.get(0);
1970 }
1971 }
1972 return null;
1973 }
1974
1975 public List<ResolveInfo> queryIntentServices(Intent intent,
1976 String resolvedType, int flags) {
1977 ComponentName comp = intent.getComponent();
1978 if (comp != null) {
1979 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1980 ServiceInfo si = getServiceInfo(comp, flags);
1981 if (si != null) {
1982 ResolveInfo ri = new ResolveInfo();
1983 ri.serviceInfo = si;
1984 list.add(ri);
1985 }
1986 return list;
1987 }
1988
1989 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001990 String pkgName = intent.getPackage();
1991 if (pkgName == null) {
1992 return (List<ResolveInfo>)mServices.queryIntent(intent,
1993 resolvedType, flags);
1994 }
1995 PackageParser.Package pkg = mPackages.get(pkgName);
1996 if (pkg != null) {
1997 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1998 resolvedType, flags, pkg.services);
1999 }
2000 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 }
2002 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 public List<PackageInfo> getInstalledPackages(int flags) {
2005 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2006
2007 synchronized (mPackages) {
2008 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2009 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2010 while (i.hasNext()) {
2011 final PackageSetting ps = i.next();
2012 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2013 if(psPkg != null) {
2014 finalList.add(psPkg);
2015 }
2016 }
2017 }
2018 else {
2019 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2020 while (i.hasNext()) {
2021 final PackageParser.Package p = i.next();
2022 if (p.applicationInfo != null) {
2023 PackageInfo pi = generatePackageInfo(p, flags);
2024 if(pi != null) {
2025 finalList.add(pi);
2026 }
2027 }
2028 }
2029 }
2030 }
2031 return finalList;
2032 }
2033
2034 public List<ApplicationInfo> getInstalledApplications(int flags) {
2035 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2036 synchronized(mPackages) {
2037 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2038 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2039 while (i.hasNext()) {
2040 final PackageSetting ps = i.next();
2041 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2042 if(ai != null) {
2043 finalList.add(ai);
2044 }
2045 }
2046 }
2047 else {
2048 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2049 while (i.hasNext()) {
2050 final PackageParser.Package p = i.next();
2051 if (p.applicationInfo != null) {
2052 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2053 if(ai != null) {
2054 finalList.add(ai);
2055 }
2056 }
2057 }
2058 }
2059 }
2060 return finalList;
2061 }
2062
2063 public List<ApplicationInfo> getPersistentApplications(int flags) {
2064 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2065
2066 synchronized (mPackages) {
2067 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2068 while (i.hasNext()) {
2069 PackageParser.Package p = i.next();
2070 if (p.applicationInfo != null
2071 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2072 && (!mSafeMode || (p.applicationInfo.flags
2073 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2074 finalList.add(p.applicationInfo);
2075 }
2076 }
2077 }
2078
2079 return finalList;
2080 }
2081
2082 public ProviderInfo resolveContentProvider(String name, int flags) {
2083 synchronized (mPackages) {
2084 final PackageParser.Provider provider = mProviders.get(name);
2085 return provider != null
2086 && mSettings.isEnabledLP(provider.info, flags)
2087 && (!mSafeMode || (provider.info.applicationInfo.flags
2088 &ApplicationInfo.FLAG_SYSTEM) != 0)
2089 ? PackageParser.generateProviderInfo(provider, flags)
2090 : null;
2091 }
2092 }
2093
Fred Quintana718d8a22009-04-29 17:53:20 -07002094 /**
2095 * @deprecated
2096 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 public void querySyncProviders(List outNames, List outInfo) {
2098 synchronized (mPackages) {
2099 Iterator<Map.Entry<String, PackageParser.Provider>> i
2100 = mProviders.entrySet().iterator();
2101
2102 while (i.hasNext()) {
2103 Map.Entry<String, PackageParser.Provider> entry = i.next();
2104 PackageParser.Provider p = entry.getValue();
2105
2106 if (p.syncable
2107 && (!mSafeMode || (p.info.applicationInfo.flags
2108 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2109 outNames.add(entry.getKey());
2110 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2111 }
2112 }
2113 }
2114 }
2115
2116 public List<ProviderInfo> queryContentProviders(String processName,
2117 int uid, int flags) {
2118 ArrayList<ProviderInfo> finalList = null;
2119
2120 synchronized (mPackages) {
2121 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2122 while (i.hasNext()) {
2123 PackageParser.Provider p = i.next();
2124 if (p.info.authority != null
2125 && (processName == null ||
2126 (p.info.processName.equals(processName)
2127 && p.info.applicationInfo.uid == uid))
2128 && mSettings.isEnabledLP(p.info, flags)
2129 && (!mSafeMode || (p.info.applicationInfo.flags
2130 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2131 if (finalList == null) {
2132 finalList = new ArrayList<ProviderInfo>(3);
2133 }
2134 finalList.add(PackageParser.generateProviderInfo(p,
2135 flags));
2136 }
2137 }
2138 }
2139
2140 if (finalList != null) {
2141 Collections.sort(finalList, mProviderInitOrderSorter);
2142 }
2143
2144 return finalList;
2145 }
2146
2147 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2148 int flags) {
2149 synchronized (mPackages) {
2150 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2151 return PackageParser.generateInstrumentationInfo(i, flags);
2152 }
2153 }
2154
2155 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2156 int flags) {
2157 ArrayList<InstrumentationInfo> finalList =
2158 new ArrayList<InstrumentationInfo>();
2159
2160 synchronized (mPackages) {
2161 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2162 while (i.hasNext()) {
2163 PackageParser.Instrumentation p = i.next();
2164 if (targetPackage == null
2165 || targetPackage.equals(p.info.targetPackage)) {
2166 finalList.add(PackageParser.generateInstrumentationInfo(p,
2167 flags));
2168 }
2169 }
2170 }
2171
2172 return finalList;
2173 }
2174
2175 private void scanDirLI(File dir, int flags, int scanMode) {
2176 Log.d(TAG, "Scanning app dir " + dir);
2177
2178 String[] files = dir.list();
2179
2180 int i;
2181 for (i=0; i<files.length; i++) {
2182 File file = new File(dir, files[i]);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002183 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002185 // Don't mess around with apps in system partition.
2186 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0) {
2187 // Delete the apk
2188 Log.w(TAG, "Cleaning up failed install of " + file);
2189 file.delete();
2190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 }
2192 }
2193
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002194 private static File getSettingsProblemFile() {
2195 File dataDir = Environment.getDataDirectory();
2196 File systemDir = new File(dataDir, "system");
2197 File fname = new File(systemDir, "uiderrors.txt");
2198 return fname;
2199 }
2200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 private static void reportSettingsProblem(int priority, String msg) {
2202 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002203 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 FileOutputStream out = new FileOutputStream(fname, true);
2205 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002206 SimpleDateFormat formatter = new SimpleDateFormat();
2207 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2208 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 pw.close();
2210 FileUtils.setPermissions(
2211 fname.toString(),
2212 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2213 -1, -1);
2214 } catch (java.io.IOException e) {
2215 }
2216 Log.println(priority, TAG, msg);
2217 }
2218
2219 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2220 PackageParser.Package pkg, File srcFile, int parseFlags) {
2221 if (GET_CERTIFICATES) {
2222 if (ps == null || !ps.codePath.equals(srcFile)
2223 || ps.getTimeStamp() != srcFile.lastModified()) {
2224 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2225 if (!pp.collectCertificates(pkg, parseFlags)) {
2226 mLastScanError = pp.getParseError();
2227 return false;
2228 }
2229 }
2230 }
2231 return true;
2232 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 /*
2235 * Scan a package and return the newly parsed package.
2236 * Returns null in case of errors and the error code is stored in mLastScanError
2237 */
2238 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002239 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002241 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002243 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002246 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 if (pkg == null) {
2248 mLastScanError = pp.getParseError();
2249 return null;
2250 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002251 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 PackageSetting updatedPkg;
2253 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002254 // Look to see if we already know about this package.
2255 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
2256 if (oldName != null && oldName.equals(pkg.mOriginalPackage)) {
2257 // This package has been renamed to its original name. Let's
2258 // use that.
2259 ps = mSettings.peekPackageLP(pkg.mOriginalPackage);
2260 }
2261 // If there was no original package, see one for the real package name.
2262 if (ps == null) {
2263 ps = mSettings.peekPackageLP(pkg.packageName);
2264 }
2265 // Check to see if this package could be hiding/updating a system
2266 // package. Must look for it either under the original or real
2267 // package name depending on our state.
2268 updatedPkg = mSettings.mDisabledSysPackages.get(
2269 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002271 // First check if this is a system package that may involve an update
2272 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2273 if (!ps.codePath.equals(scanFile)) {
2274 // The path has changed from what was last scanned... check the
2275 // version of the new path against what we have stored to determine
2276 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002277 if (pkg.mVersionCode < ps.versionCode) {
2278 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002279 // Ignore entry. Skip it.
2280 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2281 + "ignored: updated version " + ps.versionCode
2282 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002283 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2284 return null;
2285 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002286 // The current app on the system partion is better than
2287 // what we have updated to on the data partition; switch
2288 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002289 // At this point, its safely assumed that package installation for
2290 // apps in system partition will go through. If not there won't be a working
2291 // version of the app
2292 synchronized (mPackages) {
2293 // Just remove the loaded entries from package lists.
2294 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002295 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002296 Log.w(TAG, "Package " + ps.name + " at " + scanFile
2297 + "reverting from " + ps.codePathString
2298 + ": new version " + pkg.mVersionCode
2299 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002300 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2301 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002302 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 }
2305 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002306 if (updatedPkg != null) {
2307 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2308 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2309 }
2310 // Verify certificates against what was last scanned
2311 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2312 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2313 return null;
2314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 // The apk is forward locked (not public) if its code and resources
2316 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002317 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002319 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002320 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002321
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002322 String codePath = null;
2323 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002324 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2325 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002326 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002327 } else {
2328 // Should not happen at all. Just log an error.
2329 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2330 }
2331 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002332 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002333 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002334 codePath = pkg.mScanPath;
2335 // Set application objects path explicitly.
2336 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002338 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 }
2340
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002341 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2342 String destCodePath, String destResPath) {
2343 pkg.mPath = pkg.mScanPath = destCodePath;
2344 pkg.applicationInfo.sourceDir = destCodePath;
2345 pkg.applicationInfo.publicSourceDir = destResPath;
2346 }
2347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 private static String fixProcessName(String defProcessName,
2349 String processName, int uid) {
2350 if (processName == null) {
2351 return defProcessName;
2352 }
2353 return processName;
2354 }
2355
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002356 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2358 if (pkg.mSignatures != null) {
2359 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2360 updateSignature)) {
2361 Log.e(TAG, "Package " + pkg.packageName
2362 + " signatures do not match the previously installed version; ignoring!");
2363 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2364 return false;
2365 }
2366
2367 if (pkgSetting.sharedUser != null) {
2368 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2369 pkg.mSignatures, updateSignature)) {
2370 Log.e(TAG, "Package " + pkg.packageName
2371 + " has no signatures that match those in shared user "
2372 + pkgSetting.sharedUser.name + "; ignoring!");
2373 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2374 return false;
2375 }
2376 }
2377 } else {
2378 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2379 }
2380 return true;
2381 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002382
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002383 public boolean performDexOpt(String packageName) {
2384 if (!mNoDexOpt) {
2385 return false;
2386 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002387
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002388 PackageParser.Package p;
2389 synchronized (mPackages) {
2390 p = mPackages.get(packageName);
2391 if (p == null || p.mDidDexOpt) {
2392 return false;
2393 }
2394 }
2395 synchronized (mInstallLock) {
2396 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2397 }
2398 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002399
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002400 static final int DEX_OPT_SKIPPED = 0;
2401 static final int DEX_OPT_PERFORMED = 1;
2402 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002403
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002404 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2405 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002406 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002407 String path = pkg.mScanPath;
2408 int ret = 0;
2409 try {
2410 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002411 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002412 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002413 pkg.mDidDexOpt = true;
2414 performed = true;
2415 }
2416 } catch (FileNotFoundException e) {
2417 Log.w(TAG, "Apk not found for dexopt: " + path);
2418 ret = -1;
2419 } catch (IOException e) {
2420 Log.w(TAG, "Exception reading apk: " + path, e);
2421 ret = -1;
2422 }
2423 if (ret < 0) {
2424 //error from installer
2425 return DEX_OPT_FAILED;
2426 }
2427 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002428
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002429 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2430 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002431
2432 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2433 return Environment.isEncryptedFilesystemEnabled() &&
2434 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2435 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002436
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002437 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2438 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2439 Log.w(TAG, "Unable to update from " + oldPkg.name
2440 + " to " + newPkg.packageName
2441 + ": old package not in system partition");
2442 return false;
2443 } else if (mPackages.get(oldPkg.name) != null) {
2444 Log.w(TAG, "Unable to update from " + oldPkg.name
2445 + " to " + newPkg.packageName
2446 + ": old package still exists");
2447 return false;
2448 }
2449 return true;
2450 }
2451
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002452 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2453 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002454 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002455 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2456 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002457 // Bail out. The resource and code paths haven't been set.
2458 Log.w(TAG, " Code and resource paths haven't been set correctly");
2459 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2460 return null;
2461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462 mScanningPath = scanFile;
2463 if (pkg == null) {
2464 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2465 return null;
2466 }
2467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2469 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2470 }
2471
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002472 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 synchronized (mPackages) {
2474 if (mAndroidApplication != null) {
2475 Log.w(TAG, "*************************************************");
2476 Log.w(TAG, "Core android package being redefined. Skipping.");
2477 Log.w(TAG, " file=" + mScanningPath);
2478 Log.w(TAG, "*************************************************");
2479 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2480 return null;
2481 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 // Set up information for our fall-back user intent resolution
2484 // activity.
2485 mPlatformPackage = pkg;
2486 pkg.mVersionCode = mSdkVersion;
2487 mAndroidApplication = pkg.applicationInfo;
2488 mResolveActivity.applicationInfo = mAndroidApplication;
2489 mResolveActivity.name = ResolverActivity.class.getName();
2490 mResolveActivity.packageName = mAndroidApplication.packageName;
2491 mResolveActivity.processName = mAndroidApplication.processName;
2492 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2493 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2494 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2495 mResolveActivity.exported = true;
2496 mResolveActivity.enabled = true;
2497 mResolveInfo.activityInfo = mResolveActivity;
2498 mResolveInfo.priority = 0;
2499 mResolveInfo.preferredOrder = 0;
2500 mResolveInfo.match = 0;
2501 mResolveComponentName = new ComponentName(
2502 mAndroidApplication.packageName, mResolveActivity.name);
2503 }
2504 }
2505
2506 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002507 TAG, "Scanning package " + pkg.packageName);
2508 if (mPackages.containsKey(pkg.packageName)
2509 || mSharedLibraries.containsKey(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 Log.w(TAG, "*************************************************");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002511 Log.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 + " already installed. Skipping duplicate.");
2513 Log.w(TAG, "*************************************************");
2514 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2515 return null;
2516 }
2517
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002518 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002519 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2520 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 SharedUserSetting suid = null;
2523 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002526
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002527 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2528 // Only system apps can use these features.
2529 pkg.mOriginalPackage = null;
2530 pkg.mRealPackage = null;
2531 pkg.mAdoptPermissions = null;
2532 }
2533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 synchronized (mPackages) {
2535 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002536 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2537 if (mTmpSharedLibraries == null ||
2538 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2539 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2540 }
2541 int num = 0;
2542 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2543 for (int i=0; i<N; i++) {
2544 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 if (file == null) {
2546 Log.e(TAG, "Package " + pkg.packageName
2547 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002548 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2550 return null;
2551 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002552 mTmpSharedLibraries[num] = file;
2553 num++;
2554 }
2555 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2556 for (int i=0; i<N; i++) {
2557 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2558 if (file == null) {
2559 Log.w(TAG, "Package " + pkg.packageName
2560 + " desires unavailable shared library "
2561 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2562 } else {
2563 mTmpSharedLibraries[num] = file;
2564 num++;
2565 }
2566 }
2567 if (num > 0) {
2568 pkg.usesLibraryFiles = new String[num];
2569 System.arraycopy(mTmpSharedLibraries, 0,
2570 pkg.usesLibraryFiles, 0, num);
2571 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002572
Dianne Hackborn49237342009-08-27 20:08:01 -07002573 if (pkg.reqFeatures != null) {
2574 N = pkg.reqFeatures.size();
2575 for (int i=0; i<N; i++) {
2576 FeatureInfo fi = pkg.reqFeatures.get(i);
2577 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2578 // Don't care.
2579 continue;
2580 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002581
Dianne Hackborn49237342009-08-27 20:08:01 -07002582 if (fi.name != null) {
2583 if (mAvailableFeatures.get(fi.name) == null) {
2584 Log.e(TAG, "Package " + pkg.packageName
2585 + " requires unavailable feature "
2586 + fi.name + "; failing!");
2587 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2588 return null;
2589 }
2590 }
2591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 }
2593 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 if (pkg.mSharedUserId != null) {
2596 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2597 pkg.applicationInfo.flags, true);
2598 if (suid == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002599 Log.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 + " for shared user failed");
2601 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2602 return null;
2603 }
2604 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2605 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2606 + suid.userId + "): packages=" + suid.packages);
2607 }
2608 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002609
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002610 if (false) {
2611 if (pkg.mOriginalPackage != null) {
2612 Log.w(TAG, "WAITING FOR DEBUGGER");
2613 Debug.waitForDebugger();
2614 Log.i(TAG, "Package " + pkg.packageName + " from original package"
2615 + pkg.mOriginalPackage);
2616 }
2617 }
2618
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002619 // Check if we are renaming from an original package name.
2620 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002621 String realName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002622 if (pkg.mOriginalPackage != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002623 // This package may need to be renamed to a previously
2624 // installed name. Let's check on that...
2625 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
2626 if (pkg.mOriginalPackage.equals(renamed)) {
2627 // This package had originally been installed as the
2628 // original name, and we have already taken care of
2629 // transitioning to the new one. Just update the new
2630 // one to continue using the old name.
2631 realName = pkg.mRealPackage;
2632 if (!pkg.packageName.equals(renamed)) {
2633 // Callers into this function may have already taken
2634 // care of renaming the package; only do it here if
2635 // it is not already done.
2636 pkg.setPackageName(renamed);
2637 }
2638
2639 } else if ((origPackage
2640 = mSettings.peekPackageLP(pkg.mOriginalPackage)) != null) {
2641 // We do have the package already installed under its
2642 // original name... should we use it?
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002643 if (!verifyPackageUpdate(origPackage, pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002644 // New package is not compatible with original.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002645 origPackage = null;
2646 } else if (origPackage.sharedUser != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002647 // Make sure uid is compatible between packages.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002648 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2649 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2650 + " to " + pkg.packageName + ": old uid "
2651 + origPackage.sharedUser.name
2652 + " differs from " + pkg.mSharedUserId);
2653 origPackage = null;
2654 }
2655 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002656 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2657 + pkg.packageName + " to old name " + origPackage.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002658 }
2659 }
2660 }
2661
2662 if (mTransferedPackages.contains(pkg.packageName)) {
2663 Log.w(TAG, "Package " + pkg.packageName
2664 + " was transferred to another, but its .apk remains");
2665 }
2666
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002667 // Just create the setting, don't add it yet. For already existing packages
2668 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002669 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 destResourceFile, pkg.applicationInfo.flags, true, false);
2671 if (pkgSetting == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002672 Log.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2674 return null;
2675 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002676
2677 if (pkgSetting.origPackage != null) {
2678 // If we are first transitioning from an original package,
2679 // fix up the new package's name now. We need to do this after
2680 // looking up the package under its new name, so getPackageLP
2681 // can take care of fiddling things correctly.
2682 pkg.setPackageName(origPackage.name);
2683
2684 // File a report about this.
2685 String msg = "New package " + pkgSetting.realName
2686 + " renamed to replace old package " + pkgSetting.name;
2687 reportSettingsProblem(Log.WARN, msg);
2688
2689 // Make a note of it.
2690 mTransferedPackages.add(origPackage.name);
2691
2692 // No longer need to retain this.
2693 pkgSetting.origPackage = null;
2694 }
2695
2696 if (realName != null) {
2697 // Make a note of it.
2698 mTransferedPackages.add(pkg.packageName);
2699 }
2700
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002701 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2703 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 pkg.applicationInfo.uid = pkgSetting.userId;
2706 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002707
2708 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2710 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2711 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2712 return null;
2713 }
2714 // The signature has changed, but this package is in the system
2715 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002716 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 // However... if this package is part of a shared user, but it
2718 // doesn't match the signature of the shared user, let's fail.
2719 // What this means is that you can't change the signatures
2720 // associated with an overall shared user, which doesn't seem all
2721 // that unreasonable.
2722 if (pkgSetting.sharedUser != null) {
2723 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2724 pkg.mSignatures, false)) {
2725 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2726 return null;
2727 }
2728 }
2729 removeExisting = true;
2730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002731
The Android Open Source Project10592532009-03-18 17:39:46 -07002732 // Verify that this new package doesn't have any content providers
2733 // that conflict with existing packages. Only do this if the
2734 // package isn't already installed, since we don't want to break
2735 // things that are installed.
2736 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2737 int N = pkg.providers.size();
2738 int i;
2739 for (i=0; i<N; i++) {
2740 PackageParser.Provider p = pkg.providers.get(i);
2741 String names[] = p.info.authority.split(";");
2742 for (int j = 0; j < names.length; j++) {
2743 if (mProviders.containsKey(names[j])) {
2744 PackageParser.Provider other = mProviders.get(names[j]);
2745 Log.w(TAG, "Can't install because provider name " + names[j] +
2746 " (in package " + pkg.applicationInfo.packageName +
2747 ") is already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002748 + ((other != null && other.getComponentName() != null)
2749 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project10592532009-03-18 17:39:46 -07002750 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2751 return null;
2752 }
2753 }
2754 }
2755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 }
2757
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002758 final String pkgName = pkg.packageName;
2759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002761 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002763 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 if (ret != 0) {
2765 String msg = "System package " + pkg.packageName
2766 + " could not have data directory erased after signature change.";
2767 reportSettingsProblem(Log.WARN, msg);
2768 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2769 return null;
2770 }
2771 }
2772 Log.w(TAG, "System package " + pkg.packageName
2773 + " signature changed: existing data removed.");
2774 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2775 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002776
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002777 if (pkg.mAdoptPermissions != null) {
2778 // This package wants to adopt ownership of permissions from
2779 // another package.
2780 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2781 String origName = pkg.mAdoptPermissions.get(i);
2782 PackageSetting orig = mSettings.peekPackageLP(origName);
2783 if (orig != null) {
2784 if (verifyPackageUpdate(orig, pkg)) {
2785 Log.i(TAG, "Adopting permissions from "
2786 + origName + " to " + pkg.packageName);
2787 mSettings.transferPermissions(origName, pkg.packageName);
2788 }
2789 }
2790 }
2791 }
2792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 long scanFileTime = scanFile.lastModified();
2794 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2795 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2796 pkg.applicationInfo.processName = fixProcessName(
2797 pkg.applicationInfo.packageName,
2798 pkg.applicationInfo.processName,
2799 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800
2801 File dataPath;
2802 if (mPlatformPackage == pkg) {
2803 // The system package is special.
2804 dataPath = new File (Environment.getDataDirectory(), "system");
2805 pkg.applicationInfo.dataDir = dataPath.getPath();
2806 } else {
2807 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002808 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2809 if (useEncryptedFSDir) {
2810 dataPath = new File(mSecureAppDataDir, pkgName);
2811 } else {
2812 dataPath = new File(mAppDataDir, pkgName);
2813 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002814
2815 boolean uidError = false;
2816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 if (dataPath.exists()) {
2818 mOutPermissions[1] = 0;
2819 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2820 if (mOutPermissions[1] == pkg.applicationInfo.uid
2821 || !Process.supportsProcesses()) {
2822 pkg.applicationInfo.dataDir = dataPath.getPath();
2823 } else {
2824 boolean recovered = false;
2825 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2826 // If this is a system app, we can at least delete its
2827 // current data so the application will still work.
2828 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002829 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002830 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 // Old data gone!
2832 String msg = "System package " + pkg.packageName
2833 + " has changed from uid: "
2834 + mOutPermissions[1] + " to "
2835 + pkg.applicationInfo.uid + "; old data erased";
2836 reportSettingsProblem(Log.WARN, msg);
2837 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002840 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 == -1) {
2843 // Ack should not happen!
2844 msg = "System package " + pkg.packageName
2845 + " could not have data directory re-created after delete.";
2846 reportSettingsProblem(Log.WARN, msg);
2847 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2848 return null;
2849 }
2850 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 if (!recovered) {
2853 mHasSystemUidErrors = true;
2854 }
2855 }
2856 if (!recovered) {
2857 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2858 + pkg.applicationInfo.uid + "/fs_"
2859 + mOutPermissions[1];
2860 String msg = "Package " + pkg.packageName
2861 + " has mismatched uid: "
2862 + mOutPermissions[1] + " on disk, "
2863 + pkg.applicationInfo.uid + " in settings";
2864 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002865 mSettings.mReadMessages.append(msg);
2866 mSettings.mReadMessages.append('\n');
2867 uidError = true;
2868 if (!pkgSetting.uidError) {
2869 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 }
2872 }
2873 }
2874 pkg.applicationInfo.dataDir = dataPath.getPath();
2875 } else {
2876 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2877 Log.v(TAG, "Want this data dir: " + dataPath);
2878 //invoke installer to do the actual installation
2879 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002880 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 pkg.applicationInfo.uid);
2882 if(ret < 0) {
2883 // Error from installer
2884 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2885 return null;
2886 }
2887 } else {
2888 dataPath.mkdirs();
2889 if (dataPath.exists()) {
2890 FileUtils.setPermissions(
2891 dataPath.toString(),
2892 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2893 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2894 }
2895 }
2896 if (dataPath.exists()) {
2897 pkg.applicationInfo.dataDir = dataPath.getPath();
2898 } else {
2899 Log.w(TAG, "Unable to create data directory: " + dataPath);
2900 pkg.applicationInfo.dataDir = null;
2901 }
2902 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002903
2904 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 }
2906
2907 // Perform shared library installation and dex validation and
2908 // optimization, if this is not a system app.
2909 if (mInstaller != null) {
2910 String path = scanFile.getPath();
2911 if (scanFileNewer) {
2912 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002913 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2914 if (err != PackageManager.INSTALL_SUCCEEDED) {
2915 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 return null;
2917 }
2918 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002919 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002920
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002921 if ((scanMode&SCAN_NO_DEX) == 0) {
2922 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2924 return null;
2925 }
2926 }
2927 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 if (mFactoryTest && pkg.requestedPermissions.contains(
2930 android.Manifest.permission.FACTORY_TEST)) {
2931 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2932 }
2933
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002934 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 if ((scanMode&SCAN_MONITOR) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 mAppDirs.put(pkg.mPath, pkg);
2937 }
2938
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002939 // Request the ActivityManager to kill the process(only for existing packages)
2940 // so that we do not end up in a confused state while the user is still using the older
2941 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002942 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002943 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002944 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002945 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002949 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002951 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08002952 // Make sure we don't accidentally delete its data.
2953 mSettings.mPackagesToBeCleaned.remove(pkgName);
2954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 int N = pkg.providers.size();
2956 StringBuilder r = null;
2957 int i;
2958 for (i=0; i<N; i++) {
2959 PackageParser.Provider p = pkg.providers.get(i);
2960 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2961 p.info.processName, pkg.applicationInfo.uid);
2962 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2963 p.info.name), p);
2964 p.syncable = p.info.isSyncable;
2965 String names[] = p.info.authority.split(";");
2966 p.info.authority = null;
2967 for (int j = 0; j < names.length; j++) {
2968 if (j == 1 && p.syncable) {
2969 // We only want the first authority for a provider to possibly be
2970 // syncable, so if we already added this provider using a different
2971 // authority clear the syncable flag. We copy the provider before
2972 // changing it because the mProviders object contains a reference
2973 // to a provider that we don't want to change.
2974 // Only do this for the second authority since the resulting provider
2975 // object can be the same for all future authorities for this provider.
2976 p = new PackageParser.Provider(p);
2977 p.syncable = false;
2978 }
2979 if (!mProviders.containsKey(names[j])) {
2980 mProviders.put(names[j], p);
2981 if (p.info.authority == null) {
2982 p.info.authority = names[j];
2983 } else {
2984 p.info.authority = p.info.authority + ";" + names[j];
2985 }
2986 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2987 Log.d(TAG, "Registered content provider: " + names[j] +
2988 ", className = " + p.info.name +
2989 ", isSyncable = " + p.info.isSyncable);
2990 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002991 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 Log.w(TAG, "Skipping provider name " + names[j] +
2993 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002994 "): name already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002995 + ((other != null && other.getComponentName() != null)
2996 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 }
2998 }
2999 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3000 if (r == null) {
3001 r = new StringBuilder(256);
3002 } else {
3003 r.append(' ');
3004 }
3005 r.append(p.info.name);
3006 }
3007 }
3008 if (r != null) {
3009 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 N = pkg.services.size();
3013 r = null;
3014 for (i=0; i<N; i++) {
3015 PackageParser.Service s = pkg.services.get(i);
3016 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3017 s.info.processName, pkg.applicationInfo.uid);
3018 mServices.addService(s);
3019 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3020 if (r == null) {
3021 r = new StringBuilder(256);
3022 } else {
3023 r.append(' ');
3024 }
3025 r.append(s.info.name);
3026 }
3027 }
3028 if (r != null) {
3029 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 N = pkg.receivers.size();
3033 r = null;
3034 for (i=0; i<N; i++) {
3035 PackageParser.Activity a = pkg.receivers.get(i);
3036 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3037 a.info.processName, pkg.applicationInfo.uid);
3038 mReceivers.addActivity(a, "receiver");
3039 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3040 if (r == null) {
3041 r = new StringBuilder(256);
3042 } else {
3043 r.append(' ');
3044 }
3045 r.append(a.info.name);
3046 }
3047 }
3048 if (r != null) {
3049 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3050 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 N = pkg.activities.size();
3053 r = null;
3054 for (i=0; i<N; i++) {
3055 PackageParser.Activity a = pkg.activities.get(i);
3056 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3057 a.info.processName, pkg.applicationInfo.uid);
3058 mActivities.addActivity(a, "activity");
3059 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3060 if (r == null) {
3061 r = new StringBuilder(256);
3062 } else {
3063 r.append(' ');
3064 }
3065 r.append(a.info.name);
3066 }
3067 }
3068 if (r != null) {
3069 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3070 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003072 N = pkg.permissionGroups.size();
3073 r = null;
3074 for (i=0; i<N; i++) {
3075 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3076 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3077 if (cur == null) {
3078 mPermissionGroups.put(pg.info.name, pg);
3079 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3080 if (r == null) {
3081 r = new StringBuilder(256);
3082 } else {
3083 r.append(' ');
3084 }
3085 r.append(pg.info.name);
3086 }
3087 } else {
3088 Log.w(TAG, "Permission group " + pg.info.name + " from package "
3089 + pg.info.packageName + " ignored: original from "
3090 + cur.info.packageName);
3091 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3092 if (r == null) {
3093 r = new StringBuilder(256);
3094 } else {
3095 r.append(' ');
3096 }
3097 r.append("DUP:");
3098 r.append(pg.info.name);
3099 }
3100 }
3101 }
3102 if (r != null) {
3103 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3104 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 N = pkg.permissions.size();
3107 r = null;
3108 for (i=0; i<N; i++) {
3109 PackageParser.Permission p = pkg.permissions.get(i);
3110 HashMap<String, BasePermission> permissionMap =
3111 p.tree ? mSettings.mPermissionTrees
3112 : mSettings.mPermissions;
3113 p.group = mPermissionGroups.get(p.info.group);
3114 if (p.info.group == null || p.group != null) {
3115 BasePermission bp = permissionMap.get(p.info.name);
3116 if (bp == null) {
3117 bp = new BasePermission(p.info.name, p.info.packageName,
3118 BasePermission.TYPE_NORMAL);
3119 permissionMap.put(p.info.name, bp);
3120 }
3121 if (bp.perm == null) {
3122 if (bp.sourcePackage == null
3123 || bp.sourcePackage.equals(p.info.packageName)) {
3124 BasePermission tree = findPermissionTreeLP(p.info.name);
3125 if (tree == null
3126 || tree.sourcePackage.equals(p.info.packageName)) {
3127 bp.perm = p;
3128 bp.uid = pkg.applicationInfo.uid;
3129 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3130 if (r == null) {
3131 r = new StringBuilder(256);
3132 } else {
3133 r.append(' ');
3134 }
3135 r.append(p.info.name);
3136 }
3137 } else {
3138 Log.w(TAG, "Permission " + p.info.name + " from package "
3139 + p.info.packageName + " ignored: base tree "
3140 + tree.name + " is from package "
3141 + tree.sourcePackage);
3142 }
3143 } else {
3144 Log.w(TAG, "Permission " + p.info.name + " from package "
3145 + p.info.packageName + " ignored: original from "
3146 + bp.sourcePackage);
3147 }
3148 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3149 if (r == null) {
3150 r = new StringBuilder(256);
3151 } else {
3152 r.append(' ');
3153 }
3154 r.append("DUP:");
3155 r.append(p.info.name);
3156 }
3157 } else {
3158 Log.w(TAG, "Permission " + p.info.name + " from package "
3159 + p.info.packageName + " ignored: no group "
3160 + p.group);
3161 }
3162 }
3163 if (r != null) {
3164 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3165 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 N = pkg.instrumentation.size();
3168 r = null;
3169 for (i=0; i<N; i++) {
3170 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3171 a.info.packageName = pkg.applicationInfo.packageName;
3172 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3173 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3174 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003175 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3177 if (r == null) {
3178 r = new StringBuilder(256);
3179 } else {
3180 r.append(' ');
3181 }
3182 r.append(a.info.name);
3183 }
3184 }
3185 if (r != null) {
3186 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3187 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003188
Dianne Hackborn854060af2009-07-09 18:14:31 -07003189 if (pkg.protectedBroadcasts != null) {
3190 N = pkg.protectedBroadcasts.size();
3191 for (i=0; i<N; i++) {
3192 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3193 }
3194 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 pkgSetting.setTimeStamp(scanFileTime);
3197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 return pkg;
3200 }
3201
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003202 private void killApplication(String pkgName, int uid) {
3203 // Request the ActivityManager to kill the process(only for existing packages)
3204 // so that we do not end up in a confused state while the user is still using the older
3205 // version of the application while the new one gets installed.
3206 IActivityManager am = ActivityManagerNative.getDefault();
3207 if (am != null) {
3208 try {
3209 am.killApplicationWithUid(pkgName, uid);
3210 } catch (RemoteException e) {
3211 }
3212 }
3213 }
3214
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003215 // The following constants are returned by cachePackageSharedLibsForAbiLI
3216 // to indicate if native shared libraries were found in the package.
3217 // Values are:
3218 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3219 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3220 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3221 // in package (and not installed)
3222 //
3223 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3224 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3225 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003227 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3228 // and automatically copy them to /data/data/<appname>/lib if present.
3229 //
3230 // NOTE: this method may throw an IOException if the library cannot
3231 // be copied to its final destination, e.g. if there isn't enough
3232 // room left on the data partition, or a ZipException if the package
3233 // file is malformed.
3234 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003235 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3236 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003237 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3238 final String apkLib = "lib/";
3239 final int apkLibLen = apkLib.length();
3240 final int cpuAbiLen = cpuAbi.length();
3241 final String libPrefix = "lib";
3242 final int libPrefixLen = libPrefix.length();
3243 final String libSuffix = ".so";
3244 final int libSuffixLen = libSuffix.length();
3245 boolean hasNativeLibraries = false;
3246 boolean installedNativeLibraries = false;
3247
3248 // the minimum length of a valid native shared library of the form
3249 // lib/<something>/lib<name>.so.
3250 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3251
3252 ZipFile zipFile = new ZipFile(scanFile);
3253 Enumeration<ZipEntry> entries =
3254 (Enumeration<ZipEntry>) zipFile.entries();
3255
3256 while (entries.hasMoreElements()) {
3257 ZipEntry entry = entries.nextElement();
3258 // skip directories
3259 if (entry.isDirectory()) {
3260 continue;
3261 }
3262 String entryName = entry.getName();
3263
3264 // check that the entry looks like lib/<something>/lib<name>.so
3265 // here, but don't check the ABI just yet.
3266 //
3267 // - must be sufficiently long
3268 // - must end with libSuffix, i.e. ".so"
3269 // - must start with apkLib, i.e. "lib/"
3270 if (entryName.length() < minEntryLen ||
3271 !entryName.endsWith(libSuffix) ||
3272 !entryName.startsWith(apkLib) ) {
3273 continue;
3274 }
3275
3276 // file name must start with libPrefix, i.e. "lib"
3277 int lastSlash = entryName.lastIndexOf('/');
3278
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003279 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003280 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3281 continue;
3282 }
3283
3284 hasNativeLibraries = true;
3285
3286 // check the cpuAbi now, between lib/ and /lib<name>.so
3287 //
3288 if (lastSlash != apkLibLen + cpuAbiLen ||
3289 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3290 continue;
3291
3292 // extract the library file name, ensure it doesn't contain
3293 // weird characters. we're guaranteed here that it doesn't contain
3294 // a directory separator though.
3295 String libFileName = entryName.substring(lastSlash+1);
3296 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3297 continue;
3298 }
3299
3300 installedNativeLibraries = true;
3301
3302 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3303 File.separator + libFileName;
3304 File sharedLibraryFile = new File(sharedLibraryFilePath);
3305 if (! sharedLibraryFile.exists() ||
3306 sharedLibraryFile.length() != entry.getSize() ||
3307 sharedLibraryFile.lastModified() != entry.getTime()) {
3308 if (Config.LOGD) {
3309 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003311 if (mInstaller == null) {
3312 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003313 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003314 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003315 sharedLibraryFile);
3316 }
3317 }
3318 if (!hasNativeLibraries)
3319 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3320
3321 if (!installedNativeLibraries)
3322 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3323
3324 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3325 }
3326
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003327 // Find the gdbserver executable program in a package at
3328 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3329 //
3330 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3331 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3332 //
3333 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3334 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3335 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3336 final String GDBSERVER = "gdbserver";
3337 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3338
3339 ZipFile zipFile = new ZipFile(scanFile);
3340 Enumeration<ZipEntry> entries =
3341 (Enumeration<ZipEntry>) zipFile.entries();
3342
3343 while (entries.hasMoreElements()) {
3344 ZipEntry entry = entries.nextElement();
3345 // skip directories
3346 if (entry.isDirectory()) {
3347 continue;
3348 }
3349 String entryName = entry.getName();
3350
3351 if (!entryName.equals(apkGdbServerPath)) {
3352 continue;
3353 }
3354
3355 String installGdbServerPath = installGdbServerDir.getPath() +
3356 "/" + GDBSERVER;
3357 File installGdbServerFile = new File(installGdbServerPath);
3358 if (! installGdbServerFile.exists() ||
3359 installGdbServerFile.length() != entry.getSize() ||
3360 installGdbServerFile.lastModified() != entry.getTime()) {
3361 if (Config.LOGD) {
3362 Log.d(TAG, "Caching gdbserver " + entry.getName());
3363 }
3364 if (mInstaller == null) {
3365 installGdbServerDir.mkdir();
3366 }
3367 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3368 installGdbServerFile);
3369 }
3370 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3371 }
3372 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3373 }
3374
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003375 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3376 // and copy them to /data/data/<appname>/lib.
3377 //
3378 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3379 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3380 // one if ro.product.cpu.abi2 is defined.
3381 //
3382 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3383 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003384 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003385 try {
3386 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3387
3388 // some architectures are capable of supporting several CPU ABIs
3389 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3390 // this is indicated by the definition of the ro.product.cpu.abi2
3391 // system property.
3392 //
3393 // only scan the package twice in case of ABI mismatch
3394 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003395 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003396 if (cpuAbi2 != null) {
3397 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003399
3400 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3401 Log.w(TAG,"Native ABI mismatch from package file");
3402 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003404
3405 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3406 cpuAbi = cpuAbi2;
3407 }
3408 }
3409
3410 // for debuggable packages, also extract gdbserver from lib/<abi>
3411 // into /data/data/<appname>/lib too.
3412 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3413 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3414 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3415 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3416 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003419 } catch (ZipException e) {
3420 Log.w(TAG, "Failed to extract data from package file", e);
3421 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003423 Log.w(TAG, "Failed to cache package shared libs", e);
3424 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003426 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 }
3428
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003429 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003431 File binaryDir,
3432 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 InputStream inputStream = zipFile.getInputStream(entry);
3434 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003435 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003437 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 // now need to be left as world readable and owned by the system.
3439 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3440 ! tempFile.setLastModified(entry.getTime()) ||
3441 FileUtils.setPermissions(tempFilePath,
3442 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003443 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003445 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 // Failed to properly write file.
3447 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003448 throw new IOException("Couldn't create cached binary "
3449 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 }
3451 } finally {
3452 inputStream.close();
3453 }
3454 }
3455
3456 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3457 if (chatty && Config.LOGD) Log.d(
3458 TAG, "Removing package " + pkg.applicationInfo.packageName );
3459
3460 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 mPackages.remove(pkg.applicationInfo.packageName);
3464 if (pkg.mPath != null) {
3465 mAppDirs.remove(pkg.mPath);
3466 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 PackageSetting ps = (PackageSetting)pkg.mExtras;
3469 if (ps != null && ps.sharedUser != null) {
3470 // XXX don't do this until the data is removed.
3471 if (false) {
3472 ps.sharedUser.packages.remove(ps);
3473 if (ps.sharedUser.packages.size() == 0) {
3474 // Remove.
3475 }
3476 }
3477 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 int N = pkg.providers.size();
3480 StringBuilder r = null;
3481 int i;
3482 for (i=0; i<N; i++) {
3483 PackageParser.Provider p = pkg.providers.get(i);
3484 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3485 p.info.name));
3486 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 /* The is another ContentProvider with this authority when
3489 * this app was installed so this authority is null,
3490 * Ignore it as we don't have to unregister the provider.
3491 */
3492 continue;
3493 }
3494 String names[] = p.info.authority.split(";");
3495 for (int j = 0; j < names.length; j++) {
3496 if (mProviders.get(names[j]) == p) {
3497 mProviders.remove(names[j]);
3498 if (chatty && Config.LOGD) Log.d(
3499 TAG, "Unregistered content provider: " + names[j] +
3500 ", className = " + p.info.name +
3501 ", isSyncable = " + p.info.isSyncable);
3502 }
3503 }
3504 if (chatty) {
3505 if (r == null) {
3506 r = new StringBuilder(256);
3507 } else {
3508 r.append(' ');
3509 }
3510 r.append(p.info.name);
3511 }
3512 }
3513 if (r != null) {
3514 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3515 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 N = pkg.services.size();
3518 r = null;
3519 for (i=0; i<N; i++) {
3520 PackageParser.Service s = pkg.services.get(i);
3521 mServices.removeService(s);
3522 if (chatty) {
3523 if (r == null) {
3524 r = new StringBuilder(256);
3525 } else {
3526 r.append(' ');
3527 }
3528 r.append(s.info.name);
3529 }
3530 }
3531 if (r != null) {
3532 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3533 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 N = pkg.receivers.size();
3536 r = null;
3537 for (i=0; i<N; i++) {
3538 PackageParser.Activity a = pkg.receivers.get(i);
3539 mReceivers.removeActivity(a, "receiver");
3540 if (chatty) {
3541 if (r == null) {
3542 r = new StringBuilder(256);
3543 } else {
3544 r.append(' ');
3545 }
3546 r.append(a.info.name);
3547 }
3548 }
3549 if (r != null) {
3550 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3551 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003553 N = pkg.activities.size();
3554 r = null;
3555 for (i=0; i<N; i++) {
3556 PackageParser.Activity a = pkg.activities.get(i);
3557 mActivities.removeActivity(a, "activity");
3558 if (chatty) {
3559 if (r == null) {
3560 r = new StringBuilder(256);
3561 } else {
3562 r.append(' ');
3563 }
3564 r.append(a.info.name);
3565 }
3566 }
3567 if (r != null) {
3568 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 N = pkg.permissions.size();
3572 r = null;
3573 for (i=0; i<N; i++) {
3574 PackageParser.Permission p = pkg.permissions.get(i);
3575 boolean tree = false;
3576 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3577 if (bp == null) {
3578 tree = true;
3579 bp = mSettings.mPermissionTrees.get(p.info.name);
3580 }
3581 if (bp != null && bp.perm == p) {
3582 if (bp.type != BasePermission.TYPE_BUILTIN) {
3583 if (tree) {
3584 mSettings.mPermissionTrees.remove(p.info.name);
3585 } else {
3586 mSettings.mPermissions.remove(p.info.name);
3587 }
3588 } else {
3589 bp.perm = null;
3590 }
3591 if (chatty) {
3592 if (r == null) {
3593 r = new StringBuilder(256);
3594 } else {
3595 r.append(' ');
3596 }
3597 r.append(p.info.name);
3598 }
3599 }
3600 }
3601 if (r != null) {
3602 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3603 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003605 N = pkg.instrumentation.size();
3606 r = null;
3607 for (i=0; i<N; i++) {
3608 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003609 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 if (chatty) {
3611 if (r == null) {
3612 r = new StringBuilder(256);
3613 } else {
3614 r.append(' ');
3615 }
3616 r.append(a.info.name);
3617 }
3618 }
3619 if (r != null) {
3620 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3621 }
3622 }
3623 }
3624
3625 private static final boolean isPackageFilename(String name) {
3626 return name != null && name.endsWith(".apk");
3627 }
3628
3629 private void updatePermissionsLP() {
3630 // Make sure there are no dangling permission trees.
3631 Iterator<BasePermission> it = mSettings.mPermissionTrees
3632 .values().iterator();
3633 while (it.hasNext()) {
3634 BasePermission bp = it.next();
3635 if (bp.perm == null) {
3636 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3637 + " from package " + bp.sourcePackage);
3638 it.remove();
3639 }
3640 }
3641
3642 // Make sure all dynamic permissions have been assigned to a package,
3643 // and make sure there are no dangling permissions.
3644 it = mSettings.mPermissions.values().iterator();
3645 while (it.hasNext()) {
3646 BasePermission bp = it.next();
3647 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3648 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3649 + bp.name + " pkg=" + bp.sourcePackage
3650 + " info=" + bp.pendingInfo);
3651 if (bp.perm == null && bp.pendingInfo != null) {
3652 BasePermission tree = findPermissionTreeLP(bp.name);
3653 if (tree != null) {
3654 bp.perm = new PackageParser.Permission(tree.perm.owner,
3655 new PermissionInfo(bp.pendingInfo));
3656 bp.perm.info.packageName = tree.perm.info.packageName;
3657 bp.perm.info.name = bp.name;
3658 bp.uid = tree.uid;
3659 }
3660 }
3661 }
3662 if (bp.perm == null) {
3663 Log.w(TAG, "Removing dangling permission: " + bp.name
3664 + " from package " + bp.sourcePackage);
3665 it.remove();
3666 }
3667 }
3668
3669 // Now update the permissions for all packages, in particular
3670 // replace the granted permissions of the system packages.
3671 for (PackageParser.Package pkg : mPackages.values()) {
3672 grantPermissionsLP(pkg, false);
3673 }
3674 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3677 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3678 if (ps == null) {
3679 return;
3680 }
3681 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3682 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684 if (replace) {
3685 ps.permissionsFixed = false;
3686 if (gp == ps) {
3687 gp.grantedPermissions.clear();
3688 gp.gids = mGlobalGids;
3689 }
3690 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 if (gp.gids == null) {
3693 gp.gids = mGlobalGids;
3694 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 final int N = pkg.requestedPermissions.size();
3697 for (int i=0; i<N; i++) {
3698 String name = pkg.requestedPermissions.get(i);
3699 BasePermission bp = mSettings.mPermissions.get(name);
3700 PackageParser.Permission p = bp != null ? bp.perm : null;
3701 if (false) {
3702 if (gp != ps) {
3703 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3704 + ": " + p);
3705 }
3706 }
3707 if (p != null) {
3708 final String perm = p.info.name;
3709 boolean allowed;
3710 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3711 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3712 allowed = true;
3713 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3714 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003715 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003717 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 == PackageManager.SIGNATURE_MATCH);
3719 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3720 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3721 // For updated system applications, the signatureOrSystem permission
3722 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003723 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3725 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3726 if(sysPs.grantedPermissions.contains(perm)) {
3727 allowed = true;
3728 } else {
3729 allowed = false;
3730 }
3731 } else {
3732 allowed = true;
3733 }
3734 }
3735 }
3736 } else {
3737 allowed = false;
3738 }
3739 if (false) {
3740 if (gp != ps) {
3741 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3742 }
3743 }
3744 if (allowed) {
3745 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3746 && ps.permissionsFixed) {
3747 // If this is an existing, non-system package, then
3748 // we can't add any new permissions to it.
3749 if (!gp.loadedPermissions.contains(perm)) {
3750 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003751 // Except... if this is a permission that was added
3752 // to the platform (note: need to only do this when
3753 // updating the platform).
3754 final int NP = PackageParser.NEW_PERMISSIONS.length;
3755 for (int ip=0; ip<NP; ip++) {
3756 final PackageParser.NewPermissionInfo npi
3757 = PackageParser.NEW_PERMISSIONS[ip];
3758 if (npi.name.equals(perm)
3759 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3760 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003761 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003762 + pkg.packageName);
3763 break;
3764 }
3765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 }
3767 }
3768 if (allowed) {
3769 if (!gp.grantedPermissions.contains(perm)) {
3770 addedPermission = true;
3771 gp.grantedPermissions.add(perm);
3772 gp.gids = appendInts(gp.gids, bp.gids);
3773 }
3774 } else {
3775 Log.w(TAG, "Not granting permission " + perm
3776 + " to package " + pkg.packageName
3777 + " because it was previously installed without");
3778 }
3779 } else {
3780 Log.w(TAG, "Not granting permission " + perm
3781 + " to package " + pkg.packageName
3782 + " (protectionLevel=" + p.info.protectionLevel
3783 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3784 + ")");
3785 }
3786 } else {
3787 Log.w(TAG, "Unknown permission " + name
3788 + " in package " + pkg.packageName);
3789 }
3790 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003793 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3794 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 // This is the first that we have heard about this package, so the
3796 // permissions we have now selected are fixed until explicitly
3797 // changed.
3798 ps.permissionsFixed = true;
3799 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3800 }
3801 }
3802
3803 private final class ActivityIntentResolver
3804 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003805 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003806 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003807 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 }
3809
Mihai Preda074edef2009-05-18 17:13:31 +02003810 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003812 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3814 }
3815
Mihai Predaeae850c2009-05-13 10:13:48 +02003816 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3817 ArrayList<PackageParser.Activity> packageActivities) {
3818 if (packageActivities == null) {
3819 return null;
3820 }
3821 mFlags = flags;
3822 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3823 int N = packageActivities.size();
3824 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3825 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003826
3827 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003828 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003829 intentFilters = packageActivities.get(i).intents;
3830 if (intentFilters != null && intentFilters.size() > 0) {
3831 listCut.add(intentFilters);
3832 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003833 }
3834 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3835 }
3836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003838 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 if (SHOW_INFO || Config.LOGV) Log.v(
3840 TAG, " " + type + " " +
3841 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3842 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3843 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003844 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3846 if (SHOW_INFO || Config.LOGV) {
3847 Log.v(TAG, " IntentFilter:");
3848 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3849 }
3850 if (!intent.debugCheck()) {
3851 Log.w(TAG, "==> For Activity " + a.info.name);
3852 }
3853 addFilter(intent);
3854 }
3855 }
3856
3857 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003858 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 if (SHOW_INFO || Config.LOGV) Log.v(
3860 TAG, " " + type + " " +
3861 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3862 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3863 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003864 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3866 if (SHOW_INFO || Config.LOGV) {
3867 Log.v(TAG, " IntentFilter:");
3868 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3869 }
3870 removeFilter(intent);
3871 }
3872 }
3873
3874 @Override
3875 protected boolean allowFilterResult(
3876 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3877 ActivityInfo filterAi = filter.activity.info;
3878 for (int i=dest.size()-1; i>=0; i--) {
3879 ActivityInfo destAi = dest.get(i).activityInfo;
3880 if (destAi.name == filterAi.name
3881 && destAi.packageName == filterAi.packageName) {
3882 return false;
3883 }
3884 }
3885 return true;
3886 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 @Override
3889 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3890 int match) {
3891 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3892 return null;
3893 }
3894 final PackageParser.Activity activity = info.activity;
3895 if (mSafeMode && (activity.info.applicationInfo.flags
3896 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3897 return null;
3898 }
3899 final ResolveInfo res = new ResolveInfo();
3900 res.activityInfo = PackageParser.generateActivityInfo(activity,
3901 mFlags);
3902 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3903 res.filter = info;
3904 }
3905 res.priority = info.getPriority();
3906 res.preferredOrder = activity.owner.mPreferredOrder;
3907 //System.out.println("Result: " + res.activityInfo.className +
3908 // " = " + res.priority);
3909 res.match = match;
3910 res.isDefault = info.hasDefault;
3911 res.labelRes = info.labelRes;
3912 res.nonLocalizedLabel = info.nonLocalizedLabel;
3913 res.icon = info.icon;
3914 return res;
3915 }
3916
3917 @Override
3918 protected void sortResults(List<ResolveInfo> results) {
3919 Collections.sort(results, mResolvePrioritySorter);
3920 }
3921
3922 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003923 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003925 out.print(prefix); out.print(
3926 Integer.toHexString(System.identityHashCode(filter.activity)));
3927 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003928 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 }
3930
3931// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3932// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3933// final List<ResolveInfo> retList = Lists.newArrayList();
3934// while (i.hasNext()) {
3935// final ResolveInfo resolveInfo = i.next();
3936// if (isEnabledLP(resolveInfo.activityInfo)) {
3937// retList.add(resolveInfo);
3938// }
3939// }
3940// return retList;
3941// }
3942
3943 // Keys are String (activity class name), values are Activity.
3944 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3945 = new HashMap<ComponentName, PackageParser.Activity>();
3946 private int mFlags;
3947 }
3948
3949 private final class ServiceIntentResolver
3950 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003951 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003953 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 }
3955
Mihai Preda074edef2009-05-18 17:13:31 +02003956 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003958 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3960 }
3961
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003962 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3963 ArrayList<PackageParser.Service> packageServices) {
3964 if (packageServices == null) {
3965 return null;
3966 }
3967 mFlags = flags;
3968 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3969 int N = packageServices.size();
3970 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3971 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3972
3973 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3974 for (int i = 0; i < N; ++i) {
3975 intentFilters = packageServices.get(i).intents;
3976 if (intentFilters != null && intentFilters.size() > 0) {
3977 listCut.add(intentFilters);
3978 }
3979 }
3980 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3981 }
3982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003984 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 if (SHOW_INFO || Config.LOGV) Log.v(
3986 TAG, " " + (s.info.nonLocalizedLabel != null
3987 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3988 if (SHOW_INFO || Config.LOGV) Log.v(
3989 TAG, " Class=" + s.info.name);
3990 int NI = s.intents.size();
3991 int j;
3992 for (j=0; j<NI; j++) {
3993 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3994 if (SHOW_INFO || Config.LOGV) {
3995 Log.v(TAG, " IntentFilter:");
3996 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3997 }
3998 if (!intent.debugCheck()) {
3999 Log.w(TAG, "==> For Service " + s.info.name);
4000 }
4001 addFilter(intent);
4002 }
4003 }
4004
4005 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004006 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 if (SHOW_INFO || Config.LOGV) Log.v(
4008 TAG, " " + (s.info.nonLocalizedLabel != null
4009 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4010 if (SHOW_INFO || Config.LOGV) Log.v(
4011 TAG, " Class=" + s.info.name);
4012 int NI = s.intents.size();
4013 int j;
4014 for (j=0; j<NI; j++) {
4015 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4016 if (SHOW_INFO || Config.LOGV) {
4017 Log.v(TAG, " IntentFilter:");
4018 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4019 }
4020 removeFilter(intent);
4021 }
4022 }
4023
4024 @Override
4025 protected boolean allowFilterResult(
4026 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4027 ServiceInfo filterSi = filter.service.info;
4028 for (int i=dest.size()-1; i>=0; i--) {
4029 ServiceInfo destAi = dest.get(i).serviceInfo;
4030 if (destAi.name == filterSi.name
4031 && destAi.packageName == filterSi.packageName) {
4032 return false;
4033 }
4034 }
4035 return true;
4036 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 @Override
4039 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4040 int match) {
4041 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4042 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4043 return null;
4044 }
4045 final PackageParser.Service service = info.service;
4046 if (mSafeMode && (service.info.applicationInfo.flags
4047 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4048 return null;
4049 }
4050 final ResolveInfo res = new ResolveInfo();
4051 res.serviceInfo = PackageParser.generateServiceInfo(service,
4052 mFlags);
4053 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4054 res.filter = filter;
4055 }
4056 res.priority = info.getPriority();
4057 res.preferredOrder = service.owner.mPreferredOrder;
4058 //System.out.println("Result: " + res.activityInfo.className +
4059 // " = " + res.priority);
4060 res.match = match;
4061 res.isDefault = info.hasDefault;
4062 res.labelRes = info.labelRes;
4063 res.nonLocalizedLabel = info.nonLocalizedLabel;
4064 res.icon = info.icon;
4065 return res;
4066 }
4067
4068 @Override
4069 protected void sortResults(List<ResolveInfo> results) {
4070 Collections.sort(results, mResolvePrioritySorter);
4071 }
4072
4073 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004074 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004076 out.print(prefix); out.print(
4077 Integer.toHexString(System.identityHashCode(filter.service)));
4078 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004079 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 }
4081
4082// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4083// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4084// final List<ResolveInfo> retList = Lists.newArrayList();
4085// while (i.hasNext()) {
4086// final ResolveInfo resolveInfo = (ResolveInfo) i;
4087// if (isEnabledLP(resolveInfo.serviceInfo)) {
4088// retList.add(resolveInfo);
4089// }
4090// }
4091// return retList;
4092// }
4093
4094 // Keys are String (activity class name), values are Activity.
4095 private final HashMap<ComponentName, PackageParser.Service> mServices
4096 = new HashMap<ComponentName, PackageParser.Service>();
4097 private int mFlags;
4098 };
4099
4100 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4101 new Comparator<ResolveInfo>() {
4102 public int compare(ResolveInfo r1, ResolveInfo r2) {
4103 int v1 = r1.priority;
4104 int v2 = r2.priority;
4105 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4106 if (v1 != v2) {
4107 return (v1 > v2) ? -1 : 1;
4108 }
4109 v1 = r1.preferredOrder;
4110 v2 = r2.preferredOrder;
4111 if (v1 != v2) {
4112 return (v1 > v2) ? -1 : 1;
4113 }
4114 if (r1.isDefault != r2.isDefault) {
4115 return r1.isDefault ? -1 : 1;
4116 }
4117 v1 = r1.match;
4118 v2 = r2.match;
4119 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4120 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4121 }
4122 };
4123
4124 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4125 new Comparator<ProviderInfo>() {
4126 public int compare(ProviderInfo p1, ProviderInfo p2) {
4127 final int v1 = p1.initOrder;
4128 final int v2 = p2.initOrder;
4129 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4130 }
4131 };
4132
4133 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4134 IActivityManager am = ActivityManagerNative.getDefault();
4135 if (am != null) {
4136 try {
4137 final Intent intent = new Intent(action,
4138 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4139 if (extras != null) {
4140 intent.putExtras(extras);
4141 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004142 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 am.broadcastIntent(
4144 null, intent,
4145 null, null, 0, null, null, null, false, false);
4146 } catch (RemoteException ex) {
4147 }
4148 }
4149 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004150
4151 public String nextPackageToClean(String lastPackage) {
4152 synchronized (mPackages) {
4153 if (!mMediaMounted) {
4154 // If the external storage is no longer mounted at this point,
4155 // the caller may not have been able to delete all of this
4156 // packages files and can not delete any more. Bail.
4157 return null;
4158 }
4159 if (lastPackage != null) {
4160 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4161 }
4162 return mSettings.mPackagesToBeCleaned.size() > 0
4163 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4164 }
4165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004167 void schedulePackageCleaning(String packageName) {
4168 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4169 }
4170
4171 void startCleaningPackages() {
4172 synchronized (mPackages) {
4173 if (!mMediaMounted) {
4174 return;
4175 }
4176 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4177 return;
4178 }
4179 }
4180 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4181 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4182 IActivityManager am = ActivityManagerNative.getDefault();
4183 if (am != null) {
4184 try {
4185 am.startService(null, intent, null);
4186 } catch (RemoteException e) {
4187 }
4188 }
4189 }
4190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 private final class AppDirObserver extends FileObserver {
4192 public AppDirObserver(String path, int mask, boolean isrom) {
4193 super(path, mask);
4194 mRootDir = path;
4195 mIsRom = isrom;
4196 }
4197
4198 public void onEvent(int event, String path) {
4199 String removedPackage = null;
4200 int removedUid = -1;
4201 String addedPackage = null;
4202 int addedUid = -1;
4203
4204 synchronized (mInstallLock) {
4205 String fullPathStr = null;
4206 File fullPath = null;
4207 if (path != null) {
4208 fullPath = new File(mRootDir, path);
4209 fullPathStr = fullPath.getPath();
4210 }
4211
4212 if (Config.LOGV) Log.v(
4213 TAG, "File " + fullPathStr + " changed: "
4214 + Integer.toHexString(event));
4215
4216 if (!isPackageFilename(path)) {
4217 if (Config.LOGV) Log.v(
4218 TAG, "Ignoring change of non-package file: " + fullPathStr);
4219 return;
4220 }
4221
4222 if ((event&REMOVE_EVENTS) != 0) {
4223 synchronized (mInstallLock) {
4224 PackageParser.Package p = mAppDirs.get(fullPathStr);
4225 if (p != null) {
4226 removePackageLI(p, true);
4227 removedPackage = p.applicationInfo.packageName;
4228 removedUid = p.applicationInfo.uid;
4229 }
4230 }
4231 }
4232
4233 if ((event&ADD_EVENTS) != 0) {
4234 PackageParser.Package p = mAppDirs.get(fullPathStr);
4235 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004236 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4238 PackageParser.PARSE_CHATTY |
4239 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004240 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 if (p != null) {
4242 synchronized (mPackages) {
4243 grantPermissionsLP(p, false);
4244 }
4245 addedPackage = p.applicationInfo.packageName;
4246 addedUid = p.applicationInfo.uid;
4247 }
4248 }
4249 }
4250
4251 synchronized (mPackages) {
4252 mSettings.writeLP();
4253 }
4254 }
4255
4256 if (removedPackage != null) {
4257 Bundle extras = new Bundle(1);
4258 extras.putInt(Intent.EXTRA_UID, removedUid);
4259 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4260 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4261 }
4262 if (addedPackage != null) {
4263 Bundle extras = new Bundle(1);
4264 extras.putInt(Intent.EXTRA_UID, addedUid);
4265 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4266 }
4267 }
4268
4269 private final String mRootDir;
4270 private final boolean mIsRom;
4271 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 /* Called when a downloaded package installation has been confirmed by the user */
4274 public void installPackage(
4275 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004276 installPackage(packageURI, observer, flags, null);
4277 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004278
Jacek Surazski65e13172009-04-28 15:26:38 +02004279 /* Called when a downloaded package installation has been confirmed by the user */
4280 public void installPackage(
4281 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4282 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 mContext.enforceCallingOrSelfPermission(
4284 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004285
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004286 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004287 msg.obj = new InstallParams(packageURI, observer, flags,
4288 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004289 mHandler.sendMessage(msg);
4290 }
4291
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004292 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 // Queue up an async operation since the package installation may take a little while.
4294 mHandler.post(new Runnable() {
4295 public void run() {
4296 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004297 // Result object to be returned
4298 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004299 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004300 res.uid = -1;
4301 res.pkg = null;
4302 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004303 args.doPreInstall(res.returnCode);
4304 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004305 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004306 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004307 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004308 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004310 if (args.observer != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004312 args.observer.packageInstalled(res.name, res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 } catch (RemoteException e) {
4314 Log.i(TAG, "Observer no longer exists.");
4315 }
4316 }
4317 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
4318 // call appears in the synchronized block above.
4319 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4320 res.removedInfo.sendBroadcast(false, true);
4321 Bundle extras = new Bundle(1);
4322 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004323 final boolean update = res.removedInfo.removedPackage != null;
4324 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4326 }
4327 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
4328 res.pkg.applicationInfo.packageName,
4329 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004330 if (update) {
4331 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
4332 res.pkg.applicationInfo.packageName,
4333 extras);
4334 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004335 if (res.removedInfo.args != null) {
4336 // Remove the replaced package's older resources safely now
4337 synchronized (mInstallLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004338 res.removedInfo.args.doPostDeleteLI(true);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004339 }
4340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 }
4342 Runtime.getRuntime().gc();
4343 }
4344 });
4345 }
4346
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004347 static final class InstallParams {
4348 final IPackageInstallObserver observer;
4349 int flags;
4350 final Uri packageURI;
4351 final String installerPackageName;
4352 InstallParams(Uri packageURI,
4353 IPackageInstallObserver observer, int flags,
4354 String installerPackageName) {
4355 this.packageURI = packageURI;
4356 this.flags = flags;
4357 this.observer = observer;
4358 this.installerPackageName = installerPackageName;
4359 }
4360
4361 public int getInstallLocation(IMediaContainerService imcs) {
4362 try {
4363 return imcs.getRecommendedInstallLocation(packageURI);
4364 } catch (RemoteException e) {
4365 }
4366 return -1;
4367 }
4368 };
4369
4370 private InstallArgs createInstallArgs(InstallParams params) {
4371 if (installOnSd(params.flags)) {
4372 return new SdInstallArgs(params);
4373 } else {
4374 return new FileInstallArgs(params);
4375 }
4376 }
4377
4378 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4379 if (installOnSd(flags)) {
4380 return new SdInstallArgs(fullCodePath, fullResourcePath);
4381 } else {
4382 return new FileInstallArgs(fullCodePath, fullResourcePath);
4383 }
4384 }
4385
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004386 static abstract class InstallArgs {
4387 final IPackageInstallObserver observer;
4388 final int flags;
4389 final Uri packageURI;
4390 final String installerPackageName;
4391
4392 InstallArgs(Uri packageURI,
4393 IPackageInstallObserver observer, int flags,
4394 String installerPackageName) {
4395 this.packageURI = packageURI;
4396 this.flags = flags;
4397 this.observer = observer;
4398 this.installerPackageName = installerPackageName;
4399 }
4400
4401 abstract void createCopyFile();
4402 abstract int copyApk(IMediaContainerService imcs);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004403 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004404 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004405 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004406 abstract String getCodePath();
4407 abstract String getResourcePath();
4408 // Need installer lock especially for dex file removal.
4409 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004410 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004411 }
4412
4413 class FileInstallArgs extends InstallArgs {
4414 File installDir;
4415 String codeFileName;
4416 String resourceFileName;
4417
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004418 FileInstallArgs(InstallParams params) {
4419 super(params.packageURI, params.observer,
4420 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004421 }
4422
4423 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4424 super(null, null, 0, null);
4425 File codeFile = new File(fullCodePath);
4426 installDir = codeFile.getParentFile();
4427 codeFileName = fullCodePath;
4428 resourceFileName = fullResourcePath;
4429 }
4430
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004431 String getCodePath() {
4432 return codeFileName;
4433 }
4434
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004435 void createCopyFile() {
4436 boolean fwdLocked = isFwdLocked(flags);
4437 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4438 codeFileName = createTempPackageFile(installDir).getPath();
4439 resourceFileName = getResourcePathFromCodePath();
4440 }
4441
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004442 int copyApk(IMediaContainerService imcs) {
4443 // Get a ParcelFileDescriptor to write to the output file
4444 File codeFile = new File(codeFileName);
4445 ParcelFileDescriptor out = null;
4446 try {
4447 out = ParcelFileDescriptor.open(codeFile,
4448 ParcelFileDescriptor.MODE_READ_WRITE);
4449 } catch (FileNotFoundException e) {
4450 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4451 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4452 }
4453 // Copy the resource now
4454 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4455 try {
4456 if (imcs.copyResource(packageURI, out)) {
4457 ret = PackageManager.INSTALL_SUCCEEDED;
4458 }
4459 } catch (RemoteException e) {
4460 } finally {
4461 try { if (out != null) out.close(); } catch (IOException e) {}
4462 }
4463 return ret;
4464 }
4465
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004466 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004467 if (status != PackageManager.INSTALL_SUCCEEDED) {
4468 cleanUp();
4469 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004470 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004471 }
4472
4473 boolean doRename(int status, final String pkgName, String oldCodePath) {
4474 if (status != PackageManager.INSTALL_SUCCEEDED) {
4475 cleanUp();
4476 return false;
4477 } else {
4478 // Rename based on packageName
4479 File codeFile = new File(getCodePath());
4480 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4481 File desFile = new File(installDir, apkName + ".apk");
4482 if (!codeFile.renameTo(desFile)) {
4483 return false;
4484 }
4485 // Reset paths since the file has been renamed.
4486 codeFileName = desFile.getPath();
4487 resourceFileName = getResourcePathFromCodePath();
4488 // Set permissions
4489 if (!setPermissions(pkgName)) {
4490 // Failed setting permissions.
4491 return false;
4492 }
4493 return true;
4494 }
4495 }
4496
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004497 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004498 if (status != PackageManager.INSTALL_SUCCEEDED) {
4499 cleanUp();
4500 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004501 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004502 }
4503
4504 String getResourcePath() {
4505 return resourceFileName;
4506 }
4507
4508 String getResourcePathFromCodePath() {
4509 String codePath = getCodePath();
4510 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4511 String apkNameOnly = getApkName(codePath);
4512 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4513 } else {
4514 return codePath;
4515 }
4516 }
4517
4518 private boolean cleanUp() {
4519 boolean ret = true;
4520 String sourceDir = getCodePath();
4521 String publicSourceDir = getResourcePath();
4522 if (sourceDir != null) {
4523 File sourceFile = new File(sourceDir);
4524 if (!sourceFile.exists()) {
4525 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4526 ret = false;
4527 }
4528 // Delete application's code and resources
4529 sourceFile.delete();
4530 }
4531 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4532 final File publicSourceFile = new File(publicSourceDir);
4533 if (!publicSourceFile.exists()) {
4534 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4535 }
4536 if (publicSourceFile.exists()) {
4537 publicSourceFile.delete();
4538 }
4539 }
4540 return ret;
4541 }
4542
4543 void cleanUpResourcesLI() {
4544 String sourceDir = getCodePath();
4545 if (cleanUp() && mInstaller != null) {
4546 int retCode = mInstaller.rmdex(sourceDir);
4547 if (retCode < 0) {
4548 Log.w(TAG, "Couldn't remove dex file for package: "
4549 + " at location "
4550 + sourceDir + ", retcode=" + retCode);
4551 // we don't consider this to be a failure of the core package deletion
4552 }
4553 }
4554 }
4555
4556 private boolean setPermissions(String pkgName) {
4557 // TODO Do this in a more elegant way later on. for now just a hack
4558 if (!isFwdLocked(flags)) {
4559 final int filePermissions =
4560 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4561 |FileUtils.S_IROTH;
4562 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4563 if (retCode != 0) {
4564 Log.e(TAG, "Couldn't set new package file permissions for " +
4565 getCodePath()
4566 + ". The return code was: " + retCode);
4567 // TODO Define new internal error
4568 return false;
4569 }
4570 return true;
4571 }
4572 return true;
4573 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004574
4575 boolean doPostDeleteLI(boolean delete) {
4576 cleanUpResourcesLI();
4577 return true;
4578 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004579 }
4580
4581 class SdInstallArgs extends InstallArgs {
4582 String cid;
4583 String cachePath;
4584 static final String RES_FILE_NAME = "pkg.apk";
4585
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004586 SdInstallArgs(InstallParams params) {
4587 super(params.packageURI, params.observer,
4588 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004589 }
4590
4591 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004592 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004593 // Extract cid from fullCodePath
4594 int eidx = fullCodePath.lastIndexOf("/");
4595 String subStr1 = fullCodePath.substring(0, eidx);
4596 int sidx = subStr1.lastIndexOf("/");
4597 cid = subStr1.substring(sidx+1, eidx);
4598 cachePath = subStr1;
4599 }
4600
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004601 SdInstallArgs(String cid) {
4602 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
4603 this.cid = cid;
4604 }
4605
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004606 void createCopyFile() {
4607 cid = getTempContainerId();
4608 }
4609
4610 int copyApk(IMediaContainerService imcs) {
4611 try {
4612 cachePath = imcs.copyResourceToContainer(
4613 packageURI, cid,
4614 getEncryptKey(), RES_FILE_NAME);
4615 } catch (RemoteException e) {
4616 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004617 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4618 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004619 }
4620
4621 @Override
4622 String getCodePath() {
4623 return cachePath + "/" + RES_FILE_NAME;
4624 }
4625
4626 @Override
4627 String getResourcePath() {
4628 return cachePath + "/" + RES_FILE_NAME;
4629 }
4630
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004631 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004632 if (status != PackageManager.INSTALL_SUCCEEDED) {
4633 // Destroy container
4634 destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004635 } else {
4636 // STOPSHIP Remove once new api is added in MountService
4637 //boolean mounted = isContainerMounted(cid);
4638 boolean mounted = false;
4639 if (!mounted) {
4640 cachePath = mountSdDir(cid, Process.SYSTEM_UID);
4641 if (cachePath == null) {
4642 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4643 }
4644 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004645 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004646 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004647 }
4648
4649 boolean doRename(int status, final String pkgName,
4650 String oldCodePath) {
4651 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004652 String newCachePath = null;
4653 /*final int RENAME_FAILED = 1;
4654 final int MOUNT_FAILED = 2;
4655 final int DESTROY_FAILED = 3;
4656 final int PASS = 4;
4657 int errCode = RENAME_FAILED;
4658 if (mounted) {
4659 // Unmount the container
4660 if (!unMountSdDir(cid)) {
4661 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
4662 return false;
4663 }
4664 mounted = false;
4665 }
4666 if (renameSdDir(cid, newCacheId)) {
4667 errCode = MOUNT_FAILED;
4668 if ((newCachePath = mountSdDir(newCacheId, Process.SYSTEM_UID)) != null) {
4669 errCode = PASS;
4670 }
4671 }
4672 String errMsg = "";
4673 switch (errCode) {
4674 case RENAME_FAILED:
4675 errMsg = "RENAME_FAILED";
4676 break;
4677 case MOUNT_FAILED:
4678 errMsg = "MOUNT_FAILED";
4679 break;
4680 case DESTROY_FAILED:
4681 errMsg = "DESTROY_FAILED";
4682 break;
4683 default:
4684 errMsg = "PASS";
4685 break;
4686 }
4687 Log.i(TAG, "Status: " + errMsg);
4688 if (errCode != PASS) {
4689 return false;
4690 }
4691 Log.i(TAG, "Succesfully renamed " + cid + " to " +newCacheId +
4692 " at path: " + cachePath + " to new path: " + newCachePath);
4693 cid = newCacheId;
4694 cachePath = newCachePath;
4695 return true;
4696 */
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004697 // STOPSHIP TEMPORARY HACK FOR RENAME
4698 // Create new container at newCachePath
4699 String codePath = getCodePath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004700 final int CREATE_FAILED = 1;
4701 final int COPY_FAILED = 3;
4702 final int FINALIZE_FAILED = 5;
4703 final int PASS = 7;
4704 int errCode = CREATE_FAILED;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004705
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004706 if ((newCachePath = createSdDir(new File(codePath), newCacheId)) != null) {
4707 errCode = COPY_FAILED;
4708 // Copy file from codePath
4709 if (FileUtils.copyFile(new File(codePath), new File(newCachePath, RES_FILE_NAME))) {
4710 errCode = FINALIZE_FAILED;
4711 if (finalizeSdDir(newCacheId)) {
4712 errCode = PASS;
4713 }
4714 }
4715 }
4716 // Print error based on errCode
4717 String errMsg = "";
4718 switch (errCode) {
4719 case CREATE_FAILED:
4720 errMsg = "CREATE_FAILED";
4721 break;
4722 case COPY_FAILED:
4723 errMsg = "COPY_FAILED";
4724 destroySdDir(newCacheId);
4725 break;
4726 case FINALIZE_FAILED:
4727 errMsg = "FINALIZE_FAILED";
4728 destroySdDir(newCacheId);
4729 break;
4730 default:
4731 errMsg = "PASS";
4732 break;
4733 }
4734 // Destroy the temporary container
4735 destroySdDir(cid);
4736 Log.i(TAG, "Status: " + errMsg);
4737 if (errCode != PASS) {
4738 return false;
4739 }
4740 cid = newCacheId;
4741 cachePath = newCachePath;
4742
4743 return true;
4744 }
4745
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004746 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004747 if (status != PackageManager.INSTALL_SUCCEEDED) {
4748 cleanUp();
4749 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004750 // STOP SHIP Change this once new api is added.
4751 //boolean mounted = isContainerMounted(cid);
4752 boolean mounted = false;
4753 if (!mounted) {
4754 mountSdDir(cid, Process.SYSTEM_UID);
4755 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004756 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004757 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004758 }
4759
4760 private void cleanUp() {
4761 // Destroy secure container
4762 destroySdDir(cid);
4763 }
4764
4765 void cleanUpResourcesLI() {
4766 String sourceFile = getCodePath();
4767 // Remove dex file
4768 if (mInstaller != null) {
4769 int retCode = mInstaller.rmdex(sourceFile.toString());
4770 if (retCode < 0) {
4771 Log.w(TAG, "Couldn't remove dex file for package: "
4772 + " at location "
4773 + sourceFile.toString() + ", retcode=" + retCode);
4774 // we don't consider this to be a failure of the core package deletion
4775 }
4776 }
4777 cleanUp();
4778 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004779
4780 boolean matchContainer(String app) {
4781 if (cid.startsWith(app)) {
4782 return true;
4783 }
4784 return false;
4785 }
4786
4787 String getPackageName() {
4788 int idx = cid.lastIndexOf("-");
4789 if (idx == -1) {
4790 return cid;
4791 }
4792 return cid.substring(0, idx);
4793 }
4794
4795 boolean doPostDeleteLI(boolean delete) {
4796 boolean ret = false;
4797 boolean mounted = isContainerMounted(cid);
4798 if (mounted) {
4799 // Unmount first
4800 ret = unMountSdDir(cid);
4801 }
4802 if (ret && delete) {
4803 cleanUpResourcesLI();
4804 }
4805 return ret;
4806 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004807 };
4808
4809 // Utility method used to create code paths based on package name and available index.
4810 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4811 String idxStr = "";
4812 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004813 // Fall back to default value of idx=1 if prefix is not
4814 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004815 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004816 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004817 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004818 if (subStr.endsWith(suffix)) {
4819 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004820 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004821 // If oldCodePath already contains prefix find out the
4822 // ending index to either increment or decrement.
4823 int sidx = subStr.lastIndexOf(prefix);
4824 if (sidx != -1) {
4825 subStr = subStr.substring(sidx + prefix.length());
4826 if (subStr != null) {
4827 if (subStr.startsWith("-")) {
4828 subStr = subStr.substring(1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004829 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004830 try {
4831 idx = Integer.parseInt(subStr);
4832 if (idx <= 1) {
4833 idx++;
4834 } else {
4835 idx--;
4836 }
4837 } catch(NumberFormatException e) {
4838 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004839 }
4840 }
4841 }
4842 idxStr = "-" + Integer.toString(idx);
4843 return prefix + idxStr;
4844 }
4845
4846 // Utility method that returns the relative package path with respect
4847 // to the installation directory. Like say for /data/data/com.test-1.apk
4848 // string com.test-1 is returned.
4849 static String getApkName(String codePath) {
4850 if (codePath == null) {
4851 return null;
4852 }
4853 int sidx = codePath.lastIndexOf("/");
4854 int eidx = codePath.lastIndexOf(".");
4855 if (eidx == -1) {
4856 eidx = codePath.length();
4857 } else if (eidx == 0) {
4858 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
4859 return null;
4860 }
4861 return codePath.substring(sidx+1, eidx);
4862 }
4863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864 class PackageInstalledInfo {
4865 String name;
4866 int uid;
4867 PackageParser.Package pkg;
4868 int returnCode;
4869 PackageRemovedInfo removedInfo;
4870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004872 /*
4873 * Install a non-existing package.
4874 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004875 private void installNewPackageLI(PackageParser.Package pkg,
4876 int parseFlags,
4877 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004878 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004879 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08004880 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004881 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08004882
4883 if (useEncryptedFilesystemForPackage(pkg)) {
4884 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
4885 } else {
4886 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
4887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004888 res.name = pkgName;
4889 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004890 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004892 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004893 + " without first uninstalling.");
4894 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4895 return;
4896 }
4897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004898 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004899 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004900 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004901 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4903 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4904 }
4905 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004906 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004907 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004908 res);
4909 // delete the partially installed application. the data directory will have to be
4910 // restored if it was already existing
4911 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4912 // remove package from internal structures. Note that we want deletePackageX to
4913 // delete the package data and cache directories that it created in
4914 // scanPackageLocked, unless those directories existed before we even tried to
4915 // install.
4916 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004917 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004918 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
4919 res.removedInfo);
4920 }
4921 }
4922 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004923
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004924 private void replacePackageLI(PackageParser.Package pkg,
4925 int parseFlags,
4926 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004927 String installerPackageName, PackageInstalledInfo res) {
4928
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004929 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004930 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 // First find the old package info and check signatures
4932 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004933 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004934 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004935 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004936 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4937 return;
4938 }
4939 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004940 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004941 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004942 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004944 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004945 }
4946 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004948 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004949 PackageParser.Package pkg,
4950 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004951 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 PackageParser.Package newPackage = null;
4953 String pkgName = deletedPackage.packageName;
4954 boolean deletedPkg = true;
4955 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004956
Jacek Surazski65e13172009-04-28 15:26:38 +02004957 String oldInstallerPackageName = null;
4958 synchronized (mPackages) {
4959 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
4960 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004961
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004962 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004964 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 res.removedInfo)) {
4966 // If the existing package was'nt successfully deleted
4967 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4968 deletedPkg = false;
4969 } else {
4970 // Successfully deleted the old package. Now proceed with re-installation
4971 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004972 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004973 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004974 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004975 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4976 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08004977 }
4978 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004979 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004980 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004981 res);
4982 updatedSettings = true;
4983 }
4984 }
4985
4986 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4987 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004988 // were keeping around in case we needed them (see below) can now be deleted.
4989 // This info will be set on the res.removedInfo to clean up later on as post
4990 // install action.
4991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004992 //update signature on the new package setting
4993 //this should always succeed, since we checked the
4994 //signature earlier.
4995 synchronized(mPackages) {
4996 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
4997 parseFlags, true);
4998 }
4999 } else {
5000 // remove package from internal structures. Note that we want deletePackageX to
5001 // delete the package data and cache directories that it created in
5002 // scanPackageLocked, unless those directories existed before we even tried to
5003 // install.
5004 if(updatedSettings) {
5005 deletePackageLI(
5006 pkgName, true,
5007 PackageManager.DONT_DELETE_DATA,
5008 res.removedInfo);
5009 }
5010 // Since we failed to install the new package we need to restore the old
5011 // package that we deleted.
5012 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005013 File restoreFile = new File(deletedPackage.mPath);
5014 if (restoreFile == null) {
5015 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
5016 return;
5017 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005018 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5019 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005020 // Parse old package
5021 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5022 scanPackageLI(restoreFile, parseFlags, scanMode);
5023 synchronized (mPackages) {
5024 grantPermissionsLP(deletedPackage, false);
5025 mSettings.writeLP();
5026 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005027 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5028 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
5029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005030 }
5031 }
5032 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005034 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005035 PackageParser.Package pkg,
5036 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005037 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 PackageParser.Package newPackage = null;
5039 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005040 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005041 PackageParser.PARSE_IS_SYSTEM;
5042 String packageName = deletedPackage.packageName;
5043 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5044 if (packageName == null) {
5045 Log.w(TAG, "Attempt to delete null packageName.");
5046 return;
5047 }
5048 PackageParser.Package oldPkg;
5049 PackageSetting oldPkgSetting;
5050 synchronized (mPackages) {
5051 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005052 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005053 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5054 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005055 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005056 return;
5057 }
5058 }
5059 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5060 res.removedInfo.removedPackage = packageName;
5061 // Remove existing system package
5062 removePackageLI(oldPkg, true);
5063 synchronized (mPackages) {
5064 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5065 }
5066
5067 // Successfully disabled the old package. Now proceed with re-installation
5068 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5069 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005070 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005071 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005072 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005073 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5074 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5075 }
5076 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005077 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005078 updatedSettings = true;
5079 }
5080
5081 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5082 //update signature on the new package setting
5083 //this should always succeed, since we checked the
5084 //signature earlier.
5085 synchronized(mPackages) {
5086 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5087 parseFlags, true);
5088 }
5089 } else {
5090 // Re installation failed. Restore old information
5091 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005092 if (newPackage != null) {
5093 removePackageLI(newPackage, true);
5094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005095 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005096 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005098 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099 // Restore the old system information in Settings
5100 synchronized(mPackages) {
5101 if(updatedSettings) {
5102 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005103 mSettings.setInstallerPackageName(packageName,
5104 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105 }
5106 mSettings.writeLP();
5107 }
5108 }
5109 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005110
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005111 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005112 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005113 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 synchronized (mPackages) {
5115 //write settings. the installStatus will be incomplete at this stage.
5116 //note that the new package setting would have already been
5117 //added to mPackages. It hasn't been persisted yet.
5118 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5119 mSettings.writeLP();
5120 }
5121
5122 int retCode = 0;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005123 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5124 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005126 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005127 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5128 return;
5129 }
5130 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005131 res.returnCode = setPermissionsLI(newPackage);
5132 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5133 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005134 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005135 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 }
5137 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5138 if (mInstaller != null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005139 mInstaller.rmdex(newPackage.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 }
5141 }
5142
5143 synchronized (mPackages) {
5144 grantPermissionsLP(newPackage, true);
5145 res.name = pkgName;
5146 res.uid = newPackage.applicationInfo.uid;
5147 res.pkg = newPackage;
5148 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005149 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5151 //to update install status
5152 mSettings.writeLP();
5153 }
5154 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005155
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005156 private void installPackageLI(InstallArgs args,
5157 boolean newInstall, PackageInstalledInfo res) {
5158 int pFlags = args.flags;
5159 String installerPackageName = args.installerPackageName;
5160 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005161 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005162 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005163 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005164 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5165 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005166 // Result object to be returned
5167 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5168
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005169 // Retrieve PackageSettings and parse package
5170 int parseFlags = PackageParser.PARSE_CHATTY |
5171 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5172 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5173 parseFlags |= mDefParseFlags;
5174 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5175 pp.setSeparateProcesses(mSeparateProcesses);
5176 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5177 null, mMetrics, parseFlags);
5178 if (pkg == null) {
5179 res.returnCode = pp.getParseError();
5180 return;
5181 }
5182 String pkgName = res.name = pkg.packageName;
5183 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5184 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5185 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5186 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005187 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005188 }
5189 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5190 res.returnCode = pp.getParseError();
5191 return;
5192 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005193 // Get rid of all references to package scan path via parser.
5194 pp = null;
5195 String oldCodePath = null;
5196 boolean systemApp = false;
5197 synchronized (mPackages) {
5198 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005199 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5200 String oldName = mSettings.mRenamedPackages.get(pkgName);
5201 if (oldName != null && oldName.equals(pkg.mOriginalPackage)
5202 && mPackages.containsKey(oldName)) {
5203 // This package is derived from an original package,
5204 // and this device has been updating from that original
5205 // name. We must continue using the original name, so
5206 // rename the new package here.
5207 pkg.setPackageName(pkg.mOriginalPackage);
5208 pkgName = pkg.packageName;
5209 replace = true;
5210 } else if (mPackages.containsKey(pkgName)) {
5211 // This package, under its official name, already exists
5212 // on the device; we should replace it.
5213 replace = true;
5214 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005215 }
5216 PackageSetting ps = mSettings.mPackages.get(pkgName);
5217 if (ps != null) {
5218 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5219 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5220 systemApp = (ps.pkg.applicationInfo.flags &
5221 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005222 }
5223 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005224 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005225
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005226 if (systemApp && onSd) {
5227 // Disable updates to system apps on sdcard
5228 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5229 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5230 return;
5231 }
5232 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5233 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5234 return;
5235 }
5236 // Set application objects path explicitly after the rename
5237 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005238 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005239 replacePackageLI(pkg, parseFlags, scanMode,
5240 installerPackageName, res);
5241 } else {
5242 installNewPackageLI(pkg, parseFlags, scanMode,
5243 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 }
5245 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005246
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005247 private int setPermissionsLI(PackageParser.Package newPackage) {
5248 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005249 int retCode = 0;
5250 // TODO Gross hack but fix later. Ideally move this to be a post installation
5251 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005252 if ((newPackage.applicationInfo.flags
5253 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5254 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255 try {
5256 extractPublicFiles(newPackage, destResourceFile);
5257 } catch (IOException e) {
5258 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5259 " forward-locked app.");
5260 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5261 } finally {
5262 //TODO clean up the extracted public files
5263 }
5264 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005265 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005266 newPackage.applicationInfo.uid);
5267 } else {
5268 final int filePermissions =
5269 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005270 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005271 newPackage.applicationInfo.uid);
5272 }
5273 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005274 // The permissions on the resource file was set when it was copied for
5275 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005276 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005278 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005279 Log.e(TAG, "Couldn't set new package file permissions for " +
5280 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005281 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005282 // TODO Define new internal error
5283 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005284 }
5285 return PackageManager.INSTALL_SUCCEEDED;
5286 }
5287
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005288 private boolean isForwardLocked(PackageParser.Package pkg) {
5289 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005290 }
5291
5292 private void extractPublicFiles(PackageParser.Package newPackage,
5293 File publicZipFile) throws IOException {
5294 final ZipOutputStream publicZipOutStream =
5295 new ZipOutputStream(new FileOutputStream(publicZipFile));
5296 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5297
5298 // Copy manifest, resources.arsc and res directory to public zip
5299
5300 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5301 while (privateZipEntries.hasMoreElements()) {
5302 final ZipEntry zipEntry = privateZipEntries.nextElement();
5303 final String zipEntryName = zipEntry.getName();
5304 if ("AndroidManifest.xml".equals(zipEntryName)
5305 || "resources.arsc".equals(zipEntryName)
5306 || zipEntryName.startsWith("res/")) {
5307 try {
5308 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5309 } catch (IOException e) {
5310 try {
5311 publicZipOutStream.close();
5312 throw e;
5313 } finally {
5314 publicZipFile.delete();
5315 }
5316 }
5317 }
5318 }
5319
5320 publicZipOutStream.close();
5321 FileUtils.setPermissions(
5322 publicZipFile.getAbsolutePath(),
5323 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5324 -1, -1);
5325 }
5326
5327 private static void copyZipEntry(ZipEntry zipEntry,
5328 ZipFile inZipFile,
5329 ZipOutputStream outZipStream) throws IOException {
5330 byte[] buffer = new byte[4096];
5331 int num;
5332
5333 ZipEntry newEntry;
5334 if (zipEntry.getMethod() == ZipEntry.STORED) {
5335 // Preserve the STORED method of the input entry.
5336 newEntry = new ZipEntry(zipEntry);
5337 } else {
5338 // Create a new entry so that the compressed len is recomputed.
5339 newEntry = new ZipEntry(zipEntry.getName());
5340 }
5341 outZipStream.putNextEntry(newEntry);
5342
5343 InputStream data = inZipFile.getInputStream(zipEntry);
5344 while ((num = data.read(buffer)) > 0) {
5345 outZipStream.write(buffer, 0, num);
5346 }
5347 outZipStream.flush();
5348 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005350 private void deleteTempPackageFiles() {
5351 FilenameFilter filter = new FilenameFilter() {
5352 public boolean accept(File dir, String name) {
5353 return name.startsWith("vmdl") && name.endsWith(".tmp");
5354 }
5355 };
5356 String tmpFilesList[] = mAppInstallDir.list(filter);
5357 if(tmpFilesList == null) {
5358 return;
5359 }
5360 for(int i = 0; i < tmpFilesList.length; i++) {
5361 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5362 tmpFile.delete();
5363 }
5364 }
5365
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005366 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 File tmpPackageFile;
5368 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005369 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 } catch (IOException e) {
5371 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5372 return null;
5373 }
5374 try {
5375 FileUtils.setPermissions(
5376 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5377 -1, -1);
5378 } catch (IOException e) {
5379 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5380 return null;
5381 }
5382 return tmpPackageFile;
5383 }
5384
5385 public void deletePackage(final String packageName,
5386 final IPackageDeleteObserver observer,
5387 final int flags) {
5388 mContext.enforceCallingOrSelfPermission(
5389 android.Manifest.permission.DELETE_PACKAGES, null);
5390 // Queue up an async operation since the package deletion may take a little while.
5391 mHandler.post(new Runnable() {
5392 public void run() {
5393 mHandler.removeCallbacks(this);
5394 final boolean succeded = deletePackageX(packageName, true, true, flags);
5395 if (observer != null) {
5396 try {
5397 observer.packageDeleted(succeded);
5398 } catch (RemoteException e) {
5399 Log.i(TAG, "Observer no longer exists.");
5400 } //end catch
5401 } //end if
5402 } //end run
5403 });
5404 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005406 /**
5407 * This method is an internal method that could be get invoked either
5408 * to delete an installed package or to clean up a failed installation.
5409 * After deleting an installed package, a broadcast is sent to notify any
5410 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005411 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412 * installation wouldn't have sent the initial broadcast either
5413 * The key steps in deleting a package are
5414 * deleting the package information in internal structures like mPackages,
5415 * deleting the packages base directories through installd
5416 * updating mSettings to reflect current status
5417 * persisting settings for later use
5418 * sending a broadcast if necessary
5419 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5421 boolean deleteCodeAndResources, int flags) {
5422 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005423 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424
5425 synchronized (mInstallLock) {
5426 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5427 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005430 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5431 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5432
5433 // If the removed package was a system update, the old system packaged
5434 // was re-enabled; we need to broadcast this information
5435 if (systemUpdate) {
5436 Bundle extras = new Bundle(1);
5437 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5438 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5439
5440 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5441 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005444 // Delete the resources here after sending the broadcast to let
5445 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005446 if (info.args != null) {
5447 synchronized (mInstallLock) {
5448 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005449 }
5450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 return res;
5452 }
5453
5454 static class PackageRemovedInfo {
5455 String removedPackage;
5456 int uid = -1;
5457 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005458 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005459 // Clean up resources deleted packages.
5460 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462 void sendBroadcast(boolean fullRemove, boolean replacing) {
5463 Bundle extras = new Bundle(1);
5464 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5465 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5466 if (replacing) {
5467 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5468 }
5469 if (removedPackage != null) {
5470 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5471 }
5472 if (removedUid >= 0) {
5473 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5474 }
5475 }
5476 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 /*
5479 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5480 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005481 * 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 -08005482 * delete a partially installed application.
5483 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005484 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 int flags) {
5486 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005487 if (outInfo != null) {
5488 outInfo.removedPackage = packageName;
5489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490 removePackageLI(p, true);
5491 // Retrieve object to delete permissions for shared user later on
5492 PackageSetting deletedPs;
5493 synchronized (mPackages) {
5494 deletedPs = mSettings.mPackages.get(packageName);
5495 }
5496 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005497 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005499 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005500 if (retCode < 0) {
5501 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5502 + packageName + ", retcode=" + retCode);
5503 // we don't consider this to be a failure of the core package deletion
5504 }
5505 } else {
5506 //for emulator
5507 PackageParser.Package pkg = mPackages.get(packageName);
5508 File dataDir = new File(pkg.applicationInfo.dataDir);
5509 dataDir.delete();
5510 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005511 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005513 if (outInfo != null) {
5514 outInfo.removedUid = mSettings.removePackageLP(packageName);
5515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 }
5517 }
5518 synchronized (mPackages) {
5519 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5520 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005521 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 }
5523 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005524 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 }
5526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 /*
5529 * Tries to delete system package.
5530 */
5531 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005532 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005533 ApplicationInfo applicationInfo = p.applicationInfo;
5534 //applicable for non-partially installed applications only
5535 if (applicationInfo == null) {
5536 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5537 return false;
5538 }
5539 PackageSetting ps = null;
5540 // Confirm if the system package has been updated
5541 // An updated system app can be deleted. This will also have to restore
5542 // the system pkg from system partition
5543 synchronized (mPackages) {
5544 ps = mSettings.getDisabledSystemPkg(p.packageName);
5545 }
5546 if (ps == null) {
5547 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5548 return false;
5549 } else {
5550 Log.i(TAG, "Deleting system pkg from data partition");
5551 }
5552 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005553 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005554 boolean deleteCodeAndResources = false;
5555 if (ps.versionCode < p.mVersionCode) {
5556 // Delete code and resources for downgrades
5557 deleteCodeAndResources = true;
5558 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5559 flags &= ~PackageManager.DONT_DELETE_DATA;
5560 }
5561 } else {
5562 // Preserve data by setting flag
5563 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5564 flags |= PackageManager.DONT_DELETE_DATA;
5565 }
5566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5568 if (!ret) {
5569 return false;
5570 }
5571 synchronized (mPackages) {
5572 // Reinstate the old system package
5573 mSettings.enableSystemPackageLP(p.packageName);
5574 }
5575 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005576 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005578 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005580 if (newPkg == null) {
5581 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5582 return false;
5583 }
5584 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005585 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 mSettings.writeLP();
5587 }
5588 return true;
5589 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5592 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5593 ApplicationInfo applicationInfo = p.applicationInfo;
5594 if (applicationInfo == null) {
5595 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5596 return false;
5597 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005598 if (outInfo != null) {
5599 outInfo.uid = applicationInfo.uid;
5600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601
5602 // Delete package data from internal structures and also remove data if flag is set
5603 removePackageDataLI(p, outInfo, flags);
5604
5605 // Delete application code and resources
5606 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005607 // TODO can pick up from PackageSettings as well
5608 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005609 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005610 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5611 PackageManager.INSTALL_FORWARD_LOCK : 0;
5612 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005613 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 }
5615 return true;
5616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 /*
5619 * This method handles package deletion in general
5620 */
5621 private boolean deletePackageLI(String packageName,
5622 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5623 if (packageName == null) {
5624 Log.w(TAG, "Attempt to delete null packageName.");
5625 return false;
5626 }
5627 PackageParser.Package p;
5628 boolean dataOnly = false;
5629 synchronized (mPackages) {
5630 p = mPackages.get(packageName);
5631 if (p == null) {
5632 //this retrieves partially installed apps
5633 dataOnly = true;
5634 PackageSetting ps = mSettings.mPackages.get(packageName);
5635 if (ps == null) {
5636 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5637 return false;
5638 }
5639 p = ps.pkg;
5640 }
5641 }
5642 if (p == null) {
5643 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5644 return false;
5645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 if (dataOnly) {
5648 // Delete application data first
5649 removePackageDataLI(p, outInfo, flags);
5650 return true;
5651 }
5652 // At this point the package should have ApplicationInfo associated with it
5653 if (p.applicationInfo == null) {
5654 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5655 return false;
5656 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005657 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5659 Log.i(TAG, "Removing system package:"+p.packageName);
5660 // When an updated system application is deleted we delete the existing resources as well and
5661 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005662 ret = deleteSystemPackageLI(p, flags, outInfo);
5663 } else {
5664 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005665 // Kill application pre-emptively especially for apps on sd.
5666 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005667 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005669 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 public void clearApplicationUserData(final String packageName,
5673 final IPackageDataObserver observer) {
5674 mContext.enforceCallingOrSelfPermission(
5675 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5676 // Queue up an async operation since the package deletion may take a little while.
5677 mHandler.post(new Runnable() {
5678 public void run() {
5679 mHandler.removeCallbacks(this);
5680 final boolean succeeded;
5681 synchronized (mInstallLock) {
5682 succeeded = clearApplicationUserDataLI(packageName);
5683 }
5684 if (succeeded) {
5685 // invoke DeviceStorageMonitor's update method to clear any notifications
5686 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5687 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5688 if (dsm != null) {
5689 dsm.updateMemory();
5690 }
5691 }
5692 if(observer != null) {
5693 try {
5694 observer.onRemoveCompleted(packageName, succeeded);
5695 } catch (RemoteException e) {
5696 Log.i(TAG, "Observer no longer exists.");
5697 }
5698 } //end if observer
5699 } //end run
5700 });
5701 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 private boolean clearApplicationUserDataLI(String packageName) {
5704 if (packageName == null) {
5705 Log.w(TAG, "Attempt to delete null packageName.");
5706 return false;
5707 }
5708 PackageParser.Package p;
5709 boolean dataOnly = false;
5710 synchronized (mPackages) {
5711 p = mPackages.get(packageName);
5712 if(p == null) {
5713 dataOnly = true;
5714 PackageSetting ps = mSettings.mPackages.get(packageName);
5715 if((ps == null) || (ps.pkg == null)) {
5716 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5717 return false;
5718 }
5719 p = ps.pkg;
5720 }
5721 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005722 boolean useEncryptedFSDir = false;
5723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 if(!dataOnly) {
5725 //need to check this only for fully installed applications
5726 if (p == null) {
5727 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5728 return false;
5729 }
5730 final ApplicationInfo applicationInfo = p.applicationInfo;
5731 if (applicationInfo == null) {
5732 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5733 return false;
5734 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005735 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 }
5737 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005738 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 if (retCode < 0) {
5740 Log.w(TAG, "Couldn't remove cache files for package: "
5741 + packageName);
5742 return false;
5743 }
5744 }
5745 return true;
5746 }
5747
5748 public void deleteApplicationCacheFiles(final String packageName,
5749 final IPackageDataObserver observer) {
5750 mContext.enforceCallingOrSelfPermission(
5751 android.Manifest.permission.DELETE_CACHE_FILES, null);
5752 // Queue up an async operation since the package deletion may take a little while.
5753 mHandler.post(new Runnable() {
5754 public void run() {
5755 mHandler.removeCallbacks(this);
5756 final boolean succeded;
5757 synchronized (mInstallLock) {
5758 succeded = deleteApplicationCacheFilesLI(packageName);
5759 }
5760 if(observer != null) {
5761 try {
5762 observer.onRemoveCompleted(packageName, succeded);
5763 } catch (RemoteException e) {
5764 Log.i(TAG, "Observer no longer exists.");
5765 }
5766 } //end if observer
5767 } //end run
5768 });
5769 }
5770
5771 private boolean deleteApplicationCacheFilesLI(String packageName) {
5772 if (packageName == null) {
5773 Log.w(TAG, "Attempt to delete null packageName.");
5774 return false;
5775 }
5776 PackageParser.Package p;
5777 synchronized (mPackages) {
5778 p = mPackages.get(packageName);
5779 }
5780 if (p == null) {
5781 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5782 return false;
5783 }
5784 final ApplicationInfo applicationInfo = p.applicationInfo;
5785 if (applicationInfo == null) {
5786 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5787 return false;
5788 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005789 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005791 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 if (retCode < 0) {
5793 Log.w(TAG, "Couldn't remove cache files for package: "
5794 + packageName);
5795 return false;
5796 }
5797 }
5798 return true;
5799 }
5800
5801 public void getPackageSizeInfo(final String packageName,
5802 final IPackageStatsObserver observer) {
5803 mContext.enforceCallingOrSelfPermission(
5804 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5805 // Queue up an async operation since the package deletion may take a little while.
5806 mHandler.post(new Runnable() {
5807 public void run() {
5808 mHandler.removeCallbacks(this);
5809 PackageStats lStats = new PackageStats(packageName);
5810 final boolean succeded;
5811 synchronized (mInstallLock) {
5812 succeded = getPackageSizeInfoLI(packageName, lStats);
5813 }
5814 if(observer != null) {
5815 try {
5816 observer.onGetStatsCompleted(lStats, succeded);
5817 } catch (RemoteException e) {
5818 Log.i(TAG, "Observer no longer exists.");
5819 }
5820 } //end if observer
5821 } //end run
5822 });
5823 }
5824
5825 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5826 if (packageName == null) {
5827 Log.w(TAG, "Attempt to get size of null packageName.");
5828 return false;
5829 }
5830 PackageParser.Package p;
5831 boolean dataOnly = false;
5832 synchronized (mPackages) {
5833 p = mPackages.get(packageName);
5834 if(p == null) {
5835 dataOnly = true;
5836 PackageSetting ps = mSettings.mPackages.get(packageName);
5837 if((ps == null) || (ps.pkg == null)) {
5838 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5839 return false;
5840 }
5841 p = ps.pkg;
5842 }
5843 }
5844 String publicSrcDir = null;
5845 if(!dataOnly) {
5846 final ApplicationInfo applicationInfo = p.applicationInfo;
5847 if (applicationInfo == null) {
5848 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5849 return false;
5850 }
5851 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
5852 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005853 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854 if (mInstaller != null) {
5855 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08005856 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 if (res < 0) {
5858 return false;
5859 } else {
5860 return true;
5861 }
5862 }
5863 return true;
5864 }
5865
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 public void addPackageToPreferred(String packageName) {
5868 mContext.enforceCallingOrSelfPermission(
5869 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005870 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 }
5872
5873 public void removePackageFromPreferred(String packageName) {
5874 mContext.enforceCallingOrSelfPermission(
5875 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005876 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 }
5878
5879 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005880 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 }
5882
5883 public void addPreferredActivity(IntentFilter filter, int match,
5884 ComponentName[] set, ComponentName activity) {
5885 mContext.enforceCallingOrSelfPermission(
5886 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5887
5888 synchronized (mPackages) {
5889 Log.i(TAG, "Adding preferred activity " + activity + ":");
5890 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5891 mSettings.mPreferredActivities.addFilter(
5892 new PreferredActivity(filter, match, set, activity));
5893 mSettings.writeLP();
5894 }
5895 }
5896
Satish Sampath8dbe6122009-06-02 23:35:54 +01005897 public void replacePreferredActivity(IntentFilter filter, int match,
5898 ComponentName[] set, ComponentName activity) {
5899 mContext.enforceCallingOrSelfPermission(
5900 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5901 if (filter.countActions() != 1) {
5902 throw new IllegalArgumentException(
5903 "replacePreferredActivity expects filter to have only 1 action.");
5904 }
5905 if (filter.countCategories() != 1) {
5906 throw new IllegalArgumentException(
5907 "replacePreferredActivity expects filter to have only 1 category.");
5908 }
5909 if (filter.countDataAuthorities() != 0
5910 || filter.countDataPaths() != 0
5911 || filter.countDataSchemes() != 0
5912 || filter.countDataTypes() != 0) {
5913 throw new IllegalArgumentException(
5914 "replacePreferredActivity expects filter to have no data authorities, " +
5915 "paths, schemes or types.");
5916 }
5917 synchronized (mPackages) {
5918 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5919 String action = filter.getAction(0);
5920 String category = filter.getCategory(0);
5921 while (it.hasNext()) {
5922 PreferredActivity pa = it.next();
5923 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5924 it.remove();
5925 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5926 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5927 }
5928 }
5929 addPreferredActivity(filter, match, set, activity);
5930 }
5931 }
5932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005933 public void clearPackagePreferredActivities(String packageName) {
5934 mContext.enforceCallingOrSelfPermission(
5935 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5936
5937 synchronized (mPackages) {
5938 if (clearPackagePreferredActivitiesLP(packageName)) {
5939 mSettings.writeLP();
5940 }
5941 }
5942 }
5943
5944 boolean clearPackagePreferredActivitiesLP(String packageName) {
5945 boolean changed = false;
5946 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5947 while (it.hasNext()) {
5948 PreferredActivity pa = it.next();
5949 if (pa.mActivity.getPackageName().equals(packageName)) {
5950 it.remove();
5951 changed = true;
5952 }
5953 }
5954 return changed;
5955 }
5956
5957 public int getPreferredActivities(List<IntentFilter> outFilters,
5958 List<ComponentName> outActivities, String packageName) {
5959
5960 int num = 0;
5961 synchronized (mPackages) {
5962 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5963 while (it.hasNext()) {
5964 PreferredActivity pa = it.next();
5965 if (packageName == null
5966 || pa.mActivity.getPackageName().equals(packageName)) {
5967 if (outFilters != null) {
5968 outFilters.add(new IntentFilter(pa));
5969 }
5970 if (outActivities != null) {
5971 outActivities.add(pa.mActivity);
5972 }
5973 }
5974 }
5975 }
5976
5977 return num;
5978 }
5979
5980 public void setApplicationEnabledSetting(String appPackageName,
5981 int newState, int flags) {
5982 setEnabledSetting(appPackageName, null, newState, flags);
5983 }
5984
5985 public void setComponentEnabledSetting(ComponentName componentName,
5986 int newState, int flags) {
5987 setEnabledSetting(componentName.getPackageName(),
5988 componentName.getClassName(), newState, flags);
5989 }
5990
5991 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005992 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5994 || newState == COMPONENT_ENABLED_STATE_ENABLED
5995 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5996 throw new IllegalArgumentException("Invalid new component state: "
5997 + newState);
5998 }
5999 PackageSetting pkgSetting;
6000 final int uid = Binder.getCallingUid();
6001 final int permission = mContext.checkCallingPermission(
6002 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6003 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006004 boolean sendNow = false;
6005 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006006 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006008 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006010 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006012 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006014 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 }
6016 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006017 "Unknown component: " + packageName
6018 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 }
6020 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6021 throw new SecurityException(
6022 "Permission Denial: attempt to change component state from pid="
6023 + Binder.getCallingPid()
6024 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6025 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006026 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 // We're dealing with an application/package level state change
6028 pkgSetting.enabled = newState;
6029 } else {
6030 // We're dealing with a component level state change
6031 switch (newState) {
6032 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006033 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006034 break;
6035 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006036 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 break;
6038 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006039 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 break;
6041 default:
6042 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006043 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 }
6045 }
6046 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006047 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006048 components = mPendingBroadcasts.get(packageName);
6049 boolean newPackage = components == null;
6050 if (newPackage) {
6051 components = new ArrayList<String>();
6052 }
6053 if (!components.contains(componentName)) {
6054 components.add(componentName);
6055 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006056 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6057 sendNow = true;
6058 // Purge entry from pending broadcast list if another one exists already
6059 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006060 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006061 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006062 if (newPackage) {
6063 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006064 }
6065 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6066 // Schedule a message
6067 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6068 }
6069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006072 long callingId = Binder.clearCallingIdentity();
6073 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006074 if (sendNow) {
6075 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006076 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 } finally {
6079 Binder.restoreCallingIdentity(callingId);
6080 }
6081 }
6082
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006083 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006084 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6085 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6086 + " components=" + componentNames);
6087 Bundle extras = new Bundle(4);
6088 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6089 String nameList[] = new String[componentNames.size()];
6090 componentNames.toArray(nameList);
6091 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006092 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6093 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006094 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006095 }
6096
Jacek Surazski65e13172009-04-28 15:26:38 +02006097 public String getInstallerPackageName(String packageName) {
6098 synchronized (mPackages) {
6099 PackageSetting pkg = mSettings.mPackages.get(packageName);
6100 if (pkg == null) {
6101 throw new IllegalArgumentException("Unknown package: " + packageName);
6102 }
6103 return pkg.installerPackageName;
6104 }
6105 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 public int getApplicationEnabledSetting(String appPackageName) {
6108 synchronized (mPackages) {
6109 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6110 if (pkg == null) {
6111 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6112 }
6113 return pkg.enabled;
6114 }
6115 }
6116
6117 public int getComponentEnabledSetting(ComponentName componentName) {
6118 synchronized (mPackages) {
6119 final String packageNameStr = componentName.getPackageName();
6120 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6121 if (pkg == null) {
6122 throw new IllegalArgumentException("Unknown component: " + componentName);
6123 }
6124 final String classNameStr = componentName.getClassName();
6125 return pkg.currentEnabledStateLP(classNameStr);
6126 }
6127 }
6128
6129 public void enterSafeMode() {
6130 if (!mSystemReady) {
6131 mSafeMode = true;
6132 }
6133 }
6134
6135 public void systemReady() {
6136 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006137
6138 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006139 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006140 mContext.getContentResolver(),
6141 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006142 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006143 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006144 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 }
6147
6148 public boolean isSafeMode() {
6149 return mSafeMode;
6150 }
6151
6152 public boolean hasSystemUidErrors() {
6153 return mHasSystemUidErrors;
6154 }
6155
6156 static String arrayToString(int[] array) {
6157 StringBuffer buf = new StringBuffer(128);
6158 buf.append('[');
6159 if (array != null) {
6160 for (int i=0; i<array.length; i++) {
6161 if (i > 0) buf.append(", ");
6162 buf.append(array[i]);
6163 }
6164 }
6165 buf.append(']');
6166 return buf.toString();
6167 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 @Override
6170 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6171 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6172 != PackageManager.PERMISSION_GRANTED) {
6173 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6174 + Binder.getCallingPid()
6175 + ", uid=" + Binder.getCallingUid()
6176 + " without permission "
6177 + android.Manifest.permission.DUMP);
6178 return;
6179 }
6180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 synchronized (mPackages) {
6182 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006183 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 pw.println(" ");
6185 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006186 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 pw.println(" ");
6188 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006189 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 pw.println(" ");
6191 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006192 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 pw.println("Permissions:");
6195 {
6196 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006197 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6198 pw.print(Integer.toHexString(System.identityHashCode(p)));
6199 pw.println("):");
6200 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6201 pw.print(" uid="); pw.print(p.uid);
6202 pw.print(" gids="); pw.print(arrayToString(p.gids));
6203 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 }
6205 }
6206 pw.println(" ");
6207 pw.println("Packages:");
6208 {
6209 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006210 pw.print(" Package [");
6211 pw.print(ps.realName != null ? ps.realName : ps.name);
6212 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006213 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6214 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006215 if (ps.realName != null) {
6216 pw.print(" compat name="); pw.println(ps.name);
6217 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006218 pw.print(" userId="); pw.print(ps.userId);
6219 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6220 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6221 pw.print(" pkg="); pw.println(ps.pkg);
6222 pw.print(" codePath="); pw.println(ps.codePathString);
6223 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006225 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006226 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006227 pw.print(" supportsScreens=[");
6228 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006229 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006230 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006231 if (!first) pw.print(", ");
6232 first = false;
6233 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006234 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006235 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006236 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006237 if (!first) pw.print(", ");
6238 first = false;
6239 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006240 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006241 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006242 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006243 if (!first) pw.print(", ");
6244 first = false;
6245 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006246 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006247 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006248 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006249 if (!first) pw.print(", ");
6250 first = false;
6251 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006252 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006253 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006254 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6255 if (!first) pw.print(", ");
6256 first = false;
6257 pw.print("anyDensity");
6258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006260 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006261 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6262 pw.print(" signatures="); pw.println(ps.signatures);
6263 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6264 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6265 pw.print(" installStatus="); pw.print(ps.installStatus);
6266 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 if (ps.disabledComponents.size() > 0) {
6268 pw.println(" disabledComponents:");
6269 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006270 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 }
6272 }
6273 if (ps.enabledComponents.size() > 0) {
6274 pw.println(" enabledComponents:");
6275 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006276 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 }
6278 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006279 if (ps.grantedPermissions.size() > 0) {
6280 pw.println(" grantedPermissions:");
6281 for (String s : ps.grantedPermissions) {
6282 pw.print(" "); pw.println(s);
6283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006285 if (ps.loadedPermissions.size() > 0) {
6286 pw.println(" loadedPermissions:");
6287 for (String s : ps.loadedPermissions) {
6288 pw.print(" "); pw.println(s);
6289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 }
6291 }
6292 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006293 if (mSettings.mRenamedPackages.size() > 0) {
6294 pw.println(" ");
6295 pw.println("Renamed packages:");
6296 for (HashMap.Entry<String, String> e
6297 : mSettings.mRenamedPackages.entrySet()) {
6298 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6299 pw.println(e.getValue());
6300 }
6301 }
6302 if (mSettings.mDisabledSysPackages.size() > 0) {
6303 pw.println(" ");
6304 pw.println("Hidden system packages:");
6305 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6306 pw.print(" Package [");
6307 pw.print(ps.realName != null ? ps.realName : ps.name);
6308 pw.print("] (");
6309 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6310 pw.println("):");
6311 if (ps.realName != null) {
6312 pw.print(" compat name="); pw.println(ps.name);
6313 }
6314 pw.print(" userId="); pw.println(ps.userId);
6315 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6316 pw.print(" codePath="); pw.println(ps.codePathString);
6317 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6318 }
6319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 pw.println(" ");
6321 pw.println("Shared Users:");
6322 {
6323 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006324 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6325 pw.print(Integer.toHexString(System.identityHashCode(su)));
6326 pw.println("):");
6327 pw.print(" userId="); pw.print(su.userId);
6328 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 pw.println(" grantedPermissions:");
6330 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006331 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 }
6333 pw.println(" loadedPermissions:");
6334 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006335 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 }
6337 }
6338 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 pw.println(" ");
6341 pw.println("Settings parse messages:");
6342 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006343
6344 pw.println(" ");
6345 pw.println("Package warning messages:");
6346 File fname = getSettingsProblemFile();
6347 FileInputStream in;
6348 try {
6349 in = new FileInputStream(fname);
6350 int avail = in.available();
6351 byte[] data = new byte[avail];
6352 in.read(data);
6353 pw.println(new String(data));
6354 } catch (FileNotFoundException e) {
6355 } catch (IOException e) {
6356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006358
6359 synchronized (mProviders) {
6360 pw.println(" ");
6361 pw.println("Registered ContentProviders:");
6362 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006363 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006364 pw.println(p.toString());
6365 }
6366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 }
6368
6369 static final class BasePermission {
6370 final static int TYPE_NORMAL = 0;
6371 final static int TYPE_BUILTIN = 1;
6372 final static int TYPE_DYNAMIC = 2;
6373
6374 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006375 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 final int type;
6377 PackageParser.Permission perm;
6378 PermissionInfo pendingInfo;
6379 int uid;
6380 int[] gids;
6381
6382 BasePermission(String _name, String _sourcePackage, int _type) {
6383 name = _name;
6384 sourcePackage = _sourcePackage;
6385 type = _type;
6386 }
6387 }
6388
6389 static class PackageSignatures {
6390 private Signature[] mSignatures;
6391
6392 PackageSignatures(Signature[] sigs) {
6393 assignSignatures(sigs);
6394 }
6395
6396 PackageSignatures() {
6397 }
6398
6399 void writeXml(XmlSerializer serializer, String tagName,
6400 ArrayList<Signature> pastSignatures) throws IOException {
6401 if (mSignatures == null) {
6402 return;
6403 }
6404 serializer.startTag(null, tagName);
6405 serializer.attribute(null, "count",
6406 Integer.toString(mSignatures.length));
6407 for (int i=0; i<mSignatures.length; i++) {
6408 serializer.startTag(null, "cert");
6409 final Signature sig = mSignatures[i];
6410 final int sigHash = sig.hashCode();
6411 final int numPast = pastSignatures.size();
6412 int j;
6413 for (j=0; j<numPast; j++) {
6414 Signature pastSig = pastSignatures.get(j);
6415 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6416 serializer.attribute(null, "index", Integer.toString(j));
6417 break;
6418 }
6419 }
6420 if (j >= numPast) {
6421 pastSignatures.add(sig);
6422 serializer.attribute(null, "index", Integer.toString(numPast));
6423 serializer.attribute(null, "key", sig.toCharsString());
6424 }
6425 serializer.endTag(null, "cert");
6426 }
6427 serializer.endTag(null, tagName);
6428 }
6429
6430 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6431 throws IOException, XmlPullParserException {
6432 String countStr = parser.getAttributeValue(null, "count");
6433 if (countStr == null) {
6434 reportSettingsProblem(Log.WARN,
6435 "Error in package manager settings: <signatures> has"
6436 + " no count at " + parser.getPositionDescription());
6437 XmlUtils.skipCurrentTag(parser);
6438 }
6439 final int count = Integer.parseInt(countStr);
6440 mSignatures = new Signature[count];
6441 int pos = 0;
6442
6443 int outerDepth = parser.getDepth();
6444 int type;
6445 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6446 && (type != XmlPullParser.END_TAG
6447 || parser.getDepth() > outerDepth)) {
6448 if (type == XmlPullParser.END_TAG
6449 || type == XmlPullParser.TEXT) {
6450 continue;
6451 }
6452
6453 String tagName = parser.getName();
6454 if (tagName.equals("cert")) {
6455 if (pos < count) {
6456 String index = parser.getAttributeValue(null, "index");
6457 if (index != null) {
6458 try {
6459 int idx = Integer.parseInt(index);
6460 String key = parser.getAttributeValue(null, "key");
6461 if (key == null) {
6462 if (idx >= 0 && idx < pastSignatures.size()) {
6463 Signature sig = pastSignatures.get(idx);
6464 if (sig != null) {
6465 mSignatures[pos] = pastSignatures.get(idx);
6466 pos++;
6467 } else {
6468 reportSettingsProblem(Log.WARN,
6469 "Error in package manager settings: <cert> "
6470 + "index " + index + " is not defined at "
6471 + parser.getPositionDescription());
6472 }
6473 } else {
6474 reportSettingsProblem(Log.WARN,
6475 "Error in package manager settings: <cert> "
6476 + "index " + index + " is out of bounds at "
6477 + parser.getPositionDescription());
6478 }
6479 } else {
6480 while (pastSignatures.size() <= idx) {
6481 pastSignatures.add(null);
6482 }
6483 Signature sig = new Signature(key);
6484 pastSignatures.set(idx, sig);
6485 mSignatures[pos] = sig;
6486 pos++;
6487 }
6488 } catch (NumberFormatException e) {
6489 reportSettingsProblem(Log.WARN,
6490 "Error in package manager settings: <cert> "
6491 + "index " + index + " is not a number at "
6492 + parser.getPositionDescription());
6493 }
6494 } else {
6495 reportSettingsProblem(Log.WARN,
6496 "Error in package manager settings: <cert> has"
6497 + " no index at " + parser.getPositionDescription());
6498 }
6499 } else {
6500 reportSettingsProblem(Log.WARN,
6501 "Error in package manager settings: too "
6502 + "many <cert> tags, expected " + count
6503 + " at " + parser.getPositionDescription());
6504 }
6505 } else {
6506 reportSettingsProblem(Log.WARN,
6507 "Unknown element under <cert>: "
6508 + parser.getName());
6509 }
6510 XmlUtils.skipCurrentTag(parser);
6511 }
6512
6513 if (pos < count) {
6514 // Should never happen -- there is an error in the written
6515 // settings -- but if it does we don't want to generate
6516 // a bad array.
6517 Signature[] newSigs = new Signature[pos];
6518 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6519 mSignatures = newSigs;
6520 }
6521 }
6522
6523 /**
6524 * If any of the given 'sigs' is contained in the existing signatures,
6525 * then completely replace the current signatures with the ones in
6526 * 'sigs'. This is used for updating an existing package to a newly
6527 * installed version.
6528 */
6529 boolean updateSignatures(Signature[] sigs, boolean update) {
6530 if (mSignatures == null) {
6531 if (update) {
6532 assignSignatures(sigs);
6533 }
6534 return true;
6535 }
6536 if (sigs == null) {
6537 return false;
6538 }
6539
6540 for (int i=0; i<sigs.length; i++) {
6541 Signature sig = sigs[i];
6542 for (int j=0; j<mSignatures.length; j++) {
6543 if (mSignatures[j].equals(sig)) {
6544 if (update) {
6545 assignSignatures(sigs);
6546 }
6547 return true;
6548 }
6549 }
6550 }
6551 return false;
6552 }
6553
6554 /**
6555 * If any of the given 'sigs' is contained in the existing signatures,
6556 * then add in any new signatures found in 'sigs'. This is used for
6557 * including a new package into an existing shared user id.
6558 */
6559 boolean mergeSignatures(Signature[] sigs, boolean update) {
6560 if (mSignatures == null) {
6561 if (update) {
6562 assignSignatures(sigs);
6563 }
6564 return true;
6565 }
6566 if (sigs == null) {
6567 return false;
6568 }
6569
6570 Signature[] added = null;
6571 int addedCount = 0;
6572 boolean haveMatch = false;
6573 for (int i=0; i<sigs.length; i++) {
6574 Signature sig = sigs[i];
6575 boolean found = false;
6576 for (int j=0; j<mSignatures.length; j++) {
6577 if (mSignatures[j].equals(sig)) {
6578 found = true;
6579 haveMatch = true;
6580 break;
6581 }
6582 }
6583
6584 if (!found) {
6585 if (added == null) {
6586 added = new Signature[sigs.length];
6587 }
6588 added[i] = sig;
6589 addedCount++;
6590 }
6591 }
6592
6593 if (!haveMatch) {
6594 // Nothing matched -- reject the new signatures.
6595 return false;
6596 }
6597 if (added == null) {
6598 // Completely matched -- nothing else to do.
6599 return true;
6600 }
6601
6602 // Add additional signatures in.
6603 if (update) {
6604 Signature[] total = new Signature[addedCount+mSignatures.length];
6605 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6606 int j = mSignatures.length;
6607 for (int i=0; i<added.length; i++) {
6608 if (added[i] != null) {
6609 total[j] = added[i];
6610 j++;
6611 }
6612 }
6613 mSignatures = total;
6614 }
6615 return true;
6616 }
6617
6618 private void assignSignatures(Signature[] sigs) {
6619 if (sigs == null) {
6620 mSignatures = null;
6621 return;
6622 }
6623 mSignatures = new Signature[sigs.length];
6624 for (int i=0; i<sigs.length; i++) {
6625 mSignatures[i] = sigs[i];
6626 }
6627 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 @Override
6630 public String toString() {
6631 StringBuffer buf = new StringBuffer(128);
6632 buf.append("PackageSignatures{");
6633 buf.append(Integer.toHexString(System.identityHashCode(this)));
6634 buf.append(" [");
6635 if (mSignatures != null) {
6636 for (int i=0; i<mSignatures.length; i++) {
6637 if (i > 0) buf.append(", ");
6638 buf.append(Integer.toHexString(
6639 System.identityHashCode(mSignatures[i])));
6640 }
6641 }
6642 buf.append("]}");
6643 return buf.toString();
6644 }
6645 }
6646
6647 static class PreferredActivity extends IntentFilter {
6648 final int mMatch;
6649 final String[] mSetPackages;
6650 final String[] mSetClasses;
6651 final String[] mSetComponents;
6652 final ComponentName mActivity;
6653 final String mShortActivity;
6654 String mParseError;
6655
6656 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6657 ComponentName activity) {
6658 super(filter);
6659 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6660 mActivity = activity;
6661 mShortActivity = activity.flattenToShortString();
6662 mParseError = null;
6663 if (set != null) {
6664 final int N = set.length;
6665 String[] myPackages = new String[N];
6666 String[] myClasses = new String[N];
6667 String[] myComponents = new String[N];
6668 for (int i=0; i<N; i++) {
6669 ComponentName cn = set[i];
6670 if (cn == null) {
6671 mSetPackages = null;
6672 mSetClasses = null;
6673 mSetComponents = null;
6674 return;
6675 }
6676 myPackages[i] = cn.getPackageName().intern();
6677 myClasses[i] = cn.getClassName().intern();
6678 myComponents[i] = cn.flattenToShortString().intern();
6679 }
6680 mSetPackages = myPackages;
6681 mSetClasses = myClasses;
6682 mSetComponents = myComponents;
6683 } else {
6684 mSetPackages = null;
6685 mSetClasses = null;
6686 mSetComponents = null;
6687 }
6688 }
6689
6690 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6691 IOException {
6692 mShortActivity = parser.getAttributeValue(null, "name");
6693 mActivity = ComponentName.unflattenFromString(mShortActivity);
6694 if (mActivity == null) {
6695 mParseError = "Bad activity name " + mShortActivity;
6696 }
6697 String matchStr = parser.getAttributeValue(null, "match");
6698 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6699 String setCountStr = parser.getAttributeValue(null, "set");
6700 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6701
6702 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6703 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6704 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6705
6706 int setPos = 0;
6707
6708 int outerDepth = parser.getDepth();
6709 int type;
6710 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6711 && (type != XmlPullParser.END_TAG
6712 || parser.getDepth() > outerDepth)) {
6713 if (type == XmlPullParser.END_TAG
6714 || type == XmlPullParser.TEXT) {
6715 continue;
6716 }
6717
6718 String tagName = parser.getName();
6719 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6720 // + parser.getDepth() + " tag=" + tagName);
6721 if (tagName.equals("set")) {
6722 String name = parser.getAttributeValue(null, "name");
6723 if (name == null) {
6724 if (mParseError == null) {
6725 mParseError = "No name in set tag in preferred activity "
6726 + mShortActivity;
6727 }
6728 } else if (setPos >= setCount) {
6729 if (mParseError == null) {
6730 mParseError = "Too many set tags in preferred activity "
6731 + mShortActivity;
6732 }
6733 } else {
6734 ComponentName cn = ComponentName.unflattenFromString(name);
6735 if (cn == null) {
6736 if (mParseError == null) {
6737 mParseError = "Bad set name " + name + " in preferred activity "
6738 + mShortActivity;
6739 }
6740 } else {
6741 myPackages[setPos] = cn.getPackageName();
6742 myClasses[setPos] = cn.getClassName();
6743 myComponents[setPos] = name;
6744 setPos++;
6745 }
6746 }
6747 XmlUtils.skipCurrentTag(parser);
6748 } else if (tagName.equals("filter")) {
6749 //Log.i(TAG, "Starting to parse filter...");
6750 readFromXml(parser);
6751 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6752 // + parser.getDepth() + " tag=" + parser.getName());
6753 } else {
6754 reportSettingsProblem(Log.WARN,
6755 "Unknown element under <preferred-activities>: "
6756 + parser.getName());
6757 XmlUtils.skipCurrentTag(parser);
6758 }
6759 }
6760
6761 if (setPos != setCount) {
6762 if (mParseError == null) {
6763 mParseError = "Not enough set tags (expected " + setCount
6764 + " but found " + setPos + ") in " + mShortActivity;
6765 }
6766 }
6767
6768 mSetPackages = myPackages;
6769 mSetClasses = myClasses;
6770 mSetComponents = myComponents;
6771 }
6772
6773 public void writeToXml(XmlSerializer serializer) throws IOException {
6774 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6775 serializer.attribute(null, "name", mShortActivity);
6776 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6777 serializer.attribute(null, "set", Integer.toString(NS));
6778 for (int s=0; s<NS; s++) {
6779 serializer.startTag(null, "set");
6780 serializer.attribute(null, "name", mSetComponents[s]);
6781 serializer.endTag(null, "set");
6782 }
6783 serializer.startTag(null, "filter");
6784 super.writeToXml(serializer);
6785 serializer.endTag(null, "filter");
6786 }
6787
6788 boolean sameSet(List<ResolveInfo> query, int priority) {
6789 if (mSetPackages == null) return false;
6790 final int NQ = query.size();
6791 final int NS = mSetPackages.length;
6792 int numMatch = 0;
6793 for (int i=0; i<NQ; i++) {
6794 ResolveInfo ri = query.get(i);
6795 if (ri.priority != priority) continue;
6796 ActivityInfo ai = ri.activityInfo;
6797 boolean good = false;
6798 for (int j=0; j<NS; j++) {
6799 if (mSetPackages[j].equals(ai.packageName)
6800 && mSetClasses[j].equals(ai.name)) {
6801 numMatch++;
6802 good = true;
6803 break;
6804 }
6805 }
6806 if (!good) return false;
6807 }
6808 return numMatch == NS;
6809 }
6810 }
6811
6812 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006813 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 HashSet<String> grantedPermissions = new HashSet<String>();
6816 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006821 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
6822 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6823 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006824 }
6825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006827 /**
6828 * Settings base class for pending and resolved classes.
6829 */
6830 static class PackageSettingBase extends GrantedPermissions {
6831 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006832 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006833 File codePath;
6834 String codePathString;
6835 File resourcePath;
6836 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 private long timeStamp;
6838 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006839 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006841 boolean uidError;
6842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006843 PackageSignatures signatures = new PackageSignatures();
6844
6845 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 /* Explicitly disabled components */
6848 HashSet<String> disabledComponents = new HashSet<String>(0);
6849 /* Explicitly enabled components */
6850 HashSet<String> enabledComponents = new HashSet<String>(0);
6851 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6852 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006853
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006854 PackageSettingBase origPackage;
6855
Jacek Surazski65e13172009-04-28 15:26:38 +02006856 /* package name of the app that installed this package */
6857 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006859 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006860 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 super(pkgFlags);
6862 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006863 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006864 init(codePath, resourcePath, pVersionCode);
6865 }
6866
6867 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 this.codePath = codePath;
6869 this.codePathString = codePath.toString();
6870 this.resourcePath = resourcePath;
6871 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006872 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006873 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006874
Jacek Surazski65e13172009-04-28 15:26:38 +02006875 public void setInstallerPackageName(String packageName) {
6876 installerPackageName = packageName;
6877 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006878
Jacek Surazski65e13172009-04-28 15:26:38 +02006879 String getInstallerPackageName() {
6880 return installerPackageName;
6881 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006883 public void setInstallStatus(int newStatus) {
6884 installStatus = newStatus;
6885 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006887 public int getInstallStatus() {
6888 return installStatus;
6889 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006891 public void setTimeStamp(long newStamp) {
6892 if (newStamp != timeStamp) {
6893 timeStamp = newStamp;
6894 timeStampString = Long.toString(newStamp);
6895 }
6896 }
6897
6898 public void setTimeStamp(long newStamp, String newStampStr) {
6899 timeStamp = newStamp;
6900 timeStampString = newStampStr;
6901 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 public long getTimeStamp() {
6904 return timeStamp;
6905 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006907 public String getTimeStampStr() {
6908 return timeStampString;
6909 }
6910
6911 public void copyFrom(PackageSettingBase base) {
6912 grantedPermissions = base.grantedPermissions;
6913 gids = base.gids;
6914 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006916 timeStamp = base.timeStamp;
6917 timeStampString = base.timeStampString;
6918 signatures = base.signatures;
6919 permissionsFixed = base.permissionsFixed;
6920 disabledComponents = base.disabledComponents;
6921 enabledComponents = base.enabledComponents;
6922 enabled = base.enabled;
6923 installStatus = base.installStatus;
6924 }
6925
6926 void enableComponentLP(String componentClassName) {
6927 disabledComponents.remove(componentClassName);
6928 enabledComponents.add(componentClassName);
6929 }
6930
6931 void disableComponentLP(String componentClassName) {
6932 enabledComponents.remove(componentClassName);
6933 disabledComponents.add(componentClassName);
6934 }
6935
6936 void restoreComponentLP(String componentClassName) {
6937 enabledComponents.remove(componentClassName);
6938 disabledComponents.remove(componentClassName);
6939 }
6940
6941 int currentEnabledStateLP(String componentName) {
6942 if (enabledComponents.contains(componentName)) {
6943 return COMPONENT_ENABLED_STATE_ENABLED;
6944 } else if (disabledComponents.contains(componentName)) {
6945 return COMPONENT_ENABLED_STATE_DISABLED;
6946 } else {
6947 return COMPONENT_ENABLED_STATE_DEFAULT;
6948 }
6949 }
6950 }
6951
6952 /**
6953 * Settings data for a particular package we know about.
6954 */
6955 static final class PackageSetting extends PackageSettingBase {
6956 int userId;
6957 PackageParser.Package pkg;
6958 SharedUserSetting sharedUser;
6959
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006960 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006961 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006962 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006963 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 @Override
6966 public String toString() {
6967 return "PackageSetting{"
6968 + Integer.toHexString(System.identityHashCode(this))
6969 + " " + name + "/" + userId + "}";
6970 }
6971 }
6972
6973 /**
6974 * Settings data for a particular shared user ID we know about.
6975 */
6976 static final class SharedUserSetting extends GrantedPermissions {
6977 final String name;
6978 int userId;
6979 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6980 final PackageSignatures signatures = new PackageSignatures();
6981
6982 SharedUserSetting(String _name, int _pkgFlags) {
6983 super(_pkgFlags);
6984 name = _name;
6985 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006987 @Override
6988 public String toString() {
6989 return "SharedUserSetting{"
6990 + Integer.toHexString(System.identityHashCode(this))
6991 + " " + name + "/" + userId + "}";
6992 }
6993 }
6994
6995 /**
6996 * Holds information about dynamic settings.
6997 */
6998 private static final class Settings {
6999 private final File mSettingsFilename;
7000 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007001 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007002 private final HashMap<String, PackageSetting> mPackages =
7003 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007004 // List of replaced system applications
7005 final HashMap<String, PackageSetting> mDisabledSysPackages =
7006 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007008 // The user's preferred activities associated with particular intent
7009 // filters.
7010 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7011 new IntentResolver<PreferredActivity, PreferredActivity>() {
7012 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007013 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007015 out.print(prefix); out.print(
7016 Integer.toHexString(System.identityHashCode(filter)));
7017 out.print(' ');
7018 out.print(filter.mActivity.flattenToShortString());
7019 out.print(" match=0x");
7020 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007022 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007023 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007024 out.print(prefix); out.print(" ");
7025 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007026 }
7027 }
7028 }
7029 };
7030 private final HashMap<String, SharedUserSetting> mSharedUsers =
7031 new HashMap<String, SharedUserSetting>();
7032 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7033 private final SparseArray<Object> mOtherUserIds =
7034 new SparseArray<Object>();
7035
7036 // For reading/writing settings file.
7037 private final ArrayList<Signature> mPastSignatures =
7038 new ArrayList<Signature>();
7039
7040 // Mapping from permission names to info about them.
7041 final HashMap<String, BasePermission> mPermissions =
7042 new HashMap<String, BasePermission>();
7043
7044 // Mapping from permission tree names to info about them.
7045 final HashMap<String, BasePermission> mPermissionTrees =
7046 new HashMap<String, BasePermission>();
7047
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007048 // Packages that have been uninstalled and still need their external
7049 // storage data deleted.
7050 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7051
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007052 // Packages that have been renamed since they were first installed.
7053 // Keys are the new names of the packages, values are the original
7054 // names. The packages appear everwhere else under their original
7055 // names.
7056 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007058 private final StringBuilder mReadMessages = new StringBuilder();
7059
7060 private static final class PendingPackage extends PackageSettingBase {
7061 final int sharedId;
7062
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007063 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007064 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007065 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007066 this.sharedId = sharedId;
7067 }
7068 }
7069 private final ArrayList<PendingPackage> mPendingPackages
7070 = new ArrayList<PendingPackage>();
7071
7072 Settings() {
7073 File dataDir = Environment.getDataDirectory();
7074 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007075 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7076 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007077 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007078 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007079 FileUtils.setPermissions(systemDir.toString(),
7080 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7081 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7082 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007083 FileUtils.setPermissions(systemSecureDir.toString(),
7084 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7085 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7086 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 mSettingsFilename = new File(systemDir, "packages.xml");
7088 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007089 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007090 }
7091
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007092 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007093 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 int pkgFlags, boolean create, boolean add) {
7095 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007096 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007097 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007098 return p;
7099 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007100
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007101 PackageSetting peekPackageLP(String name) {
7102 return mPackages.get(name);
7103 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007104 PackageSetting p = mPackages.get(name);
7105 if (p != null && p.codePath.getPath().equals(codePath)) {
7106 return p;
7107 }
7108 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007109 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007112 void setInstallStatus(String pkgName, int status) {
7113 PackageSetting p = mPackages.get(pkgName);
7114 if(p != null) {
7115 if(p.getInstallStatus() != status) {
7116 p.setInstallStatus(status);
7117 }
7118 }
7119 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007120
Jacek Surazski65e13172009-04-28 15:26:38 +02007121 void setInstallerPackageName(String pkgName,
7122 String installerPkgName) {
7123 PackageSetting p = mPackages.get(pkgName);
7124 if(p != null) {
7125 p.setInstallerPackageName(installerPkgName);
7126 }
7127 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007128
Jacek Surazski65e13172009-04-28 15:26:38 +02007129 String getInstallerPackageName(String pkgName) {
7130 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007131 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007132 }
7133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 int getInstallStatus(String pkgName) {
7135 PackageSetting p = mPackages.get(pkgName);
7136 if(p != null) {
7137 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007139 return -1;
7140 }
7141
7142 SharedUserSetting getSharedUserLP(String name,
7143 int pkgFlags, boolean create) {
7144 SharedUserSetting s = mSharedUsers.get(name);
7145 if (s == null) {
7146 if (!create) {
7147 return null;
7148 }
7149 s = new SharedUserSetting(name, pkgFlags);
7150 if (MULTIPLE_APPLICATION_UIDS) {
7151 s.userId = newUserIdLP(s);
7152 } else {
7153 s.userId = FIRST_APPLICATION_UID;
7154 }
7155 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7156 // < 0 means we couldn't assign a userid; fall out and return
7157 // s, which is currently null
7158 if (s.userId >= 0) {
7159 mSharedUsers.put(name, s);
7160 }
7161 }
7162
7163 return s;
7164 }
7165
7166 int disableSystemPackageLP(String name) {
7167 PackageSetting p = mPackages.get(name);
7168 if(p == null) {
7169 Log.w(TAG, "Package:"+name+" is not an installed package");
7170 return -1;
7171 }
7172 PackageSetting dp = mDisabledSysPackages.get(name);
7173 // always make sure the system package code and resource paths dont change
7174 if(dp == null) {
7175 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7176 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7177 }
7178 mDisabledSysPackages.put(name, p);
7179 }
7180 return removePackageLP(name);
7181 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007183 PackageSetting enableSystemPackageLP(String name) {
7184 PackageSetting p = mDisabledSysPackages.get(name);
7185 if(p == null) {
7186 Log.w(TAG, "Package:"+name+" is not disabled");
7187 return null;
7188 }
7189 // Reset flag in ApplicationInfo object
7190 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7191 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7192 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007193 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007194 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007195 mDisabledSysPackages.remove(name);
7196 return ret;
7197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007198
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007199 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007200 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007201 PackageSetting p = mPackages.get(name);
7202 if (p != null) {
7203 if (p.userId == uid) {
7204 return p;
7205 }
7206 reportSettingsProblem(Log.ERROR,
7207 "Adding duplicate package, keeping first: " + name);
7208 return null;
7209 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007210 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 p.userId = uid;
7212 if (addUserIdLP(uid, p, name)) {
7213 mPackages.put(name, p);
7214 return p;
7215 }
7216 return null;
7217 }
7218
7219 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7220 SharedUserSetting s = mSharedUsers.get(name);
7221 if (s != null) {
7222 if (s.userId == uid) {
7223 return s;
7224 }
7225 reportSettingsProblem(Log.ERROR,
7226 "Adding duplicate shared user, keeping first: " + name);
7227 return null;
7228 }
7229 s = new SharedUserSetting(name, pkgFlags);
7230 s.userId = uid;
7231 if (addUserIdLP(uid, s, name)) {
7232 mSharedUsers.put(name, s);
7233 return s;
7234 }
7235 return null;
7236 }
7237
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007238 // Transfer ownership of permissions from one package to another.
7239 private void transferPermissions(String origPkg, String newPkg) {
7240 // Transfer ownership of permissions to the new package.
7241 for (int i=0; i<2; i++) {
7242 HashMap<String, BasePermission> permissions =
7243 i == 0 ? mPermissionTrees : mPermissions;
7244 for (BasePermission bp : permissions.values()) {
7245 if (origPkg.equals(bp.sourcePackage)) {
7246 if (DEBUG_UPGRADE) Log.v(TAG,
7247 "Moving permission " + bp.name
7248 + " from pkg " + bp.sourcePackage
7249 + " to " + newPkg);
7250 bp.sourcePackage = newPkg;
7251 bp.perm = null;
7252 if (bp.pendingInfo != null) {
7253 bp.sourcePackage = newPkg;
7254 }
7255 bp.uid = 0;
7256 bp.gids = null;
7257 }
7258 }
7259 }
7260 }
7261
7262 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007263 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007264 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 PackageSetting p = mPackages.get(name);
7266 if (p != null) {
7267 if (!p.codePath.equals(codePath)) {
7268 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007269 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007270 // This is an updated system app with versions in both system
7271 // and data partition. Just let the most recent version
7272 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007273 Log.w(TAG, "Trying to update system app code path from " +
7274 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007275 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007276 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07007277 reportSettingsProblem(Log.WARN,
7278 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007279 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007280 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007281 }
7282 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007283 reportSettingsProblem(Log.WARN,
7284 "Package " + name + " shared user changed from "
7285 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7286 + " to "
7287 + (sharedUser != null ? sharedUser.name : "<nothing>")
7288 + "; replacing with new");
7289 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007290 } else {
7291 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7292 // If what we are scanning is a system package, then
7293 // make it so, regardless of whether it was previously
7294 // installed only in the data partition.
7295 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007297 }
7298 }
7299 if (p == null) {
7300 // Create a new PackageSettings entry. this can end up here because
7301 // of code path mismatch or user id mismatch of an updated system partition
7302 if (!create) {
7303 return null;
7304 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007305 if (origPackage != null) {
7306 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007307 p = new PackageSetting(origPackage.name, name, codePath,
7308 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007309 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7310 + " is adopting original package " + origPackage.name);
7311 p.copyFrom(origPackage);
7312 p.sharedUser = origPackage.sharedUser;
7313 p.userId = origPackage.userId;
7314 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007315 mRenamedPackages.put(name, origPackage.name);
7316 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007317 // Update new package state.
7318 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007319 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007320 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007321 p.setTimeStamp(codePath.lastModified());
7322 p.sharedUser = sharedUser;
7323 if (sharedUser != null) {
7324 p.userId = sharedUser.userId;
7325 } else if (MULTIPLE_APPLICATION_UIDS) {
7326 // Clone the setting here for disabled system packages
7327 PackageSetting dis = mDisabledSysPackages.get(name);
7328 if (dis != null) {
7329 // For disabled packages a new setting is created
7330 // from the existing user id. This still has to be
7331 // added to list of user id's
7332 // Copy signatures from previous setting
7333 if (dis.signatures.mSignatures != null) {
7334 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7335 }
7336 p.userId = dis.userId;
7337 // Clone permissions
7338 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7339 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7340 // Clone component info
7341 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7342 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7343 // Add new setting to list of user ids
7344 addUserIdLP(p.userId, p, name);
7345 } else {
7346 // Assign new user id
7347 p.userId = newUserIdLP(p);
7348 }
7349 } else {
7350 p.userId = FIRST_APPLICATION_UID;
7351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352 }
7353 if (p.userId < 0) {
7354 reportSettingsProblem(Log.WARN,
7355 "Package " + name + " could not be assigned a valid uid");
7356 return null;
7357 }
7358 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007359 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007361 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007362 }
7363 }
7364 return p;
7365 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007366
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007367 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007368 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007369 String codePath = pkg.applicationInfo.sourceDir;
7370 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007371 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007372 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007373 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007374 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007375 p.codePath = new File(codePath);
7376 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007377 }
7378 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007379 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007380 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007381 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007382 p.resourcePath = new File(resourcePath);
7383 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007384 }
7385 // Update version code if needed
7386 if (pkg.mVersionCode != p.versionCode) {
7387 p.versionCode = pkg.mVersionCode;
7388 }
7389 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7390 }
7391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 // Utility method that adds a PackageSetting to mPackages and
7393 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007394 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395 SharedUserSetting sharedUser) {
7396 mPackages.put(name, p);
7397 if (sharedUser != null) {
7398 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7399 reportSettingsProblem(Log.ERROR,
7400 "Package " + p.name + " was user "
7401 + p.sharedUser + " but is now " + sharedUser
7402 + "; I am not changing its files so it will probably fail!");
7403 p.sharedUser.packages.remove(p);
7404 } else if (p.userId != sharedUser.userId) {
7405 reportSettingsProblem(Log.ERROR,
7406 "Package " + p.name + " was user id " + p.userId
7407 + " but is now user " + sharedUser
7408 + " with id " + sharedUser.userId
7409 + "; I am not changing its files so it will probably fail!");
7410 }
7411
7412 sharedUser.packages.add(p);
7413 p.sharedUser = sharedUser;
7414 p.userId = sharedUser.userId;
7415 }
7416 }
7417
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007418 /*
7419 * Update the shared user setting when a package using
7420 * specifying the shared user id is removed. The gids
7421 * associated with each permission of the deleted package
7422 * are removed from the shared user's gid list only if its
7423 * not in use by other permissions of packages in the
7424 * shared user setting.
7425 */
7426 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007427 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7428 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7429 return;
7430 }
7431 // No sharedUserId
7432 if (deletedPs.sharedUser == null) {
7433 return;
7434 }
7435 SharedUserSetting sus = deletedPs.sharedUser;
7436 // Update permissions
7437 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7438 boolean used = false;
7439 if (!sus.grantedPermissions.contains (eachPerm)) {
7440 continue;
7441 }
7442 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007443 if (pkg.pkg != null &&
7444 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7445 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007446 used = true;
7447 break;
7448 }
7449 }
7450 if (!used) {
7451 // can safely delete this permission from list
7452 sus.grantedPermissions.remove(eachPerm);
7453 sus.loadedPermissions.remove(eachPerm);
7454 }
7455 }
7456 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007457 int newGids[] = globalGids;
7458 for (String eachPerm : sus.grantedPermissions) {
7459 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007460 if (bp != null) {
7461 newGids = appendInts(newGids, bp.gids);
7462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007463 }
7464 sus.gids = newGids;
7465 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 private int removePackageLP(String name) {
7468 PackageSetting p = mPackages.get(name);
7469 if (p != null) {
7470 mPackages.remove(name);
7471 if (p.sharedUser != null) {
7472 p.sharedUser.packages.remove(p);
7473 if (p.sharedUser.packages.size() == 0) {
7474 mSharedUsers.remove(p.sharedUser.name);
7475 removeUserIdLP(p.sharedUser.userId);
7476 return p.sharedUser.userId;
7477 }
7478 } else {
7479 removeUserIdLP(p.userId);
7480 return p.userId;
7481 }
7482 }
7483 return -1;
7484 }
7485
7486 private boolean addUserIdLP(int uid, Object obj, Object name) {
7487 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7488 return false;
7489 }
7490
7491 if (uid >= FIRST_APPLICATION_UID) {
7492 int N = mUserIds.size();
7493 final int index = uid - FIRST_APPLICATION_UID;
7494 while (index >= N) {
7495 mUserIds.add(null);
7496 N++;
7497 }
7498 if (mUserIds.get(index) != null) {
7499 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007500 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007501 + " name=" + name);
7502 return false;
7503 }
7504 mUserIds.set(index, obj);
7505 } else {
7506 if (mOtherUserIds.get(uid) != null) {
7507 reportSettingsProblem(Log.ERROR,
7508 "Adding duplicate shared id: " + uid
7509 + " name=" + name);
7510 return false;
7511 }
7512 mOtherUserIds.put(uid, obj);
7513 }
7514 return true;
7515 }
7516
7517 public Object getUserIdLP(int uid) {
7518 if (uid >= FIRST_APPLICATION_UID) {
7519 int N = mUserIds.size();
7520 final int index = uid - FIRST_APPLICATION_UID;
7521 return index < N ? mUserIds.get(index) : null;
7522 } else {
7523 return mOtherUserIds.get(uid);
7524 }
7525 }
7526
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007527 private Set<String> findPackagesWithFlag(int flag) {
7528 Set<String> ret = new HashSet<String>();
7529 for (PackageSetting ps : mPackages.values()) {
7530 // Has to match atleast all the flag bits set on flag
7531 if ((ps.pkgFlags & flag) == flag) {
7532 ret.add(ps.name);
7533 }
7534 }
7535 return ret;
7536 }
7537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 private void removeUserIdLP(int uid) {
7539 if (uid >= FIRST_APPLICATION_UID) {
7540 int N = mUserIds.size();
7541 final int index = uid - FIRST_APPLICATION_UID;
7542 if (index < N) mUserIds.set(index, null);
7543 } else {
7544 mOtherUserIds.remove(uid);
7545 }
7546 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 void writeLP() {
7549 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7550
7551 // Keep the old settings around until we know the new ones have
7552 // been successfully written.
7553 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007554 // Presence of backup settings file indicates that we failed
7555 // to persist settings earlier. So preserve the older
7556 // backup for future reference since the current settings
7557 // might have been corrupted.
7558 if (!mBackupSettingsFilename.exists()) {
7559 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7560 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7561 return;
7562 }
7563 } else {
7564 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007566 }
7567
7568 mPastSignatures.clear();
7569
7570 try {
7571 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7572
7573 //XmlSerializer serializer = XmlUtils.serializerInstance();
7574 XmlSerializer serializer = new FastXmlSerializer();
7575 serializer.setOutput(str, "utf-8");
7576 serializer.startDocument(null, true);
7577 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7578
7579 serializer.startTag(null, "packages");
7580
7581 serializer.startTag(null, "permission-trees");
7582 for (BasePermission bp : mPermissionTrees.values()) {
7583 writePermission(serializer, bp);
7584 }
7585 serializer.endTag(null, "permission-trees");
7586
7587 serializer.startTag(null, "permissions");
7588 for (BasePermission bp : mPermissions.values()) {
7589 writePermission(serializer, bp);
7590 }
7591 serializer.endTag(null, "permissions");
7592
7593 for (PackageSetting pkg : mPackages.values()) {
7594 writePackage(serializer, pkg);
7595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007597 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7598 writeDisabledSysPackage(serializer, pkg);
7599 }
7600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 serializer.startTag(null, "preferred-activities");
7602 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7603 serializer.startTag(null, "item");
7604 pa.writeToXml(serializer);
7605 serializer.endTag(null, "item");
7606 }
7607 serializer.endTag(null, "preferred-activities");
7608
7609 for (SharedUserSetting usr : mSharedUsers.values()) {
7610 serializer.startTag(null, "shared-user");
7611 serializer.attribute(null, "name", usr.name);
7612 serializer.attribute(null, "userId",
7613 Integer.toString(usr.userId));
7614 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7615 serializer.startTag(null, "perms");
7616 for (String name : usr.grantedPermissions) {
7617 serializer.startTag(null, "item");
7618 serializer.attribute(null, "name", name);
7619 serializer.endTag(null, "item");
7620 }
7621 serializer.endTag(null, "perms");
7622 serializer.endTag(null, "shared-user");
7623 }
7624
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007625 if (mPackagesToBeCleaned.size() > 0) {
7626 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7627 serializer.startTag(null, "cleaning-package");
7628 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7629 serializer.endTag(null, "cleaning-package");
7630 }
7631 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007632
7633 if (mRenamedPackages.size() > 0) {
7634 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
7635 serializer.startTag(null, "renamed-package");
7636 serializer.attribute(null, "new", e.getKey());
7637 serializer.attribute(null, "old", e.getValue());
7638 serializer.endTag(null, "renamed-package");
7639 }
7640 }
7641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007642 serializer.endTag(null, "packages");
7643
7644 serializer.endDocument();
7645
7646 str.flush();
7647 str.close();
7648
7649 // New settings successfully written, old ones are no longer
7650 // needed.
7651 mBackupSettingsFilename.delete();
7652 FileUtils.setPermissions(mSettingsFilename.toString(),
7653 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7654 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7655 |FileUtils.S_IROTH,
7656 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007657
7658 // Write package list file now, use a JournaledFile.
7659 //
7660 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
7661 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
7662
7663 str = new FileOutputStream(journal.chooseForWrite());
7664 try {
7665 StringBuilder sb = new StringBuilder();
7666 for (PackageSetting pkg : mPackages.values()) {
7667 ApplicationInfo ai = pkg.pkg.applicationInfo;
7668 String dataPath = ai.dataDir;
7669 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7670
7671 // Avoid any application that has a space in its path
7672 // or that is handled by the system.
7673 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
7674 continue;
7675
7676 // we store on each line the following information for now:
7677 //
7678 // pkgName - package name
7679 // userId - application-specific user id
7680 // debugFlag - 0 or 1 if the package is debuggable.
7681 // dataPath - path to package's data path
7682 //
7683 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
7684 //
7685 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
7686 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
7687 // system/core/run-as/run-as.c
7688 //
7689 sb.setLength(0);
7690 sb.append(ai.packageName);
7691 sb.append(" ");
7692 sb.append((int)ai.uid);
7693 sb.append(isDebug ? " 1 " : " 0 ");
7694 sb.append(dataPath);
7695 sb.append("\n");
7696 str.write(sb.toString().getBytes());
7697 }
7698 str.flush();
7699 str.close();
7700 journal.commit();
7701 }
7702 catch (Exception e) {
7703 journal.rollback();
7704 }
7705
7706 FileUtils.setPermissions(mPackageListFilename.toString(),
7707 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7708 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7709 |FileUtils.S_IROTH,
7710 -1, -1);
7711
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007712 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007713
7714 } catch(XmlPullParserException e) {
7715 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 -08007716 } catch(java.io.IOException e) {
7717 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 -08007718 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007719 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007720 if (mSettingsFilename.exists()) {
7721 if (!mSettingsFilename.delete()) {
7722 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7723 }
7724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007725 //Debug.stopMethodTracing();
7726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007727
7728 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007729 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 serializer.startTag(null, "updated-package");
7731 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007732 if (pkg.realName != null) {
7733 serializer.attribute(null, "realName", pkg.realName);
7734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 serializer.attribute(null, "codePath", pkg.codePathString);
7736 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007737 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7739 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7740 }
7741 if (pkg.sharedUser == null) {
7742 serializer.attribute(null, "userId",
7743 Integer.toString(pkg.userId));
7744 } else {
7745 serializer.attribute(null, "sharedUserId",
7746 Integer.toString(pkg.userId));
7747 }
7748 serializer.startTag(null, "perms");
7749 if (pkg.sharedUser == null) {
7750 // If this is a shared user, the permissions will
7751 // be written there. We still need to write an
7752 // empty permissions list so permissionsFixed will
7753 // be set.
7754 for (final String name : pkg.grantedPermissions) {
7755 BasePermission bp = mPermissions.get(name);
7756 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7757 // We only need to write signature or system permissions but this wont
7758 // match the semantics of grantedPermissions. So write all permissions.
7759 serializer.startTag(null, "item");
7760 serializer.attribute(null, "name", name);
7761 serializer.endTag(null, "item");
7762 }
7763 }
7764 }
7765 serializer.endTag(null, "perms");
7766 serializer.endTag(null, "updated-package");
7767 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007768
7769 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007770 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 serializer.startTag(null, "package");
7772 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007773 if (pkg.realName != null) {
7774 serializer.attribute(null, "realName", pkg.realName);
7775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 serializer.attribute(null, "codePath", pkg.codePathString);
7777 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7778 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7779 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007780 serializer.attribute(null, "flags",
7781 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007782 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007783 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007784 if (pkg.sharedUser == null) {
7785 serializer.attribute(null, "userId",
7786 Integer.toString(pkg.userId));
7787 } else {
7788 serializer.attribute(null, "sharedUserId",
7789 Integer.toString(pkg.userId));
7790 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007791 if (pkg.uidError) {
7792 serializer.attribute(null, "uidError", "true");
7793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007794 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7795 serializer.attribute(null, "enabled",
7796 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7797 ? "true" : "false");
7798 }
7799 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7800 serializer.attribute(null, "installStatus", "false");
7801 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007802 if (pkg.installerPackageName != null) {
7803 serializer.attribute(null, "installer", pkg.installerPackageName);
7804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7806 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7807 serializer.startTag(null, "perms");
7808 if (pkg.sharedUser == null) {
7809 // If this is a shared user, the permissions will
7810 // be written there. We still need to write an
7811 // empty permissions list so permissionsFixed will
7812 // be set.
7813 for (final String name : pkg.grantedPermissions) {
7814 serializer.startTag(null, "item");
7815 serializer.attribute(null, "name", name);
7816 serializer.endTag(null, "item");
7817 }
7818 }
7819 serializer.endTag(null, "perms");
7820 }
7821 if (pkg.disabledComponents.size() > 0) {
7822 serializer.startTag(null, "disabled-components");
7823 for (final String name : pkg.disabledComponents) {
7824 serializer.startTag(null, "item");
7825 serializer.attribute(null, "name", name);
7826 serializer.endTag(null, "item");
7827 }
7828 serializer.endTag(null, "disabled-components");
7829 }
7830 if (pkg.enabledComponents.size() > 0) {
7831 serializer.startTag(null, "enabled-components");
7832 for (final String name : pkg.enabledComponents) {
7833 serializer.startTag(null, "item");
7834 serializer.attribute(null, "name", name);
7835 serializer.endTag(null, "item");
7836 }
7837 serializer.endTag(null, "enabled-components");
7838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 serializer.endTag(null, "package");
7841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 void writePermission(XmlSerializer serializer, BasePermission bp)
7844 throws XmlPullParserException, java.io.IOException {
7845 if (bp.type != BasePermission.TYPE_BUILTIN
7846 && bp.sourcePackage != null) {
7847 serializer.startTag(null, "item");
7848 serializer.attribute(null, "name", bp.name);
7849 serializer.attribute(null, "package", bp.sourcePackage);
7850 if (DEBUG_SETTINGS) Log.v(TAG,
7851 "Writing perm: name=" + bp.name + " type=" + bp.type);
7852 if (bp.type == BasePermission.TYPE_DYNAMIC) {
7853 PermissionInfo pi = bp.perm != null ? bp.perm.info
7854 : bp.pendingInfo;
7855 if (pi != null) {
7856 serializer.attribute(null, "type", "dynamic");
7857 if (pi.icon != 0) {
7858 serializer.attribute(null, "icon",
7859 Integer.toString(pi.icon));
7860 }
7861 if (pi.nonLocalizedLabel != null) {
7862 serializer.attribute(null, "label",
7863 pi.nonLocalizedLabel.toString());
7864 }
7865 if (pi.protectionLevel !=
7866 PermissionInfo.PROTECTION_NORMAL) {
7867 serializer.attribute(null, "protection",
7868 Integer.toString(pi.protectionLevel));
7869 }
7870 }
7871 }
7872 serializer.endTag(null, "item");
7873 }
7874 }
7875
7876 String getReadMessagesLP() {
7877 return mReadMessages.toString();
7878 }
7879
Oscar Montemayora8529f62009-11-18 10:14:20 -08007880 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007881 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
7882 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007883 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 while(its.hasNext()) {
7885 String key = its.next();
7886 PackageSetting ps = mPackages.get(key);
7887 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08007888 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 }
7890 }
7891 return ret;
7892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 boolean readLP() {
7895 FileInputStream str = null;
7896 if (mBackupSettingsFilename.exists()) {
7897 try {
7898 str = new FileInputStream(mBackupSettingsFilename);
7899 mReadMessages.append("Reading from backup settings file\n");
7900 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007901 if (mSettingsFilename.exists()) {
7902 // If both the backup and settings file exist, we
7903 // ignore the settings since it might have been
7904 // corrupted.
7905 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
7906 mSettingsFilename.delete();
7907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007908 } catch (java.io.IOException e) {
7909 // We'll try for the normal settings file.
7910 }
7911 }
7912
7913 mPastSignatures.clear();
7914
7915 try {
7916 if (str == null) {
7917 if (!mSettingsFilename.exists()) {
7918 mReadMessages.append("No settings file found\n");
7919 Log.i(TAG, "No current settings file!");
7920 return false;
7921 }
7922 str = new FileInputStream(mSettingsFilename);
7923 }
7924 XmlPullParser parser = Xml.newPullParser();
7925 parser.setInput(str, null);
7926
7927 int type;
7928 while ((type=parser.next()) != XmlPullParser.START_TAG
7929 && type != XmlPullParser.END_DOCUMENT) {
7930 ;
7931 }
7932
7933 if (type != XmlPullParser.START_TAG) {
7934 mReadMessages.append("No start tag found in settings file\n");
7935 Log.e(TAG, "No start tag found in package manager settings");
7936 return false;
7937 }
7938
7939 int outerDepth = parser.getDepth();
7940 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7941 && (type != XmlPullParser.END_TAG
7942 || parser.getDepth() > outerDepth)) {
7943 if (type == XmlPullParser.END_TAG
7944 || type == XmlPullParser.TEXT) {
7945 continue;
7946 }
7947
7948 String tagName = parser.getName();
7949 if (tagName.equals("package")) {
7950 readPackageLP(parser);
7951 } else if (tagName.equals("permissions")) {
7952 readPermissionsLP(mPermissions, parser);
7953 } else if (tagName.equals("permission-trees")) {
7954 readPermissionsLP(mPermissionTrees, parser);
7955 } else if (tagName.equals("shared-user")) {
7956 readSharedUserLP(parser);
7957 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08007958 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007959 } else if (tagName.equals("preferred-activities")) {
7960 readPreferredActivitiesLP(parser);
7961 } else if(tagName.equals("updated-package")) {
7962 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007963 } else if (tagName.equals("cleaning-package")) {
7964 String name = parser.getAttributeValue(null, "name");
7965 if (name != null) {
7966 mPackagesToBeCleaned.add(name);
7967 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007968 } else if (tagName.equals("renamed-package")) {
7969 String nname = parser.getAttributeValue(null, "new");
7970 String oname = parser.getAttributeValue(null, "old");
7971 if (nname != null && oname != null) {
7972 mRenamedPackages.put(nname, oname);
7973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 } else {
7975 Log.w(TAG, "Unknown element under <packages>: "
7976 + parser.getName());
7977 XmlUtils.skipCurrentTag(parser);
7978 }
7979 }
7980
7981 str.close();
7982
7983 } catch(XmlPullParserException e) {
7984 mReadMessages.append("Error reading: " + e.toString());
7985 Log.e(TAG, "Error reading package manager settings", e);
7986
7987 } catch(java.io.IOException e) {
7988 mReadMessages.append("Error reading: " + e.toString());
7989 Log.e(TAG, "Error reading package manager settings", e);
7990
7991 }
7992
7993 int N = mPendingPackages.size();
7994 for (int i=0; i<N; i++) {
7995 final PendingPackage pp = mPendingPackages.get(i);
7996 Object idObj = getUserIdLP(pp.sharedId);
7997 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007998 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007999 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008000 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008001 if (p == null) {
8002 Log.w(TAG, "Unable to create application package for "
8003 + pp.name);
8004 continue;
8005 }
8006 p.copyFrom(pp);
8007 } else if (idObj != null) {
8008 String msg = "Bad package setting: package " + pp.name
8009 + " has shared uid " + pp.sharedId
8010 + " that is not a shared uid\n";
8011 mReadMessages.append(msg);
8012 Log.e(TAG, msg);
8013 } else {
8014 String msg = "Bad package setting: package " + pp.name
8015 + " has shared uid " + pp.sharedId
8016 + " that is not defined\n";
8017 mReadMessages.append(msg);
8018 Log.e(TAG, msg);
8019 }
8020 }
8021 mPendingPackages.clear();
8022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 mReadMessages.append("Read completed successfully: "
8024 + mPackages.size() + " packages, "
8025 + mSharedUsers.size() + " shared uids\n");
8026
8027 return true;
8028 }
8029
8030 private int readInt(XmlPullParser parser, String ns, String name,
8031 int defValue) {
8032 String v = parser.getAttributeValue(ns, name);
8033 try {
8034 if (v == null) {
8035 return defValue;
8036 }
8037 return Integer.parseInt(v);
8038 } catch (NumberFormatException e) {
8039 reportSettingsProblem(Log.WARN,
8040 "Error in package manager settings: attribute " +
8041 name + " has bad integer value " + v + " at "
8042 + parser.getPositionDescription());
8043 }
8044 return defValue;
8045 }
8046
8047 private void readPermissionsLP(HashMap<String, BasePermission> out,
8048 XmlPullParser parser)
8049 throws IOException, XmlPullParserException {
8050 int outerDepth = parser.getDepth();
8051 int type;
8052 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8053 && (type != XmlPullParser.END_TAG
8054 || parser.getDepth() > outerDepth)) {
8055 if (type == XmlPullParser.END_TAG
8056 || type == XmlPullParser.TEXT) {
8057 continue;
8058 }
8059
8060 String tagName = parser.getName();
8061 if (tagName.equals("item")) {
8062 String name = parser.getAttributeValue(null, "name");
8063 String sourcePackage = parser.getAttributeValue(null, "package");
8064 String ptype = parser.getAttributeValue(null, "type");
8065 if (name != null && sourcePackage != null) {
8066 boolean dynamic = "dynamic".equals(ptype);
8067 BasePermission bp = new BasePermission(name, sourcePackage,
8068 dynamic
8069 ? BasePermission.TYPE_DYNAMIC
8070 : BasePermission.TYPE_NORMAL);
8071 if (dynamic) {
8072 PermissionInfo pi = new PermissionInfo();
8073 pi.packageName = sourcePackage.intern();
8074 pi.name = name.intern();
8075 pi.icon = readInt(parser, null, "icon", 0);
8076 pi.nonLocalizedLabel = parser.getAttributeValue(
8077 null, "label");
8078 pi.protectionLevel = readInt(parser, null, "protection",
8079 PermissionInfo.PROTECTION_NORMAL);
8080 bp.pendingInfo = pi;
8081 }
8082 out.put(bp.name, bp);
8083 } else {
8084 reportSettingsProblem(Log.WARN,
8085 "Error in package manager settings: permissions has"
8086 + " no name at " + parser.getPositionDescription());
8087 }
8088 } else {
8089 reportSettingsProblem(Log.WARN,
8090 "Unknown element reading permissions: "
8091 + parser.getName() + " at "
8092 + parser.getPositionDescription());
8093 }
8094 XmlUtils.skipCurrentTag(parser);
8095 }
8096 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008098 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008099 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008100 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008101 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008102 String codePathStr = parser.getAttributeValue(null, "codePath");
8103 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008104 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008105 resourcePathStr = codePathStr;
8106 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008107 String version = parser.getAttributeValue(null, "version");
8108 int versionCode = 0;
8109 if (version != null) {
8110 try {
8111 versionCode = Integer.parseInt(version);
8112 } catch (NumberFormatException e) {
8113 }
8114 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008116 int pkgFlags = 0;
8117 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008118 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008119 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008120 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008121 String timeStampStr = parser.getAttributeValue(null, "ts");
8122 if (timeStampStr != null) {
8123 try {
8124 long timeStamp = Long.parseLong(timeStampStr);
8125 ps.setTimeStamp(timeStamp, timeStampStr);
8126 } catch (NumberFormatException e) {
8127 }
8128 }
8129 String idStr = parser.getAttributeValue(null, "userId");
8130 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8131 if(ps.userId <= 0) {
8132 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8133 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8134 }
8135 int outerDepth = parser.getDepth();
8136 int type;
8137 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8138 && (type != XmlPullParser.END_TAG
8139 || parser.getDepth() > outerDepth)) {
8140 if (type == XmlPullParser.END_TAG
8141 || type == XmlPullParser.TEXT) {
8142 continue;
8143 }
8144
8145 String tagName = parser.getName();
8146 if (tagName.equals("perms")) {
8147 readGrantedPermissionsLP(parser,
8148 ps.grantedPermissions);
8149 } else {
8150 reportSettingsProblem(Log.WARN,
8151 "Unknown element under <updated-package>: "
8152 + parser.getName());
8153 XmlUtils.skipCurrentTag(parser);
8154 }
8155 }
8156 mDisabledSysPackages.put(name, ps);
8157 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 private void readPackageLP(XmlPullParser parser)
8160 throws XmlPullParserException, IOException {
8161 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008162 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 String idStr = null;
8164 String sharedIdStr = null;
8165 String codePathStr = null;
8166 String resourcePathStr = null;
8167 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008168 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008169 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 int pkgFlags = 0;
8171 String timeStampStr;
8172 long timeStamp = 0;
8173 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008174 String version = null;
8175 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008176 try {
8177 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008178 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008179 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008180 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008181 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8182 codePathStr = parser.getAttributeValue(null, "codePath");
8183 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008184 version = parser.getAttributeValue(null, "version");
8185 if (version != null) {
8186 try {
8187 versionCode = Integer.parseInt(version);
8188 } catch (NumberFormatException e) {
8189 }
8190 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008191 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008192
8193 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008194 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008195 try {
8196 pkgFlags = Integer.parseInt(systemStr);
8197 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008198 }
8199 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008200 // For backward compatibility
8201 systemStr = parser.getAttributeValue(null, "system");
8202 if (systemStr != null) {
8203 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8204 } else {
8205 // Old settings that don't specify system... just treat
8206 // them as system, good enough.
8207 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008209 }
8210 timeStampStr = parser.getAttributeValue(null, "ts");
8211 if (timeStampStr != null) {
8212 try {
8213 timeStamp = Long.parseLong(timeStampStr);
8214 } catch (NumberFormatException e) {
8215 }
8216 }
8217 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8218 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8219 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8220 if (resourcePathStr == null) {
8221 resourcePathStr = codePathStr;
8222 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008223 if (realName != null) {
8224 realName = realName.intern();
8225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008226 if (name == null) {
8227 reportSettingsProblem(Log.WARN,
8228 "Error in package manager settings: <package> has no name at "
8229 + parser.getPositionDescription());
8230 } else if (codePathStr == null) {
8231 reportSettingsProblem(Log.WARN,
8232 "Error in package manager settings: <package> has no codePath at "
8233 + parser.getPositionDescription());
8234 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008235 packageSetting = addPackageLP(name.intern(), realName,
8236 new File(codePathStr), new File(resourcePathStr),
8237 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008238 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8239 + ": userId=" + userId + " pkg=" + packageSetting);
8240 if (packageSetting == null) {
8241 reportSettingsProblem(Log.ERROR,
8242 "Failure adding uid " + userId
8243 + " while parsing settings at "
8244 + parser.getPositionDescription());
8245 } else {
8246 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8247 }
8248 } else if (sharedIdStr != null) {
8249 userId = sharedIdStr != null
8250 ? Integer.parseInt(sharedIdStr) : 0;
8251 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008252 packageSetting = new PendingPackage(name.intern(), realName,
8253 new File(codePathStr), new File(resourcePathStr),
8254 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008255 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8256 mPendingPackages.add((PendingPackage) packageSetting);
8257 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8258 + ": sharedUserId=" + userId + " pkg="
8259 + packageSetting);
8260 } else {
8261 reportSettingsProblem(Log.WARN,
8262 "Error in package manager settings: package "
8263 + name + " has bad sharedId " + sharedIdStr
8264 + " at " + parser.getPositionDescription());
8265 }
8266 } else {
8267 reportSettingsProblem(Log.WARN,
8268 "Error in package manager settings: package "
8269 + name + " has bad userId " + idStr + " at "
8270 + parser.getPositionDescription());
8271 }
8272 } catch (NumberFormatException e) {
8273 reportSettingsProblem(Log.WARN,
8274 "Error in package manager settings: package "
8275 + name + " has bad userId " + idStr + " at "
8276 + parser.getPositionDescription());
8277 }
8278 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008279 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008280 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008281 final String enabledStr = parser.getAttributeValue(null, "enabled");
8282 if (enabledStr != null) {
8283 if (enabledStr.equalsIgnoreCase("true")) {
8284 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8285 } else if (enabledStr.equalsIgnoreCase("false")) {
8286 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8287 } else if (enabledStr.equalsIgnoreCase("default")) {
8288 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8289 } else {
8290 reportSettingsProblem(Log.WARN,
8291 "Error in package manager settings: package "
8292 + name + " has bad enabled value: " + idStr
8293 + " at " + parser.getPositionDescription());
8294 }
8295 } else {
8296 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8297 }
8298 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8299 if (installStatusStr != null) {
8300 if (installStatusStr.equalsIgnoreCase("false")) {
8301 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8302 } else {
8303 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8304 }
8305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008307 int outerDepth = parser.getDepth();
8308 int type;
8309 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8310 && (type != XmlPullParser.END_TAG
8311 || parser.getDepth() > outerDepth)) {
8312 if (type == XmlPullParser.END_TAG
8313 || type == XmlPullParser.TEXT) {
8314 continue;
8315 }
8316
8317 String tagName = parser.getName();
8318 if (tagName.equals("disabled-components")) {
8319 readDisabledComponentsLP(packageSetting, parser);
8320 } else if (tagName.equals("enabled-components")) {
8321 readEnabledComponentsLP(packageSetting, parser);
8322 } else if (tagName.equals("sigs")) {
8323 packageSetting.signatures.readXml(parser, mPastSignatures);
8324 } else if (tagName.equals("perms")) {
8325 readGrantedPermissionsLP(parser,
8326 packageSetting.loadedPermissions);
8327 packageSetting.permissionsFixed = true;
8328 } else {
8329 reportSettingsProblem(Log.WARN,
8330 "Unknown element under <package>: "
8331 + parser.getName());
8332 XmlUtils.skipCurrentTag(parser);
8333 }
8334 }
8335 } else {
8336 XmlUtils.skipCurrentTag(parser);
8337 }
8338 }
8339
8340 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8341 XmlPullParser parser)
8342 throws IOException, XmlPullParserException {
8343 int outerDepth = parser.getDepth();
8344 int type;
8345 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8346 && (type != XmlPullParser.END_TAG
8347 || parser.getDepth() > outerDepth)) {
8348 if (type == XmlPullParser.END_TAG
8349 || type == XmlPullParser.TEXT) {
8350 continue;
8351 }
8352
8353 String tagName = parser.getName();
8354 if (tagName.equals("item")) {
8355 String name = parser.getAttributeValue(null, "name");
8356 if (name != null) {
8357 packageSetting.disabledComponents.add(name.intern());
8358 } else {
8359 reportSettingsProblem(Log.WARN,
8360 "Error in package manager settings: <disabled-components> has"
8361 + " no name at " + parser.getPositionDescription());
8362 }
8363 } else {
8364 reportSettingsProblem(Log.WARN,
8365 "Unknown element under <disabled-components>: "
8366 + parser.getName());
8367 }
8368 XmlUtils.skipCurrentTag(parser);
8369 }
8370 }
8371
8372 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8373 XmlPullParser parser)
8374 throws IOException, XmlPullParserException {
8375 int outerDepth = parser.getDepth();
8376 int type;
8377 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8378 && (type != XmlPullParser.END_TAG
8379 || parser.getDepth() > outerDepth)) {
8380 if (type == XmlPullParser.END_TAG
8381 || type == XmlPullParser.TEXT) {
8382 continue;
8383 }
8384
8385 String tagName = parser.getName();
8386 if (tagName.equals("item")) {
8387 String name = parser.getAttributeValue(null, "name");
8388 if (name != null) {
8389 packageSetting.enabledComponents.add(name.intern());
8390 } else {
8391 reportSettingsProblem(Log.WARN,
8392 "Error in package manager settings: <enabled-components> has"
8393 + " no name at " + parser.getPositionDescription());
8394 }
8395 } else {
8396 reportSettingsProblem(Log.WARN,
8397 "Unknown element under <enabled-components>: "
8398 + parser.getName());
8399 }
8400 XmlUtils.skipCurrentTag(parser);
8401 }
8402 }
8403
8404 private void readSharedUserLP(XmlPullParser parser)
8405 throws XmlPullParserException, IOException {
8406 String name = null;
8407 String idStr = null;
8408 int pkgFlags = 0;
8409 SharedUserSetting su = null;
8410 try {
8411 name = parser.getAttributeValue(null, "name");
8412 idStr = parser.getAttributeValue(null, "userId");
8413 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8414 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8415 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8416 }
8417 if (name == null) {
8418 reportSettingsProblem(Log.WARN,
8419 "Error in package manager settings: <shared-user> has no name at "
8420 + parser.getPositionDescription());
8421 } else if (userId == 0) {
8422 reportSettingsProblem(Log.WARN,
8423 "Error in package manager settings: shared-user "
8424 + name + " has bad userId " + idStr + " at "
8425 + parser.getPositionDescription());
8426 } else {
8427 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8428 reportSettingsProblem(Log.ERROR,
8429 "Occurred while parsing settings at "
8430 + parser.getPositionDescription());
8431 }
8432 }
8433 } catch (NumberFormatException e) {
8434 reportSettingsProblem(Log.WARN,
8435 "Error in package manager settings: package "
8436 + name + " has bad userId " + idStr + " at "
8437 + parser.getPositionDescription());
8438 };
8439
8440 if (su != null) {
8441 int outerDepth = parser.getDepth();
8442 int type;
8443 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8444 && (type != XmlPullParser.END_TAG
8445 || parser.getDepth() > outerDepth)) {
8446 if (type == XmlPullParser.END_TAG
8447 || type == XmlPullParser.TEXT) {
8448 continue;
8449 }
8450
8451 String tagName = parser.getName();
8452 if (tagName.equals("sigs")) {
8453 su.signatures.readXml(parser, mPastSignatures);
8454 } else if (tagName.equals("perms")) {
8455 readGrantedPermissionsLP(parser, su.loadedPermissions);
8456 } else {
8457 reportSettingsProblem(Log.WARN,
8458 "Unknown element under <shared-user>: "
8459 + parser.getName());
8460 XmlUtils.skipCurrentTag(parser);
8461 }
8462 }
8463
8464 } else {
8465 XmlUtils.skipCurrentTag(parser);
8466 }
8467 }
8468
8469 private void readGrantedPermissionsLP(XmlPullParser parser,
8470 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8471 int outerDepth = parser.getDepth();
8472 int type;
8473 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8474 && (type != XmlPullParser.END_TAG
8475 || parser.getDepth() > outerDepth)) {
8476 if (type == XmlPullParser.END_TAG
8477 || type == XmlPullParser.TEXT) {
8478 continue;
8479 }
8480
8481 String tagName = parser.getName();
8482 if (tagName.equals("item")) {
8483 String name = parser.getAttributeValue(null, "name");
8484 if (name != null) {
8485 outPerms.add(name.intern());
8486 } else {
8487 reportSettingsProblem(Log.WARN,
8488 "Error in package manager settings: <perms> has"
8489 + " no name at " + parser.getPositionDescription());
8490 }
8491 } else {
8492 reportSettingsProblem(Log.WARN,
8493 "Unknown element under <perms>: "
8494 + parser.getName());
8495 }
8496 XmlUtils.skipCurrentTag(parser);
8497 }
8498 }
8499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008500 private void readPreferredActivitiesLP(XmlPullParser parser)
8501 throws XmlPullParserException, IOException {
8502 int outerDepth = parser.getDepth();
8503 int type;
8504 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8505 && (type != XmlPullParser.END_TAG
8506 || parser.getDepth() > outerDepth)) {
8507 if (type == XmlPullParser.END_TAG
8508 || type == XmlPullParser.TEXT) {
8509 continue;
8510 }
8511
8512 String tagName = parser.getName();
8513 if (tagName.equals("item")) {
8514 PreferredActivity pa = new PreferredActivity(parser);
8515 if (pa.mParseError == null) {
8516 mPreferredActivities.addFilter(pa);
8517 } else {
8518 reportSettingsProblem(Log.WARN,
8519 "Error in package manager settings: <preferred-activity> "
8520 + pa.mParseError + " at "
8521 + parser.getPositionDescription());
8522 }
8523 } else {
8524 reportSettingsProblem(Log.WARN,
8525 "Unknown element under <preferred-activities>: "
8526 + parser.getName());
8527 XmlUtils.skipCurrentTag(parser);
8528 }
8529 }
8530 }
8531
8532 // Returns -1 if we could not find an available UserId to assign
8533 private int newUserIdLP(Object obj) {
8534 // Let's be stupidly inefficient for now...
8535 final int N = mUserIds.size();
8536 for (int i=0; i<N; i++) {
8537 if (mUserIds.get(i) == null) {
8538 mUserIds.set(i, obj);
8539 return FIRST_APPLICATION_UID + i;
8540 }
8541 }
8542
8543 // None left?
8544 if (N >= MAX_APPLICATION_UIDS) {
8545 return -1;
8546 }
8547
8548 mUserIds.add(obj);
8549 return FIRST_APPLICATION_UID + N;
8550 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 public PackageSetting getDisabledSystemPkg(String name) {
8553 synchronized(mPackages) {
8554 PackageSetting ps = mDisabledSysPackages.get(name);
8555 return ps;
8556 }
8557 }
8558
8559 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8560 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8561 if (Config.LOGV) {
8562 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8563 + " componentName = " + componentInfo.name);
8564 Log.v(TAG, "enabledComponents: "
8565 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8566 Log.v(TAG, "disabledComponents: "
8567 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8568 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008569 if (packageSettings == null) {
8570 if (false) {
8571 Log.w(TAG, "WAITING FOR DEBUGGER");
8572 Debug.waitForDebugger();
8573 Log.i(TAG, "We will crash!");
8574 }
8575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008576 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8577 || ((componentInfo.enabled
8578 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8579 || (componentInfo.applicationInfo.enabled
8580 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8581 && !packageSettings.disabledComponents.contains(componentInfo.name))
8582 || packageSettings.enabledComponents.contains(componentInfo.name));
8583 }
8584 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008585
8586 // ------- apps on sdcard specific code -------
8587 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008588 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008589 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008590 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008591 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008592
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008593
8594 static MountService getMountService() {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008595 return (MountService) ServiceManager.getService("mount");
8596 }
8597
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008598 private String getEncryptKey() {
8599 try {
8600 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8601 if (sdEncKey == null) {
8602 sdEncKey = SystemKeyStore.getInstance().
8603 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8604 if (sdEncKey == null) {
8605 Log.e(TAG, "Failed to create encryption keys");
8606 return null;
8607 }
8608 }
8609 return sdEncKey;
8610 } catch (NoSuchAlgorithmException nsae) {
8611 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8612 return null;
8613 }
8614 }
8615
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008616 private String createSdDir(File tmpPackageFile, String pkgName) {
8617 // Create mount point via MountService
8618 MountService mountService = getMountService();
8619 long len = tmpPackageFile.length();
8620 int mbLen = (int) (len/(1024*1024));
8621 if ((len - (mbLen * 1024 * 1024)) > 0) {
8622 mbLen++;
8623 }
8624 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
8625 String cachePath = null;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008626 String sdEncKey;
8627 try {
8628 sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8629 if (sdEncKey == null) {
8630 sdEncKey = SystemKeyStore.getInstance().
8631 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8632 if (sdEncKey == null) {
8633 Log.e(TAG, "Failed to create encryption keys for package: " + pkgName + ".");
8634 return null;
8635 }
8636 }
8637 } catch (NoSuchAlgorithmException nsae) {
8638 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8639 return null;
8640 }
San Mehatbe16cb12010-01-29 05:35:35 -08008641
8642 int rc = mountService.createSecureContainer(
8643 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
San Mehatb1043402010-02-05 08:26:50 -08008644 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008645 Log.e(TAG, String.format("Failed to create container (%d)", rc));
8646
8647 rc = mountService.destroySecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008648 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008649 Log.e(TAG, String.format("Failed to cleanup container (%d)", rc));
8650 return null;
8651 }
8652 rc = mountService.createSecureContainer(
8653 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
San Mehatb1043402010-02-05 08:26:50 -08008654 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008655 Log.e(TAG, String.format("Failed to create container (2nd try) (%d)", rc));
8656 return null;
8657 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008658 }
San Mehatbe16cb12010-01-29 05:35:35 -08008659
8660 cachePath = mountService.getSecureContainerPath(pkgName);
8661 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008662 return cachePath;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008663 }
8664
8665 private String mountSdDir(String pkgName, int ownerUid) {
Oscar Montemayord02546b2010-01-14 16:38:40 -08008666 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8667 if (sdEncKey == null) {
8668 Log.e(TAG, "Failed to retrieve encryption keys to mount package code: " + pkgName + ".");
8669 return null;
8670 }
San Mehatbe16cb12010-01-29 05:35:35 -08008671
8672 int rc = getMountService().mountSecureContainer(pkgName, sdEncKey, ownerUid);
8673
San Mehatb1043402010-02-05 08:26:50 -08008674 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008675 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " rc : " + rc);
8676 return null;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008677 }
San Mehatbe16cb12010-01-29 05:35:35 -08008678
8679 return getMountService().getSecureContainerPath(pkgName);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008680 }
8681
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008682 private boolean unMountSdDir(String pkgName) {
8683 // STOPSHIP unmount directory
San Mehatbe16cb12010-01-29 05:35:35 -08008684 int rc = getMountService().unmountSecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008685 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008686 Log.e(TAG, "Failed to unmount : " + pkgName + " with rc " + rc);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008687 return false;
8688 }
San Mehatbe16cb12010-01-29 05:35:35 -08008689 return true;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008690 }
8691
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008692 private boolean renameSdDir(String oldId, String newId) {
8693 try {
8694 getMountService().renameSecureContainer(oldId, newId);
8695 return true;
8696 } catch (IllegalStateException e) {
8697 Log.i(TAG, "Failed ot rename " + oldId + " to " + newId +
8698 " with exception : " + e);
8699 }
8700 return false;
8701 }
8702
8703 private String getSdDir(String pkgName) {
8704 return getMountService().getSecureContainerPath(pkgName);
8705 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008706
San Mehatbe16cb12010-01-29 05:35:35 -08008707 private boolean finalizeSdDir(String pkgName) {
8708 int rc = getMountService().finalizeSecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008709 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008710 Log.i(TAG, "Failed to finalize container for pkg : " + pkgName);
8711 return false;
8712 }
8713 return true;
8714 }
8715
8716 private boolean destroySdDir(String pkgName) {
8717 int rc = getMountService().destroySecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008718 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008719 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
8720 return false;
8721 }
8722 return true;
8723 }
8724
8725 static String[] getSecureContainerList() {
8726 String[] list = getMountService().getSecureContainerList();
8727 return list.length == 0 ? null : list;
8728 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008729
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008730 static boolean isContainerMounted(String cid) {
8731 // STOPSHIP
8732 // New api from MountService
8733 try {
8734 return (getMountService().getSecureContainerPath(cid) != null);
8735 } catch (IllegalStateException e) {
8736 }
8737 return false;
8738 }
8739
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008740 static String getTempContainerId() {
8741 String prefix = "smdl1tmp";
8742 int tmpIdx = 1;
8743 String list[] = getSecureContainerList();
8744 if (list != null) {
8745 int idx = 0;
8746 int idList[] = new int[MAX_CONTAINERS];
8747 boolean neverFound = true;
8748 for (String name : list) {
8749 // Ignore null entries
8750 if (name == null) {
8751 continue;
8752 }
8753 int sidx = name.indexOf(prefix);
8754 if (sidx == -1) {
8755 // Not a temp file. just ignore
8756 continue;
8757 }
8758 String subStr = name.substring(sidx + prefix.length());
8759 idList[idx] = -1;
8760 if (subStr != null) {
8761 try {
8762 int cid = Integer.parseInt(subStr);
8763 idList[idx++] = cid;
8764 neverFound = false;
8765 } catch (NumberFormatException e) {
8766 }
8767 }
8768 }
8769 if (!neverFound) {
8770 // Sort idList
8771 Arrays.sort(idList);
8772 for (int j = 1; j <= idList.length; j++) {
8773 if (idList[j-1] != j) {
8774 tmpIdx = j;
8775 break;
8776 }
8777 }
8778 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008779 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008780 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008781 }
8782
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008783 public void updateExternalMediaStatus(final boolean mediaStatus) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008784 synchronized (mPackages) {
8785 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8786 mediaStatus+", mMediaMounted=" + mMediaMounted);
8787 if (mediaStatus == mMediaMounted) {
8788 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008789 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008790 mMediaMounted = mediaStatus;
8791 // Queue up an async operation since the package installation may take a little while.
8792 mHandler.post(new Runnable() {
8793 public void run() {
8794 mHandler.removeCallbacks(this);
8795 updateExternalMediaStatusInner(mediaStatus);
8796 }
8797 });
8798 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008799 }
8800
8801 void updateExternalMediaStatusInner(boolean mediaStatus) {
8802 final String list[] = getSecureContainerList();
8803 if (list == null || list.length == 0) {
8804 return;
8805 }
8806 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8807 int uidList[] = new int[list.length];
8808 int num = 0;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008809 synchronized (mPackages) {
8810 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8811 for (String cid : list) {
8812 SdInstallArgs args = new SdInstallArgs(cid);
8813 String removeEntry = null;
8814 for (String app : appList) {
8815 if (args.matchContainer(app)) {
8816 removeEntry = app;
8817 break;
8818 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008819 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008820 if (removeEntry == null) {
8821 // No matching app on device. Skip entry or may be cleanup?
8822 // Ignore default package
8823 continue;
8824 }
8825 appList.remove(removeEntry);
8826 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8827 processCids.put(args, ps.codePathString);
8828 int uid = ps.userId;
8829 if (uid != -1) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008830 uidList[num++] = uid;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008831 }
8832 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008833 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008834 int uidArr[] = null;
8835 if (num > 0) {
8836 // Sort uid list
8837 Arrays.sort(uidList, 0, num);
8838 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008839 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008840 uidArr[0] = uidList[0];
8841 int di = 0;
8842 for (int i = 1; i < num; i++) {
8843 if (uidList[i-1] != uidList[i]) {
8844 uidArr[di++] = uidList[i];
8845 }
8846 }
8847 if (true) {
8848 for (int j = 0; j < num; j++) {
8849 Log.i(TAG, "uidArr[" + j + "]=" + uidArr[j]);
8850 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008851 }
8852 }
8853 if (mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008854 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008855 loadMediaPackages(processCids, uidArr);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008856 startCleaningPackages();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008857 } else {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008858 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008859 unloadMediaPackages(processCids, uidArr);
8860 }
8861 }
8862
8863 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8864 ArrayList<String> pkgList, int uidArr[]) {
8865 int size = pkgList.size();
8866 if (size > 0) {
8867 // Send broadcasts here
8868 Bundle extras = new Bundle();
8869 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8870 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008871 if (uidArr != null) {
8872 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8873 }
8874 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8875 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008876 sendPackageBroadcast(action, null, extras);
8877 }
8878 }
8879
8880 void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8881 ArrayList<String> pkgList = new ArrayList<String>();
8882 Set<SdInstallArgs> keys = processCids.keySet();
8883 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008884 String codePath = processCids.get(args);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008885 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install pkg : "
8886 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008887 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008888 Log.e(TAG, "Failed to install package: " + codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008889 continue;
8890 }
8891 // Parse package
8892 int parseFlags = PackageParser.PARSE_CHATTY |
8893 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8894 PackageParser pp = new PackageParser(codePath);
8895 pp.setSeparateProcesses(mSeparateProcesses);
8896 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
8897 codePath, mMetrics, parseFlags);
8898 if (pkg == null) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008899 Log.e(TAG, "Trying to install pkg : "
8900 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008901 continue;
8902 }
8903 setApplicationInfoPaths(pkg, codePath, codePath);
8904 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8905 synchronized (mInstallLock) {
8906 // Scan the package
8907 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
8908 synchronized (mPackages) {
8909 // Grant permissions
8910 grantPermissionsLP(pkg, false);
8911 // Persist settings
8912 mSettings.writeLP();
8913 retCode = PackageManager.INSTALL_SUCCEEDED;
8914 pkgList.add(pkg.packageName);
8915 }
8916 } else {
8917 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
8918 }
8919 }
8920 args.doPostInstall(retCode);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008921 }
8922 // Send broadcasts first
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008923 if (pkgList.size() > 0) {
8924 sendResourcesChangedBroadcast(true, pkgList, uidArr);
8925 Runtime.getRuntime().gc();
8926 // If something failed do we clean up here or next install?
8927 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008928 }
8929
8930 void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008931 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008932 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008933 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008934 Set<SdInstallArgs> keys = processCids.keySet();
8935 for (SdInstallArgs args : keys) {
8936 String cid = args.cid;
8937 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008938 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008939 // Delete package internally
8940 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8941 synchronized (mInstallLock) {
8942 boolean res = deletePackageLI(pkgName, false,
8943 PackageManager.DONT_DELETE_DATA, outInfo);
8944 if (res) {
8945 pkgList.add(pkgName);
8946 } else {
8947 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008948 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008949 }
8950 }
8951 }
8952 // Send broadcasts
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008953 if (pkgList.size() > 0) {
8954 sendResourcesChangedBroadcast(false, pkgList, uidArr);
8955 Runtime.getRuntime().gc();
8956 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008957 // Do clean up. Just unmount
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008958 for (SdInstallArgs args : failedList) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008959 synchronized (mInstallLock) {
8960 args.doPostDeleteLI(false);
8961 }
8962 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964}