blob: 4a7fc9c0570bc0a27adfb618161001061c7810f0 [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;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080031import android.app.DevicePolicyManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.app.IActivityManager;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080033import android.app.IDevicePolicyManager;
Christopher Tate1bb69062010-02-19 17:02:12 -080034import android.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.Context;
37import android.content.Intent;
38import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070039import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080040import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070041import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.ActivityInfo;
43import android.content.pm.ApplicationInfo;
44import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070045import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.IPackageDataObserver;
47import android.content.pm.IPackageDeleteObserver;
48import android.content.pm.IPackageInstallObserver;
49import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080050import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.IPackageStatsObserver;
52import android.content.pm.InstrumentationInfo;
53import android.content.pm.PackageInfo;
54import android.content.pm.PackageManager;
55import android.content.pm.PackageStats;
56import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
59import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
60import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
61import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
San Mehatb1043402010-02-05 08:26:50 -080083import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.ParcelFileDescriptor;
85import android.os.Process;
86import android.os.ServiceManager;
87import android.os.SystemClock;
88import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import android.view.Display;
92import android.view.WindowManager;
93
94import java.io.File;
95import java.io.FileDescriptor;
96import java.io.FileInputStream;
97import java.io.FileNotFoundException;
98import java.io.FileOutputStream;
99import java.io.FileReader;
100import java.io.FilenameFilter;
101import java.io.IOException;
102import java.io.InputStream;
103import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800104import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800105import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.ArrayList;
107import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700108import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Collections;
110import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800111import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import java.util.Enumeration;
113import java.util.HashMap;
114import java.util.HashSet;
115import java.util.Iterator;
116import java.util.List;
117import java.util.Map;
118import java.util.Set;
119import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800120import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import java.util.zip.ZipFile;
122import java.util.zip.ZipOutputStream;
123
124class PackageManagerService extends IPackageManager.Stub {
125 private static final String TAG = "PackageManager";
126 private static final boolean DEBUG_SETTINGS = false;
127 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800128 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800129 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130
131 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
132 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400133 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 private static final int FIRST_APPLICATION_UID =
135 Process.FIRST_APPLICATION_UID;
136 private static final int MAX_APPLICATION_UIDS = 1000;
137
138 private static final boolean SHOW_INFO = false;
139
140 private static final boolean GET_CERTIFICATES = true;
141
Oscar Montemayora8529f62009-11-18 10:14:20 -0800142 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 private static final int REMOVE_EVENTS =
145 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
146 private static final int ADD_EVENTS =
147 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
148
149 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800150 // Suffix used during package installation when copying/moving
151 // package apks to install directory.
152 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
154 static final int SCAN_MONITOR = 1<<0;
155 static final int SCAN_NO_DEX = 1<<1;
156 static final int SCAN_FORCE_DEX = 1<<2;
157 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800158 static final int SCAN_NEW_INSTALL = 1<<4;
159 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800161 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
162 "com.android.defcontainer",
163 "com.android.defcontainer.DefaultContainerService");
164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
166 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700167 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
Dianne Hackborn851a5412009-05-08 12:06:44 -0700169 final int mSdkVersion = Build.VERSION.SDK_INT;
170 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
171 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 final Context mContext;
174 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700175 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 final DisplayMetrics mMetrics;
177 final int mDefParseFlags;
178 final String[] mSeparateProcesses;
179
180 // This is where all application persistent data goes.
181 final File mAppDataDir;
182
Oscar Montemayora8529f62009-11-18 10:14:20 -0800183 // If Encrypted File System feature is enabled, all application persistent data
184 // should go here instead.
185 final File mSecureAppDataDir;
186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 // This is the object monitoring the framework dir.
188 final FileObserver mFrameworkInstallObserver;
189
190 // This is the object monitoring the system app dir.
191 final FileObserver mSystemInstallObserver;
192
193 // This is the object monitoring mAppInstallDir.
194 final FileObserver mAppInstallObserver;
195
196 // This is the object monitoring mDrmAppPrivateInstallDir.
197 final FileObserver mDrmAppInstallObserver;
198
199 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
200 // LOCK HELD. Can be called with mInstallLock held.
201 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 final File mFrameworkDir;
204 final File mSystemAppDir;
205 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700206 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
208 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
209 // apps.
210 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 // Lock for state used when installing and doing other long running
215 // operations. Methods that must be called with this lock held have
216 // the prefix "LI".
217 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 // These are the directories in the 3rd party applications installed dir
220 // that we have currently loaded packages from. Keys are the application's
221 // installed zip file (absolute codePath), and values are Package.
222 final HashMap<String, PackageParser.Package> mAppDirs =
223 new HashMap<String, PackageParser.Package>();
224
225 // Information for the parser to write more useful error messages.
226 File mScanningPath;
227 int mLastScanError;
228
229 final int[] mOutPermissions = new int[3];
230
231 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 // Keys are String (package name), values are Package. This also serves
234 // as the lock for the global state. Methods that must be called with
235 // this lock held have the prefix "LP".
236 final HashMap<String, PackageParser.Package> mPackages =
237 new HashMap<String, PackageParser.Package>();
238
239 final Settings mSettings;
240 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
243 int[] mGlobalGids;
244
245 // These are the built-in uid -> permission mappings that were read from the
246 // etc/permissions.xml file.
247 final SparseArray<HashSet<String>> mSystemPermissions =
248 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 // These are the built-in shared libraries that were read from the
251 // etc/permissions.xml file.
252 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800253
Dianne Hackborn49237342009-08-27 20:08:01 -0700254 // Temporary for building the final shared libraries for an .apk.
255 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800256
Dianne Hackborn49237342009-08-27 20:08:01 -0700257 // These are the features this devices supports that were read from the
258 // etc/permissions.xml file.
259 final HashMap<String, FeatureInfo> mAvailableFeatures =
260 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 // All available activities, for your resolving pleasure.
263 final ActivityIntentResolver mActivities =
264 new ActivityIntentResolver();
265
266 // All available receivers, for your resolving pleasure.
267 final ActivityIntentResolver mReceivers =
268 new ActivityIntentResolver();
269
270 // All available services, for your resolving pleasure.
271 final ServiceIntentResolver mServices = new ServiceIntentResolver();
272
273 // Keys are String (provider class name), values are Provider.
274 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
275 new HashMap<ComponentName, PackageParser.Provider>();
276
277 // Mapping from provider base names (first directory in content URI codePath)
278 // to the provider information.
279 final HashMap<String, PackageParser.Provider> mProviders =
280 new HashMap<String, PackageParser.Provider>();
281
282 // Mapping from instrumentation class names to info about them.
283 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
284 new HashMap<ComponentName, PackageParser.Instrumentation>();
285
286 // Mapping from permission names to info about them.
287 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
288 new HashMap<String, PackageParser.PermissionGroup>();
289
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800290 // Packages whose data we have transfered into another package, thus
291 // should no longer exist.
292 final HashSet<String> mTransferedPackages = new HashSet<String>();
293
Dianne Hackborn854060af2009-07-09 18:14:31 -0700294 // Broadcast actions that are only available to the system.
295 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 boolean mSystemReady;
298 boolean mSafeMode;
299 boolean mHasSystemUidErrors;
300
301 ApplicationInfo mAndroidApplication;
302 final ActivityInfo mResolveActivity = new ActivityInfo();
303 final ResolveInfo mResolveInfo = new ResolveInfo();
304 ComponentName mResolveComponentName;
305 PackageParser.Package mPlatformPackage;
306
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700307 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800308 final HashMap<String, ArrayList<String>> mPendingBroadcasts
309 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700310 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800311 static final int MCS_BOUND = 3;
312 static final int END_COPY = 4;
313 static final int INIT_COPY = 5;
314 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800315 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800316 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800317 static final int POST_INSTALL = 9;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700318 // Delay time in millisecs
319 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800320 private ServiceConnection mDefContainerConn = new ServiceConnection() {
321 public void onServiceConnected(ComponentName name, IBinder service) {
322 IMediaContainerService imcs =
323 IMediaContainerService.Stub.asInterface(service);
324 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
325 mHandler.sendMessage(msg);
326 }
327
328 public void onServiceDisconnected(ComponentName name) {
329 }
330 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700331
Christopher Tate1bb69062010-02-19 17:02:12 -0800332 // Recordkeeping of restore-after-install operations that are currently in flight
333 // between the Package Manager and the Backup Manager
334 class PostInstallData {
335 public InstallArgs args;
336 public PackageInstalledInfo res;
337
338 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
339 args = _a;
340 res = _r;
341 }
342 };
343 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
344 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
345
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700346 class PackageHandler extends Handler {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800347 final ArrayList<HandlerParams> mPendingInstalls =
348 new ArrayList<HandlerParams>();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800349 // Service Connection to remote media container service to copy
350 // package uri's from external media onto secure containers
351 // or internal storage.
352 private IMediaContainerService mContainerService = null;
353
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700354 PackageHandler(Looper looper) {
355 super(looper);
356 }
357 public void handleMessage(Message msg) {
358 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800359 case INIT_COPY: {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800360 HandlerParams params = (HandlerParams) msg.obj;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800361 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800362 if (mContainerService != null) {
363 // No need to add to pending list. Use remote stub directly
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800364 params.handleStartCopy(mContainerService);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800365 } else {
366 if (mContext.bindService(service, mDefContainerConn,
367 Context.BIND_AUTO_CREATE)) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800368 mPendingInstalls.add(params);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800369 } else {
370 Log.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800371 // Indicate service bind error
372 params.handleServiceError();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800373 }
374 }
375 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800376 }
377 case MCS_BOUND: {
378 // Initialize mContainerService if needed.
379 if (msg.obj != null) {
380 mContainerService = (IMediaContainerService) msg.obj;
381 }
382 if (mPendingInstalls.size() > 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800383 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800384 if (params != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800385 params.handleStartCopy(mContainerService);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800386 }
387 }
388 break;
389 }
390 case MCS_UNBIND : {
391 if (mPendingInstalls.size() == 0) {
392 mContext.unbindService(mDefContainerConn);
393 mContainerService = null;
394 }
395 break;
396 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700397 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800398 String packages[];
399 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700400 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700401 int uids[];
402 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800403 if (mPendingBroadcasts == null) {
404 return;
405 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700406 size = mPendingBroadcasts.size();
407 if (size <= 0) {
408 // Nothing to be done. Just return
409 return;
410 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800411 packages = new String[size];
412 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700413 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800414 Iterator<HashMap.Entry<String, ArrayList<String>>>
415 it = mPendingBroadcasts.entrySet().iterator();
416 int i = 0;
417 while (it.hasNext() && i < size) {
418 HashMap.Entry<String, ArrayList<String>> ent = it.next();
419 packages[i] = ent.getKey();
420 components[i] = ent.getValue();
421 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700422 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800423 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700424 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800425 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700426 mPendingBroadcasts.clear();
427 }
428 // Send broadcasts
429 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800430 sendPackageChangedBroadcast(packages[i], true,
431 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700432 }
433 break;
434 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800435 case START_CLEANING_PACKAGE: {
436 String packageName = (String)msg.obj;
437 synchronized (mPackages) {
438 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
439 mSettings.mPackagesToBeCleaned.add(packageName);
440 }
441 }
442 startCleaningPackages();
443 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800444 case POST_INSTALL: {
445 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
446 PostInstallData data = mRunningInstalls.get(msg.arg1);
447 mRunningInstalls.delete(msg.arg1);
448
449 if (data != null) {
450 InstallArgs args = data.args;
451 PackageInstalledInfo res = data.res;
452
453 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
454 res.removedInfo.sendBroadcast(false, true);
455 Bundle extras = new Bundle(1);
456 extras.putInt(Intent.EXTRA_UID, res.uid);
457 final boolean update = res.removedInfo.removedPackage != null;
458 if (update) {
459 extras.putBoolean(Intent.EXTRA_REPLACING, true);
460 }
461 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
462 res.pkg.applicationInfo.packageName,
463 extras);
464 if (update) {
465 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
466 res.pkg.applicationInfo.packageName,
467 extras);
468 }
469 if (res.removedInfo.args != null) {
470 // Remove the replaced package's older resources safely now
471 synchronized (mInstallLock) {
472 res.removedInfo.args.doPostDeleteLI(true);
473 }
474 }
475 }
476 Runtime.getRuntime().gc();
477
478 if (args.observer != null) {
479 try {
480 args.observer.packageInstalled(res.name, res.returnCode);
481 } catch (RemoteException e) {
482 Log.i(TAG, "Observer no longer exists.");
483 }
484 }
485 } else {
486 Log.e(TAG, "Bogus post-install token " + msg.arg1);
487 }
488 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700489 }
490 }
491 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800492
493 static boolean installOnSd(int flags) {
494 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800495 ((flags & PackageManager.INSTALL_EXTERNAL) == 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800496 return false;
497 }
498 return true;
499 }
500
501 static boolean isFwdLocked(int flags) {
502 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
503 return true;
504 }
505 return false;
506 }
507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 public static final IPackageManager main(Context context, boolean factoryTest) {
509 PackageManagerService m = new PackageManagerService(context, factoryTest);
510 ServiceManager.addService("package", m);
511 return m;
512 }
513
514 static String[] splitString(String str, char sep) {
515 int count = 1;
516 int i = 0;
517 while ((i=str.indexOf(sep, i)) >= 0) {
518 count++;
519 i++;
520 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 String[] res = new String[count];
523 i=0;
524 count = 0;
525 int lastI=0;
526 while ((i=str.indexOf(sep, i)) >= 0) {
527 res[count] = str.substring(lastI, i);
528 count++;
529 i++;
530 lastI = i;
531 }
532 res[count] = str.substring(lastI, str.length());
533 return res;
534 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800537 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 if (mSdkVersion <= 0) {
541 Log.w(TAG, "**** ro.build.version.sdk not set!");
542 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 mContext = context;
545 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700546 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 mMetrics = new DisplayMetrics();
548 mSettings = new Settings();
549 mSettings.addSharedUserLP("android.uid.system",
550 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
551 mSettings.addSharedUserLP("android.uid.phone",
552 MULTIPLE_APPLICATION_UIDS
553 ? RADIO_UID : FIRST_APPLICATION_UID,
554 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400555 mSettings.addSharedUserLP("android.uid.log",
556 MULTIPLE_APPLICATION_UIDS
557 ? LOG_UID : FIRST_APPLICATION_UID,
558 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559
560 String separateProcesses = SystemProperties.get("debug.separate_processes");
561 if (separateProcesses != null && separateProcesses.length() > 0) {
562 if ("*".equals(separateProcesses)) {
563 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
564 mSeparateProcesses = null;
565 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
566 } else {
567 mDefParseFlags = 0;
568 mSeparateProcesses = separateProcesses.split(",");
569 Log.w(TAG, "Running with debug.separate_processes: "
570 + separateProcesses);
571 }
572 } else {
573 mDefParseFlags = 0;
574 mSeparateProcesses = null;
575 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 Installer installer = new Installer();
578 // Little hacky thing to check if installd is here, to determine
579 // whether we are running on the simulator and thus need to take
580 // care of building the /data file structure ourself.
581 // (apparently the sim now has a working installer)
582 if (installer.ping() && Process.supportsProcesses()) {
583 mInstaller = installer;
584 } else {
585 mInstaller = null;
586 }
587
588 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
589 Display d = wm.getDefaultDisplay();
590 d.getMetrics(mMetrics);
591
592 synchronized (mInstallLock) {
593 synchronized (mPackages) {
594 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700595 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 File dataDir = Environment.getDataDirectory();
598 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800599 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
601
602 if (mInstaller == null) {
603 // Make sure these dirs exist, when we are running in
604 // the simulator.
605 // Make a wide-open directory for random misc stuff.
606 File miscDir = new File(dataDir, "misc");
607 miscDir.mkdirs();
608 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800609 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 mDrmAppPrivateInstallDir.mkdirs();
611 }
612
613 readPermissions();
614
615 mRestoredSettings = mSettings.readLP();
616 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800617
618 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800620
Suchi Amalapurapudaec1722010-01-14 21:25:16 -0800621 // Set flag to monitor and not change apk file paths when
622 // scanning install directories.
623 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700624 if (mNoDexOpt) {
625 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800626 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700627 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700632 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700635 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 /**
638 * Out of paranoia, ensure that everything in the boot class
639 * path has been dexed.
640 */
641 String bootClassPath = System.getProperty("java.boot.class.path");
642 if (bootClassPath != null) {
643 String[] paths = splitString(bootClassPath, ':');
644 for (int i=0; i<paths.length; i++) {
645 try {
646 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
647 libFiles.add(paths[i]);
648 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700649 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 }
651 } catch (FileNotFoundException e) {
652 Log.w(TAG, "Boot class path not found: " + paths[i]);
653 } catch (IOException e) {
654 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
655 }
656 }
657 } else {
658 Log.w(TAG, "No BOOTCLASSPATH found!");
659 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 /**
662 * Also ensure all external libraries have had dexopt run on them.
663 */
664 if (mSharedLibraries.size() > 0) {
665 Iterator<String> libs = mSharedLibraries.values().iterator();
666 while (libs.hasNext()) {
667 String lib = libs.next();
668 try {
669 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
670 libFiles.add(lib);
671 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700672 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 }
674 } catch (FileNotFoundException e) {
675 Log.w(TAG, "Library not found: " + lib);
676 } catch (IOException e) {
677 Log.w(TAG, "Exception reading library: " + lib, e);
678 }
679 }
680 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 // Gross hack for now: we know this file doesn't contain any
683 // code, so don't dexopt it to avoid the resulting log spew.
684 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 /**
687 * And there are a number of commands implemented in Java, which
688 * we currently need to do the dexopt on so that they can be
689 * run from a non-root shell.
690 */
691 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700692 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 for (int i=0; i<frameworkFiles.length; i++) {
694 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
695 String path = libPath.getPath();
696 // Skip the file if we alrady did it.
697 if (libFiles.contains(path)) {
698 continue;
699 }
700 // Skip the file if it is not a type we want to dexopt.
701 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
702 continue;
703 }
704 try {
705 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
706 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700707 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 }
709 } catch (FileNotFoundException e) {
710 Log.w(TAG, "Jar not found: " + path);
711 } catch (IOException e) {
712 Log.w(TAG, "Exception reading jar: " + path, e);
713 }
714 }
715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800716
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700717 if (didDexOpt) {
718 // If we had to do a dexopt of one of the previous
719 // things, then something on the system has changed.
720 // Consider this significant, and wipe away all other
721 // existing dexopt files to ensure we don't leave any
722 // dangling around.
723 String[] files = mDalvikCacheDir.list();
724 if (files != null) {
725 for (int i=0; i<files.length; i++) {
726 String fn = files[i];
727 if (fn.startsWith("data@app@")
728 || fn.startsWith("data@app-private@")) {
729 Log.i(TAG, "Pruning dalvik file: " + fn);
730 (new File(mDalvikCacheDir, fn)).delete();
731 }
732 }
733 }
734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800736
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800737 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 mFrameworkInstallObserver = new AppDirObserver(
739 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
740 mFrameworkInstallObserver.startWatching();
741 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec1722010-01-14 21:25:16 -0800742 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800743
744 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
746 mSystemInstallObserver = new AppDirObserver(
747 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
748 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec1722010-01-14 21:25:16 -0800749 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800750
751 if (mInstaller != null) {
752 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
753 mInstaller.moveFiles();
754 }
755
756 // Prune any system packages that no longer exist.
757 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
758 while (psit.hasNext()) {
759 PackageSetting ps = psit.next();
760 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800761 && !mPackages.containsKey(ps.name)
762 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800763 psit.remove();
764 String msg = "System package " + ps.name
765 + " no longer exists; wiping its data";
766 reportSettingsProblem(Log.WARN, msg);
767 if (mInstaller != null) {
768 // XXX how to set useEncryptedFSDir for packages that
769 // are not encrypted?
770 mInstaller.remove(ps.name, true);
771 }
772 }
773 }
774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 mAppInstallDir = new File(dataDir, "app");
776 if (mInstaller == null) {
777 // Make sure these dirs exist, when we are running in
778 // the simulator.
779 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
780 }
781 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800782 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 //clean up list
784 for(int i = 0; i < deletePkgsList.size(); i++) {
785 //clean up here
786 cleanupInstallFailedPackage(deletePkgsList.get(i));
787 }
788 //delete tmp files
789 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800790
791 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 SystemClock.uptimeMillis());
793 mAppInstallObserver = new AppDirObserver(
794 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
795 mAppInstallObserver.startWatching();
796 scanDirLI(mAppInstallDir, 0, scanMode);
797
798 mDrmAppInstallObserver = new AppDirObserver(
799 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
800 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800801 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800803 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 SystemClock.uptimeMillis());
805 Log.i(TAG, "Time to scan packages: "
806 + ((SystemClock.uptimeMillis()-startTime)/1000f)
807 + " seconds");
808
809 updatePermissionsLP();
810
811 mSettings.writeLP();
812
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800813 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 // Now after opening every single application zip, make sure they
817 // are all flushed. Not really needed, but keeps things nice and
818 // tidy.
819 Runtime.getRuntime().gc();
820 } // synchronized (mPackages)
821 } // synchronized (mInstallLock)
822 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 @Override
825 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
826 throws RemoteException {
827 try {
828 return super.onTransact(code, data, reply, flags);
829 } catch (RuntimeException e) {
830 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
831 Log.e(TAG, "Package Manager Crash", e);
832 }
833 throw e;
834 }
835 }
836
Dianne Hackborne6620b22010-01-22 14:46:21 -0800837 void cleanupInstallFailedPackage(PackageSetting ps) {
838 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800840 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
841 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 if (retCode < 0) {
843 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800844 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 }
846 } else {
847 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800848 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 File dataDir = new File(pkg.applicationInfo.dataDir);
850 dataDir.delete();
851 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800852 if (ps.codePath != null) {
853 if (!ps.codePath.delete()) {
854 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
855 }
856 }
857 if (ps.resourcePath != null) {
858 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
859 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
860 }
861 }
862 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
864
865 void readPermissions() {
866 // Read permissions from .../etc/permission directory.
867 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
868 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
869 Log.w(TAG, "No directory " + libraryDir + ", skipping");
870 return;
871 }
872 if (!libraryDir.canRead()) {
873 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
874 return;
875 }
876
877 // Iterate over the files in the directory and scan .xml files
878 for (File f : libraryDir.listFiles()) {
879 // We'll read platform.xml last
880 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
881 continue;
882 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 if (!f.getPath().endsWith(".xml")) {
885 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
886 continue;
887 }
888 if (!f.canRead()) {
889 Log.w(TAG, "Permissions library file " + f + " cannot be read");
890 continue;
891 }
892
893 readPermissionsFromXml(f);
894 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
897 final File permFile = new File(Environment.getRootDirectory(),
898 "etc/permissions/platform.xml");
899 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800900
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700901 StringBuilder sb = new StringBuilder(128);
902 sb.append("Libs:");
903 Iterator<String> it = mSharedLibraries.keySet().iterator();
904 while (it.hasNext()) {
905 sb.append(' ');
906 String name = it.next();
907 sb.append(name);
908 sb.append(':');
909 sb.append(mSharedLibraries.get(name));
910 }
911 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800912
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700913 sb.setLength(0);
914 sb.append("Features:");
915 it = mAvailableFeatures.keySet().iterator();
916 while (it.hasNext()) {
917 sb.append(' ');
918 sb.append(it.next());
919 }
920 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800922
923 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 FileReader permReader = null;
925 try {
926 permReader = new FileReader(permFile);
927 } catch (FileNotFoundException e) {
928 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
929 return;
930 }
931
932 try {
933 XmlPullParser parser = Xml.newPullParser();
934 parser.setInput(permReader);
935
936 XmlUtils.beginDocument(parser, "permissions");
937
938 while (true) {
939 XmlUtils.nextElement(parser);
940 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
941 break;
942 }
943
944 String name = parser.getName();
945 if ("group".equals(name)) {
946 String gidStr = parser.getAttributeValue(null, "gid");
947 if (gidStr != null) {
948 int gid = Integer.parseInt(gidStr);
949 mGlobalGids = appendInt(mGlobalGids, gid);
950 } else {
951 Log.w(TAG, "<group> without gid at "
952 + parser.getPositionDescription());
953 }
954
955 XmlUtils.skipCurrentTag(parser);
956 continue;
957 } else if ("permission".equals(name)) {
958 String perm = parser.getAttributeValue(null, "name");
959 if (perm == null) {
960 Log.w(TAG, "<permission> without name at "
961 + parser.getPositionDescription());
962 XmlUtils.skipCurrentTag(parser);
963 continue;
964 }
965 perm = perm.intern();
966 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 } else if ("assign-permission".equals(name)) {
969 String perm = parser.getAttributeValue(null, "name");
970 if (perm == null) {
971 Log.w(TAG, "<assign-permission> without name at "
972 + parser.getPositionDescription());
973 XmlUtils.skipCurrentTag(parser);
974 continue;
975 }
976 String uidStr = parser.getAttributeValue(null, "uid");
977 if (uidStr == null) {
978 Log.w(TAG, "<assign-permission> without uid at "
979 + parser.getPositionDescription());
980 XmlUtils.skipCurrentTag(parser);
981 continue;
982 }
983 int uid = Process.getUidForName(uidStr);
984 if (uid < 0) {
985 Log.w(TAG, "<assign-permission> with unknown uid \""
986 + uidStr + "\" at "
987 + parser.getPositionDescription());
988 XmlUtils.skipCurrentTag(parser);
989 continue;
990 }
991 perm = perm.intern();
992 HashSet<String> perms = mSystemPermissions.get(uid);
993 if (perms == null) {
994 perms = new HashSet<String>();
995 mSystemPermissions.put(uid, perms);
996 }
997 perms.add(perm);
998 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 } else if ("library".equals(name)) {
1001 String lname = parser.getAttributeValue(null, "name");
1002 String lfile = parser.getAttributeValue(null, "file");
1003 if (lname == null) {
1004 Log.w(TAG, "<library> without name at "
1005 + parser.getPositionDescription());
1006 } else if (lfile == null) {
1007 Log.w(TAG, "<library> without file at "
1008 + parser.getPositionDescription());
1009 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001010 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001011 mSharedLibraries.put(lname, lfile);
1012 }
1013 XmlUtils.skipCurrentTag(parser);
1014 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001015
Dianne Hackborn49237342009-08-27 20:08:01 -07001016 } else if ("feature".equals(name)) {
1017 String fname = parser.getAttributeValue(null, "name");
1018 if (fname == null) {
1019 Log.w(TAG, "<feature> without name at "
1020 + parser.getPositionDescription());
1021 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001022 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001023 FeatureInfo fi = new FeatureInfo();
1024 fi.name = fname;
1025 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 }
1027 XmlUtils.skipCurrentTag(parser);
1028 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 } else {
1031 XmlUtils.skipCurrentTag(parser);
1032 continue;
1033 }
1034
1035 }
1036 } catch (XmlPullParserException e) {
1037 Log.w(TAG, "Got execption parsing permissions.", e);
1038 } catch (IOException e) {
1039 Log.w(TAG, "Got execption parsing permissions.", e);
1040 }
1041 }
1042
1043 void readPermission(XmlPullParser parser, String name)
1044 throws IOException, XmlPullParserException {
1045
1046 name = name.intern();
1047
1048 BasePermission bp = mSettings.mPermissions.get(name);
1049 if (bp == null) {
1050 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1051 mSettings.mPermissions.put(name, bp);
1052 }
1053 int outerDepth = parser.getDepth();
1054 int type;
1055 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1056 && (type != XmlPullParser.END_TAG
1057 || parser.getDepth() > outerDepth)) {
1058 if (type == XmlPullParser.END_TAG
1059 || type == XmlPullParser.TEXT) {
1060 continue;
1061 }
1062
1063 String tagName = parser.getName();
1064 if ("group".equals(tagName)) {
1065 String gidStr = parser.getAttributeValue(null, "gid");
1066 if (gidStr != null) {
1067 int gid = Process.getGidForName(gidStr);
1068 bp.gids = appendInt(bp.gids, gid);
1069 } else {
1070 Log.w(TAG, "<group> without gid at "
1071 + parser.getPositionDescription());
1072 }
1073 }
1074 XmlUtils.skipCurrentTag(parser);
1075 }
1076 }
1077
1078 static int[] appendInt(int[] cur, int val) {
1079 if (cur == null) {
1080 return new int[] { val };
1081 }
1082 final int N = cur.length;
1083 for (int i=0; i<N; i++) {
1084 if (cur[i] == val) {
1085 return cur;
1086 }
1087 }
1088 int[] ret = new int[N+1];
1089 System.arraycopy(cur, 0, ret, 0, N);
1090 ret[N] = val;
1091 return ret;
1092 }
1093
1094 static int[] appendInts(int[] cur, int[] add) {
1095 if (add == null) return cur;
1096 if (cur == null) return add;
1097 final int N = add.length;
1098 for (int i=0; i<N; i++) {
1099 cur = appendInt(cur, add[i]);
1100 }
1101 return cur;
1102 }
1103
1104 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001105 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1106 // The package has been uninstalled but has retained data and resources.
1107 return PackageParser.generatePackageInfo(p, null, flags);
1108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 final PackageSetting ps = (PackageSetting)p.mExtras;
1110 if (ps == null) {
1111 return null;
1112 }
1113 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1114 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1115 }
1116
1117 public PackageInfo getPackageInfo(String packageName, int flags) {
1118 synchronized (mPackages) {
1119 PackageParser.Package p = mPackages.get(packageName);
1120 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001121 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 + ": " + p);
1123 if (p != null) {
1124 return generatePackageInfo(p, flags);
1125 }
1126 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1127 return generatePackageInfoFromSettingsLP(packageName, flags);
1128 }
1129 }
1130 return null;
1131 }
1132
Dianne Hackborn47096932010-02-11 15:57:09 -08001133 public String[] currentToCanonicalPackageNames(String[] names) {
1134 String[] out = new String[names.length];
1135 synchronized (mPackages) {
1136 for (int i=names.length-1; i>=0; i--) {
1137 PackageSetting ps = mSettings.mPackages.get(names[i]);
1138 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1139 }
1140 }
1141 return out;
1142 }
1143
1144 public String[] canonicalToCurrentPackageNames(String[] names) {
1145 String[] out = new String[names.length];
1146 synchronized (mPackages) {
1147 for (int i=names.length-1; i>=0; i--) {
1148 String cur = mSettings.mRenamedPackages.get(names[i]);
1149 out[i] = cur != null ? cur : names[i];
1150 }
1151 }
1152 return out;
1153 }
1154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 public int getPackageUid(String packageName) {
1156 synchronized (mPackages) {
1157 PackageParser.Package p = mPackages.get(packageName);
1158 if(p != null) {
1159 return p.applicationInfo.uid;
1160 }
1161 PackageSetting ps = mSettings.mPackages.get(packageName);
1162 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1163 return -1;
1164 }
1165 p = ps.pkg;
1166 return p != null ? p.applicationInfo.uid : -1;
1167 }
1168 }
1169
1170 public int[] getPackageGids(String packageName) {
1171 synchronized (mPackages) {
1172 PackageParser.Package p = mPackages.get(packageName);
1173 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001174 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 + ": " + p);
1176 if (p != null) {
1177 final PackageSetting ps = (PackageSetting)p.mExtras;
1178 final SharedUserSetting suid = ps.sharedUser;
1179 return suid != null ? suid.gids : ps.gids;
1180 }
1181 }
1182 // stupid thing to indicate an error.
1183 return new int[0];
1184 }
1185
1186 public PermissionInfo getPermissionInfo(String name, int flags) {
1187 synchronized (mPackages) {
1188 final BasePermission p = mSettings.mPermissions.get(name);
1189 if (p != null && p.perm != null) {
1190 return PackageParser.generatePermissionInfo(p.perm, flags);
1191 }
1192 return null;
1193 }
1194 }
1195
1196 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1197 synchronized (mPackages) {
1198 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1199 for (BasePermission p : mSettings.mPermissions.values()) {
1200 if (group == null) {
1201 if (p.perm.info.group == null) {
1202 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1203 }
1204 } else {
1205 if (group.equals(p.perm.info.group)) {
1206 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1207 }
1208 }
1209 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 if (out.size() > 0) {
1212 return out;
1213 }
1214 return mPermissionGroups.containsKey(group) ? out : null;
1215 }
1216 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1219 synchronized (mPackages) {
1220 return PackageParser.generatePermissionGroupInfo(
1221 mPermissionGroups.get(name), flags);
1222 }
1223 }
1224
1225 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1226 synchronized (mPackages) {
1227 final int N = mPermissionGroups.size();
1228 ArrayList<PermissionGroupInfo> out
1229 = new ArrayList<PermissionGroupInfo>(N);
1230 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1231 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1232 }
1233 return out;
1234 }
1235 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1238 PackageSetting ps = mSettings.mPackages.get(packageName);
1239 if(ps != null) {
1240 if(ps.pkg == null) {
1241 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1242 if(pInfo != null) {
1243 return pInfo.applicationInfo;
1244 }
1245 return null;
1246 }
1247 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1248 }
1249 return null;
1250 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1253 PackageSetting ps = mSettings.mPackages.get(packageName);
1254 if(ps != null) {
1255 if(ps.pkg == null) {
1256 ps.pkg = new PackageParser.Package(packageName);
1257 ps.pkg.applicationInfo.packageName = packageName;
1258 }
1259 return generatePackageInfo(ps.pkg, flags);
1260 }
1261 return null;
1262 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1265 synchronized (mPackages) {
1266 PackageParser.Package p = mPackages.get(packageName);
1267 if (Config.LOGV) Log.v(
1268 TAG, "getApplicationInfo " + packageName
1269 + ": " + p);
1270 if (p != null) {
1271 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001272 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 }
1274 if ("android".equals(packageName)||"system".equals(packageName)) {
1275 return mAndroidApplication;
1276 }
1277 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1278 return generateApplicationInfoFromSettingsLP(packageName, flags);
1279 }
1280 }
1281 return null;
1282 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001283
1284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1286 mContext.enforceCallingOrSelfPermission(
1287 android.Manifest.permission.CLEAR_APP_CACHE, null);
1288 // Queue up an async operation since clearing cache may take a little while.
1289 mHandler.post(new Runnable() {
1290 public void run() {
1291 mHandler.removeCallbacks(this);
1292 int retCode = -1;
1293 if (mInstaller != null) {
1294 retCode = mInstaller.freeCache(freeStorageSize);
1295 if (retCode < 0) {
1296 Log.w(TAG, "Couldn't clear application caches");
1297 }
1298 } //end if mInstaller
1299 if (observer != null) {
1300 try {
1301 observer.onRemoveCompleted(null, (retCode >= 0));
1302 } catch (RemoteException e) {
1303 Log.w(TAG, "RemoveException when invoking call back");
1304 }
1305 }
1306 }
1307 });
1308 }
1309
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001310 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001311 mContext.enforceCallingOrSelfPermission(
1312 android.Manifest.permission.CLEAR_APP_CACHE, null);
1313 // Queue up an async operation since clearing cache may take a little while.
1314 mHandler.post(new Runnable() {
1315 public void run() {
1316 mHandler.removeCallbacks(this);
1317 int retCode = -1;
1318 if (mInstaller != null) {
1319 retCode = mInstaller.freeCache(freeStorageSize);
1320 if (retCode < 0) {
1321 Log.w(TAG, "Couldn't clear application caches");
1322 }
1323 }
1324 if(pi != null) {
1325 try {
1326 // Callback via pending intent
1327 int code = (retCode >= 0) ? 1 : 0;
1328 pi.sendIntent(null, code, null,
1329 null, null);
1330 } catch (SendIntentException e1) {
1331 Log.i(TAG, "Failed to send pending intent");
1332 }
1333 }
1334 }
1335 });
1336 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1339 synchronized (mPackages) {
1340 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001341
1342 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001344 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 }
1346 if (mResolveComponentName.equals(component)) {
1347 return mResolveActivity;
1348 }
1349 }
1350 return null;
1351 }
1352
1353 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1354 synchronized (mPackages) {
1355 PackageParser.Activity a = mReceivers.mActivities.get(component);
1356 if (Config.LOGV) Log.v(
1357 TAG, "getReceiverInfo " + component + ": " + a);
1358 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1359 return PackageParser.generateActivityInfo(a, flags);
1360 }
1361 }
1362 return null;
1363 }
1364
1365 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1366 synchronized (mPackages) {
1367 PackageParser.Service s = mServices.mServices.get(component);
1368 if (Config.LOGV) Log.v(
1369 TAG, "getServiceInfo " + component + ": " + s);
1370 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1371 return PackageParser.generateServiceInfo(s, flags);
1372 }
1373 }
1374 return null;
1375 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 public String[] getSystemSharedLibraryNames() {
1378 Set<String> libSet;
1379 synchronized (mPackages) {
1380 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001381 int size = libSet.size();
1382 if (size > 0) {
1383 String[] libs = new String[size];
1384 libSet.toArray(libs);
1385 return libs;
1386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001388 return null;
1389 }
1390
1391 public FeatureInfo[] getSystemAvailableFeatures() {
1392 Collection<FeatureInfo> featSet;
1393 synchronized (mPackages) {
1394 featSet = mAvailableFeatures.values();
1395 int size = featSet.size();
1396 if (size > 0) {
1397 FeatureInfo[] features = new FeatureInfo[size+1];
1398 featSet.toArray(features);
1399 FeatureInfo fi = new FeatureInfo();
1400 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1401 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1402 features[size] = fi;
1403 return features;
1404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 }
1406 return null;
1407 }
1408
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001409 public boolean hasSystemFeature(String name) {
1410 synchronized (mPackages) {
1411 return mAvailableFeatures.containsKey(name);
1412 }
1413 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 public int checkPermission(String permName, String pkgName) {
1416 synchronized (mPackages) {
1417 PackageParser.Package p = mPackages.get(pkgName);
1418 if (p != null && p.mExtras != null) {
1419 PackageSetting ps = (PackageSetting)p.mExtras;
1420 if (ps.sharedUser != null) {
1421 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1422 return PackageManager.PERMISSION_GRANTED;
1423 }
1424 } else if (ps.grantedPermissions.contains(permName)) {
1425 return PackageManager.PERMISSION_GRANTED;
1426 }
1427 }
1428 }
1429 return PackageManager.PERMISSION_DENIED;
1430 }
1431
1432 public int checkUidPermission(String permName, int uid) {
1433 synchronized (mPackages) {
1434 Object obj = mSettings.getUserIdLP(uid);
1435 if (obj != null) {
1436 if (obj instanceof SharedUserSetting) {
1437 SharedUserSetting sus = (SharedUserSetting)obj;
1438 if (sus.grantedPermissions.contains(permName)) {
1439 return PackageManager.PERMISSION_GRANTED;
1440 }
1441 } else if (obj instanceof PackageSetting) {
1442 PackageSetting ps = (PackageSetting)obj;
1443 if (ps.grantedPermissions.contains(permName)) {
1444 return PackageManager.PERMISSION_GRANTED;
1445 }
1446 }
1447 } else {
1448 HashSet<String> perms = mSystemPermissions.get(uid);
1449 if (perms != null && perms.contains(permName)) {
1450 return PackageManager.PERMISSION_GRANTED;
1451 }
1452 }
1453 }
1454 return PackageManager.PERMISSION_DENIED;
1455 }
1456
1457 private BasePermission findPermissionTreeLP(String permName) {
1458 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1459 if (permName.startsWith(bp.name) &&
1460 permName.length() > bp.name.length() &&
1461 permName.charAt(bp.name.length()) == '.') {
1462 return bp;
1463 }
1464 }
1465 return null;
1466 }
1467
1468 private BasePermission checkPermissionTreeLP(String permName) {
1469 if (permName != null) {
1470 BasePermission bp = findPermissionTreeLP(permName);
1471 if (bp != null) {
1472 if (bp.uid == Binder.getCallingUid()) {
1473 return bp;
1474 }
1475 throw new SecurityException("Calling uid "
1476 + Binder.getCallingUid()
1477 + " is not allowed to add to permission tree "
1478 + bp.name + " owned by uid " + bp.uid);
1479 }
1480 }
1481 throw new SecurityException("No permission tree found for " + permName);
1482 }
1483
1484 public boolean addPermission(PermissionInfo info) {
1485 synchronized (mPackages) {
1486 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1487 throw new SecurityException("Label must be specified in permission");
1488 }
1489 BasePermission tree = checkPermissionTreeLP(info.name);
1490 BasePermission bp = mSettings.mPermissions.get(info.name);
1491 boolean added = bp == null;
1492 if (added) {
1493 bp = new BasePermission(info.name, tree.sourcePackage,
1494 BasePermission.TYPE_DYNAMIC);
1495 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1496 throw new SecurityException(
1497 "Not allowed to modify non-dynamic permission "
1498 + info.name);
1499 }
1500 bp.perm = new PackageParser.Permission(tree.perm.owner,
1501 new PermissionInfo(info));
1502 bp.perm.info.packageName = tree.perm.info.packageName;
1503 bp.uid = tree.uid;
1504 if (added) {
1505 mSettings.mPermissions.put(info.name, bp);
1506 }
1507 mSettings.writeLP();
1508 return added;
1509 }
1510 }
1511
1512 public void removePermission(String name) {
1513 synchronized (mPackages) {
1514 checkPermissionTreeLP(name);
1515 BasePermission bp = mSettings.mPermissions.get(name);
1516 if (bp != null) {
1517 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1518 throw new SecurityException(
1519 "Not allowed to modify non-dynamic permission "
1520 + name);
1521 }
1522 mSettings.mPermissions.remove(name);
1523 mSettings.writeLP();
1524 }
1525 }
1526 }
1527
Dianne Hackborn854060af2009-07-09 18:14:31 -07001528 public boolean isProtectedBroadcast(String actionName) {
1529 synchronized (mPackages) {
1530 return mProtectedBroadcasts.contains(actionName);
1531 }
1532 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 public int checkSignatures(String pkg1, String pkg2) {
1535 synchronized (mPackages) {
1536 PackageParser.Package p1 = mPackages.get(pkg1);
1537 PackageParser.Package p2 = mPackages.get(pkg2);
1538 if (p1 == null || p1.mExtras == null
1539 || p2 == null || p2.mExtras == null) {
1540 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1541 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001542 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 }
1544 }
1545
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001546 public int checkUidSignatures(int uid1, int uid2) {
1547 synchronized (mPackages) {
1548 Signature[] s1;
1549 Signature[] s2;
1550 Object obj = mSettings.getUserIdLP(uid1);
1551 if (obj != null) {
1552 if (obj instanceof SharedUserSetting) {
1553 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1554 } else if (obj instanceof PackageSetting) {
1555 s1 = ((PackageSetting)obj).signatures.mSignatures;
1556 } else {
1557 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1558 }
1559 } else {
1560 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1561 }
1562 obj = mSettings.getUserIdLP(uid2);
1563 if (obj != null) {
1564 if (obj instanceof SharedUserSetting) {
1565 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1566 } else if (obj instanceof PackageSetting) {
1567 s2 = ((PackageSetting)obj).signatures.mSignatures;
1568 } else {
1569 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1570 }
1571 } else {
1572 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1573 }
1574 return checkSignaturesLP(s1, s2);
1575 }
1576 }
1577
1578 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1579 if (s1 == null) {
1580 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1582 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1583 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001584 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1586 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001587 final int N1 = s1.length;
1588 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 for (int i=0; i<N1; i++) {
1590 boolean match = false;
1591 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001592 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 match = true;
1594 break;
1595 }
1596 }
1597 if (!match) {
1598 return PackageManager.SIGNATURE_NO_MATCH;
1599 }
1600 }
1601 return PackageManager.SIGNATURE_MATCH;
1602 }
1603
1604 public String[] getPackagesForUid(int uid) {
1605 synchronized (mPackages) {
1606 Object obj = mSettings.getUserIdLP(uid);
1607 if (obj instanceof SharedUserSetting) {
1608 SharedUserSetting sus = (SharedUserSetting)obj;
1609 final int N = sus.packages.size();
1610 String[] res = new String[N];
1611 Iterator<PackageSetting> it = sus.packages.iterator();
1612 int i=0;
1613 while (it.hasNext()) {
1614 res[i++] = it.next().name;
1615 }
1616 return res;
1617 } else if (obj instanceof PackageSetting) {
1618 PackageSetting ps = (PackageSetting)obj;
1619 return new String[] { ps.name };
1620 }
1621 }
1622 return null;
1623 }
1624
1625 public String getNameForUid(int uid) {
1626 synchronized (mPackages) {
1627 Object obj = mSettings.getUserIdLP(uid);
1628 if (obj instanceof SharedUserSetting) {
1629 SharedUserSetting sus = (SharedUserSetting)obj;
1630 return sus.name + ":" + sus.userId;
1631 } else if (obj instanceof PackageSetting) {
1632 PackageSetting ps = (PackageSetting)obj;
1633 return ps.name;
1634 }
1635 }
1636 return null;
1637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 public int getUidForSharedUser(String sharedUserName) {
1640 if(sharedUserName == null) {
1641 return -1;
1642 }
1643 synchronized (mPackages) {
1644 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1645 if(suid == null) {
1646 return -1;
1647 }
1648 return suid.userId;
1649 }
1650 }
1651
1652 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1653 int flags) {
1654 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001655 return chooseBestActivity(intent, resolvedType, flags, query);
1656 }
1657
Mihai Predaeae850c2009-05-13 10:13:48 +02001658 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1659 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 if (query != null) {
1661 final int N = query.size();
1662 if (N == 1) {
1663 return query.get(0);
1664 } else if (N > 1) {
1665 // If there is more than one activity with the same priority,
1666 // then let the user decide between them.
1667 ResolveInfo r0 = query.get(0);
1668 ResolveInfo r1 = query.get(1);
1669 if (false) {
1670 System.out.println(r0.activityInfo.name +
1671 "=" + r0.priority + " vs " +
1672 r1.activityInfo.name +
1673 "=" + r1.priority);
1674 }
1675 // If the first activity has a higher priority, or a different
1676 // default, then it is always desireable to pick it.
1677 if (r0.priority != r1.priority
1678 || r0.preferredOrder != r1.preferredOrder
1679 || r0.isDefault != r1.isDefault) {
1680 return query.get(0);
1681 }
1682 // If we have saved a preference for a preferred activity for
1683 // this Intent, use that.
1684 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1685 flags, query, r0.priority);
1686 if (ri != null) {
1687 return ri;
1688 }
1689 return mResolveInfo;
1690 }
1691 }
1692 return null;
1693 }
1694
1695 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1696 int flags, List<ResolveInfo> query, int priority) {
1697 synchronized (mPackages) {
1698 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1699 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001700 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1702 if (prefs != null && prefs.size() > 0) {
1703 // First figure out how good the original match set is.
1704 // We will only allow preferred activities that came
1705 // from the same match quality.
1706 int match = 0;
1707 final int N = query.size();
1708 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1709 for (int j=0; j<N; j++) {
1710 ResolveInfo ri = query.get(j);
1711 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1712 + ": 0x" + Integer.toHexString(match));
1713 if (ri.match > match) match = ri.match;
1714 }
1715 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1716 + Integer.toHexString(match));
1717 match &= IntentFilter.MATCH_CATEGORY_MASK;
1718 final int M = prefs.size();
1719 for (int i=0; i<M; i++) {
1720 PreferredActivity pa = prefs.get(i);
1721 if (pa.mMatch != match) {
1722 continue;
1723 }
1724 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1725 if (DEBUG_PREFERRED) {
1726 Log.v(TAG, "Got preferred activity:");
1727 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1728 }
1729 if (ai != null) {
1730 for (int j=0; j<N; j++) {
1731 ResolveInfo ri = query.get(j);
1732 if (!ri.activityInfo.applicationInfo.packageName
1733 .equals(ai.applicationInfo.packageName)) {
1734 continue;
1735 }
1736 if (!ri.activityInfo.name.equals(ai.name)) {
1737 continue;
1738 }
1739
1740 // Okay we found a previously set preferred app.
1741 // If the result set is different from when this
1742 // was created, we need to clear it and re-ask the
1743 // user their preference.
1744 if (!pa.sameSet(query, priority)) {
1745 Log.i(TAG, "Result set changed, dropping preferred activity for "
1746 + intent + " type " + resolvedType);
1747 mSettings.mPreferredActivities.removeFilter(pa);
1748 return null;
1749 }
1750
1751 // Yay!
1752 return ri;
1753 }
1754 }
1755 }
1756 }
1757 }
1758 return null;
1759 }
1760
1761 public List<ResolveInfo> queryIntentActivities(Intent intent,
1762 String resolvedType, int flags) {
1763 ComponentName comp = intent.getComponent();
1764 if (comp != null) {
1765 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1766 ActivityInfo ai = getActivityInfo(comp, flags);
1767 if (ai != null) {
1768 ResolveInfo ri = new ResolveInfo();
1769 ri.activityInfo = ai;
1770 list.add(ri);
1771 }
1772 return list;
1773 }
1774
1775 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07001776 String pkgName = intent.getPackage();
1777 if (pkgName == null) {
1778 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1779 resolvedType, flags);
1780 }
1781 PackageParser.Package pkg = mPackages.get(pkgName);
1782 if (pkg != null) {
1783 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1784 resolvedType, flags, pkg.activities);
1785 }
1786 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 }
1788 }
1789
1790 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1791 Intent[] specifics, String[] specificTypes, Intent intent,
1792 String resolvedType, int flags) {
1793 final String resultsAction = intent.getAction();
1794
1795 List<ResolveInfo> results = queryIntentActivities(
1796 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1797 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1798
1799 int specificsPos = 0;
1800 int N;
1801
1802 // todo: note that the algorithm used here is O(N^2). This
1803 // isn't a problem in our current environment, but if we start running
1804 // into situations where we have more than 5 or 10 matches then this
1805 // should probably be changed to something smarter...
1806
1807 // First we go through and resolve each of the specific items
1808 // that were supplied, taking care of removing any corresponding
1809 // duplicate items in the generic resolve list.
1810 if (specifics != null) {
1811 for (int i=0; i<specifics.length; i++) {
1812 final Intent sintent = specifics[i];
1813 if (sintent == null) {
1814 continue;
1815 }
1816
1817 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1818 String action = sintent.getAction();
1819 if (resultsAction != null && resultsAction.equals(action)) {
1820 // If this action was explicitly requested, then don't
1821 // remove things that have it.
1822 action = null;
1823 }
1824 ComponentName comp = sintent.getComponent();
1825 ResolveInfo ri = null;
1826 ActivityInfo ai = null;
1827 if (comp == null) {
1828 ri = resolveIntent(
1829 sintent,
1830 specificTypes != null ? specificTypes[i] : null,
1831 flags);
1832 if (ri == null) {
1833 continue;
1834 }
1835 if (ri == mResolveInfo) {
1836 // ACK! Must do something better with this.
1837 }
1838 ai = ri.activityInfo;
1839 comp = new ComponentName(ai.applicationInfo.packageName,
1840 ai.name);
1841 } else {
1842 ai = getActivityInfo(comp, flags);
1843 if (ai == null) {
1844 continue;
1845 }
1846 }
1847
1848 // Look for any generic query activities that are duplicates
1849 // of this specific one, and remove them from the results.
1850 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1851 N = results.size();
1852 int j;
1853 for (j=specificsPos; j<N; j++) {
1854 ResolveInfo sri = results.get(j);
1855 if ((sri.activityInfo.name.equals(comp.getClassName())
1856 && sri.activityInfo.applicationInfo.packageName.equals(
1857 comp.getPackageName()))
1858 || (action != null && sri.filter.matchAction(action))) {
1859 results.remove(j);
1860 if (Config.LOGV) Log.v(
1861 TAG, "Removing duplicate item from " + j
1862 + " due to specific " + specificsPos);
1863 if (ri == null) {
1864 ri = sri;
1865 }
1866 j--;
1867 N--;
1868 }
1869 }
1870
1871 // Add this specific item to its proper place.
1872 if (ri == null) {
1873 ri = new ResolveInfo();
1874 ri.activityInfo = ai;
1875 }
1876 results.add(specificsPos, ri);
1877 ri.specificIndex = i;
1878 specificsPos++;
1879 }
1880 }
1881
1882 // Now we go through the remaining generic results and remove any
1883 // duplicate actions that are found here.
1884 N = results.size();
1885 for (int i=specificsPos; i<N-1; i++) {
1886 final ResolveInfo rii = results.get(i);
1887 if (rii.filter == null) {
1888 continue;
1889 }
1890
1891 // Iterate over all of the actions of this result's intent
1892 // filter... typically this should be just one.
1893 final Iterator<String> it = rii.filter.actionsIterator();
1894 if (it == null) {
1895 continue;
1896 }
1897 while (it.hasNext()) {
1898 final String action = it.next();
1899 if (resultsAction != null && resultsAction.equals(action)) {
1900 // If this action was explicitly requested, then don't
1901 // remove things that have it.
1902 continue;
1903 }
1904 for (int j=i+1; j<N; j++) {
1905 final ResolveInfo rij = results.get(j);
1906 if (rij.filter != null && rij.filter.hasAction(action)) {
1907 results.remove(j);
1908 if (Config.LOGV) Log.v(
1909 TAG, "Removing duplicate item from " + j
1910 + " due to action " + action + " at " + i);
1911 j--;
1912 N--;
1913 }
1914 }
1915 }
1916
1917 // If the caller didn't request filter information, drop it now
1918 // so we don't have to marshall/unmarshall it.
1919 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1920 rii.filter = null;
1921 }
1922 }
1923
1924 // Filter out the caller activity if so requested.
1925 if (caller != null) {
1926 N = results.size();
1927 for (int i=0; i<N; i++) {
1928 ActivityInfo ainfo = results.get(i).activityInfo;
1929 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1930 && caller.getClassName().equals(ainfo.name)) {
1931 results.remove(i);
1932 break;
1933 }
1934 }
1935 }
1936
1937 // If the caller didn't request filter information,
1938 // drop them now so we don't have to
1939 // marshall/unmarshall it.
1940 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1941 N = results.size();
1942 for (int i=0; i<N; i++) {
1943 results.get(i).filter = null;
1944 }
1945 }
1946
1947 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1948 return results;
1949 }
1950
1951 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1952 String resolvedType, int flags) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07001953 ComponentName comp = intent.getComponent();
1954 if (comp != null) {
1955 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1956 ActivityInfo ai = getReceiverInfo(comp, flags);
1957 if (ai != null) {
1958 ResolveInfo ri = new ResolveInfo();
1959 ri.activityInfo = ai;
1960 list.add(ri);
1961 }
1962 return list;
1963 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07001966 String pkgName = intent.getPackage();
1967 if (pkgName == null) {
1968 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1969 resolvedType, flags);
1970 }
1971 PackageParser.Package pkg = mPackages.get(pkgName);
1972 if (pkg != null) {
1973 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1974 resolvedType, flags, pkg.receivers);
1975 }
1976 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 }
1978 }
1979
1980 public ResolveInfo resolveService(Intent intent, String resolvedType,
1981 int flags) {
1982 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1983 flags);
1984 if (query != null) {
1985 if (query.size() >= 1) {
1986 // If there is more than one service with the same priority,
1987 // just arbitrarily pick the first one.
1988 return query.get(0);
1989 }
1990 }
1991 return null;
1992 }
1993
1994 public List<ResolveInfo> queryIntentServices(Intent intent,
1995 String resolvedType, int flags) {
1996 ComponentName comp = intent.getComponent();
1997 if (comp != null) {
1998 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1999 ServiceInfo si = getServiceInfo(comp, flags);
2000 if (si != null) {
2001 ResolveInfo ri = new ResolveInfo();
2002 ri.serviceInfo = si;
2003 list.add(ri);
2004 }
2005 return list;
2006 }
2007
2008 synchronized (mPackages) {
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07002009 String pkgName = intent.getPackage();
2010 if (pkgName == null) {
2011 return (List<ResolveInfo>)mServices.queryIntent(intent,
2012 resolvedType, flags);
2013 }
2014 PackageParser.Package pkg = mPackages.get(pkgName);
2015 if (pkg != null) {
2016 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2017 resolvedType, flags, pkg.services);
2018 }
2019 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 }
2021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 public List<PackageInfo> getInstalledPackages(int flags) {
2024 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2025
2026 synchronized (mPackages) {
2027 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2028 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2029 while (i.hasNext()) {
2030 final PackageSetting ps = i.next();
2031 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2032 if(psPkg != null) {
2033 finalList.add(psPkg);
2034 }
2035 }
2036 }
2037 else {
2038 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2039 while (i.hasNext()) {
2040 final PackageParser.Package p = i.next();
2041 if (p.applicationInfo != null) {
2042 PackageInfo pi = generatePackageInfo(p, flags);
2043 if(pi != null) {
2044 finalList.add(pi);
2045 }
2046 }
2047 }
2048 }
2049 }
2050 return finalList;
2051 }
2052
2053 public List<ApplicationInfo> getInstalledApplications(int flags) {
2054 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2055 synchronized(mPackages) {
2056 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2057 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2058 while (i.hasNext()) {
2059 final PackageSetting ps = i.next();
2060 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2061 if(ai != null) {
2062 finalList.add(ai);
2063 }
2064 }
2065 }
2066 else {
2067 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2068 while (i.hasNext()) {
2069 final PackageParser.Package p = i.next();
2070 if (p.applicationInfo != null) {
2071 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2072 if(ai != null) {
2073 finalList.add(ai);
2074 }
2075 }
2076 }
2077 }
2078 }
2079 return finalList;
2080 }
2081
2082 public List<ApplicationInfo> getPersistentApplications(int flags) {
2083 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2084
2085 synchronized (mPackages) {
2086 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2087 while (i.hasNext()) {
2088 PackageParser.Package p = i.next();
2089 if (p.applicationInfo != null
2090 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2091 && (!mSafeMode || (p.applicationInfo.flags
2092 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2093 finalList.add(p.applicationInfo);
2094 }
2095 }
2096 }
2097
2098 return finalList;
2099 }
2100
2101 public ProviderInfo resolveContentProvider(String name, int flags) {
2102 synchronized (mPackages) {
2103 final PackageParser.Provider provider = mProviders.get(name);
2104 return provider != null
2105 && mSettings.isEnabledLP(provider.info, flags)
2106 && (!mSafeMode || (provider.info.applicationInfo.flags
2107 &ApplicationInfo.FLAG_SYSTEM) != 0)
2108 ? PackageParser.generateProviderInfo(provider, flags)
2109 : null;
2110 }
2111 }
2112
Fred Quintana718d8a22009-04-29 17:53:20 -07002113 /**
2114 * @deprecated
2115 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 public void querySyncProviders(List outNames, List outInfo) {
2117 synchronized (mPackages) {
2118 Iterator<Map.Entry<String, PackageParser.Provider>> i
2119 = mProviders.entrySet().iterator();
2120
2121 while (i.hasNext()) {
2122 Map.Entry<String, PackageParser.Provider> entry = i.next();
2123 PackageParser.Provider p = entry.getValue();
2124
2125 if (p.syncable
2126 && (!mSafeMode || (p.info.applicationInfo.flags
2127 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2128 outNames.add(entry.getKey());
2129 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2130 }
2131 }
2132 }
2133 }
2134
2135 public List<ProviderInfo> queryContentProviders(String processName,
2136 int uid, int flags) {
2137 ArrayList<ProviderInfo> finalList = null;
2138
2139 synchronized (mPackages) {
2140 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2141 while (i.hasNext()) {
2142 PackageParser.Provider p = i.next();
2143 if (p.info.authority != null
2144 && (processName == null ||
2145 (p.info.processName.equals(processName)
2146 && p.info.applicationInfo.uid == uid))
2147 && mSettings.isEnabledLP(p.info, flags)
2148 && (!mSafeMode || (p.info.applicationInfo.flags
2149 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2150 if (finalList == null) {
2151 finalList = new ArrayList<ProviderInfo>(3);
2152 }
2153 finalList.add(PackageParser.generateProviderInfo(p,
2154 flags));
2155 }
2156 }
2157 }
2158
2159 if (finalList != null) {
2160 Collections.sort(finalList, mProviderInitOrderSorter);
2161 }
2162
2163 return finalList;
2164 }
2165
2166 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2167 int flags) {
2168 synchronized (mPackages) {
2169 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2170 return PackageParser.generateInstrumentationInfo(i, flags);
2171 }
2172 }
2173
2174 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2175 int flags) {
2176 ArrayList<InstrumentationInfo> finalList =
2177 new ArrayList<InstrumentationInfo>();
2178
2179 synchronized (mPackages) {
2180 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2181 while (i.hasNext()) {
2182 PackageParser.Instrumentation p = i.next();
2183 if (targetPackage == null
2184 || targetPackage.equals(p.info.targetPackage)) {
2185 finalList.add(PackageParser.generateInstrumentationInfo(p,
2186 flags));
2187 }
2188 }
2189 }
2190
2191 return finalList;
2192 }
2193
2194 private void scanDirLI(File dir, int flags, int scanMode) {
2195 Log.d(TAG, "Scanning app dir " + dir);
2196
2197 String[] files = dir.list();
2198
2199 int i;
2200 for (i=0; i<files.length; i++) {
2201 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002202 if (!isPackageFilename(files[i])) {
2203 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002204 continue;
2205 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002206 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002208 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002209 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2210 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002211 // Delete the apk
2212 Log.w(TAG, "Cleaning up failed install of " + file);
2213 file.delete();
2214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 }
2216 }
2217
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002218 private static File getSettingsProblemFile() {
2219 File dataDir = Environment.getDataDirectory();
2220 File systemDir = new File(dataDir, "system");
2221 File fname = new File(systemDir, "uiderrors.txt");
2222 return fname;
2223 }
2224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 private static void reportSettingsProblem(int priority, String msg) {
2226 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002227 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 FileOutputStream out = new FileOutputStream(fname, true);
2229 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002230 SimpleDateFormat formatter = new SimpleDateFormat();
2231 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2232 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 pw.close();
2234 FileUtils.setPermissions(
2235 fname.toString(),
2236 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2237 -1, -1);
2238 } catch (java.io.IOException e) {
2239 }
2240 Log.println(priority, TAG, msg);
2241 }
2242
2243 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2244 PackageParser.Package pkg, File srcFile, int parseFlags) {
2245 if (GET_CERTIFICATES) {
2246 if (ps == null || !ps.codePath.equals(srcFile)
2247 || ps.getTimeStamp() != srcFile.lastModified()) {
2248 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2249 if (!pp.collectCertificates(pkg, parseFlags)) {
2250 mLastScanError = pp.getParseError();
2251 return false;
2252 }
2253 }
2254 }
2255 return true;
2256 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 /*
2259 * Scan a package and return the newly parsed package.
2260 * Returns null in case of errors and the error code is stored in mLastScanError
2261 */
2262 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002263 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002265 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002267 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002270 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 if (pkg == null) {
2272 mLastScanError = pp.getParseError();
2273 return null;
2274 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002275 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 PackageSetting updatedPkg;
2277 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002278 // Look to see if we already know about this package.
2279 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
2280 if (oldName != null && oldName.equals(pkg.mOriginalPackage)) {
2281 // This package has been renamed to its original name. Let's
2282 // use that.
2283 ps = mSettings.peekPackageLP(pkg.mOriginalPackage);
2284 }
2285 // If there was no original package, see one for the real package name.
2286 if (ps == null) {
2287 ps = mSettings.peekPackageLP(pkg.packageName);
2288 }
2289 // Check to see if this package could be hiding/updating a system
2290 // package. Must look for it either under the original or real
2291 // package name depending on our state.
2292 updatedPkg = mSettings.mDisabledSysPackages.get(
2293 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002295 // First check if this is a system package that may involve an update
2296 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2297 if (!ps.codePath.equals(scanFile)) {
2298 // The path has changed from what was last scanned... check the
2299 // version of the new path against what we have stored to determine
2300 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002301 if (pkg.mVersionCode < ps.versionCode) {
2302 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002303 // Ignore entry. Skip it.
2304 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2305 + "ignored: updated version " + ps.versionCode
2306 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002307 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2308 return null;
2309 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002310 // The current app on the system partion is better than
2311 // what we have updated to on the data partition; switch
2312 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002313 // At this point, its safely assumed that package installation for
2314 // apps in system partition will go through. If not there won't be a working
2315 // version of the app
2316 synchronized (mPackages) {
2317 // Just remove the loaded entries from package lists.
2318 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002319 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002320 Log.w(TAG, "Package " + ps.name + " at " + scanFile
2321 + "reverting from " + ps.codePathString
2322 + ": new version " + pkg.mVersionCode
2323 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002324 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2325 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002326 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 }
2329 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002330 if (updatedPkg != null) {
2331 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2332 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2333 }
2334 // Verify certificates against what was last scanned
2335 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2336 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2337 return null;
2338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 // The apk is forward locked (not public) if its code and resources
2340 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002341 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002343 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002344 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002345
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002346 String codePath = null;
2347 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002348 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2349 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002350 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002351 } else {
2352 // Should not happen at all. Just log an error.
2353 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2354 }
2355 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002356 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002357 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002358 codePath = pkg.mScanPath;
2359 // Set application objects path explicitly.
2360 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002362 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 }
2364
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002365 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2366 String destCodePath, String destResPath) {
2367 pkg.mPath = pkg.mScanPath = destCodePath;
2368 pkg.applicationInfo.sourceDir = destCodePath;
2369 pkg.applicationInfo.publicSourceDir = destResPath;
2370 }
2371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 private static String fixProcessName(String defProcessName,
2373 String processName, int uid) {
2374 if (processName == null) {
2375 return defProcessName;
2376 }
2377 return processName;
2378 }
2379
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002380 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2382 if (pkg.mSignatures != null) {
2383 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2384 updateSignature)) {
2385 Log.e(TAG, "Package " + pkg.packageName
2386 + " signatures do not match the previously installed version; ignoring!");
2387 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2388 return false;
2389 }
2390
2391 if (pkgSetting.sharedUser != null) {
2392 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2393 pkg.mSignatures, updateSignature)) {
2394 Log.e(TAG, "Package " + pkg.packageName
2395 + " has no signatures that match those in shared user "
2396 + pkgSetting.sharedUser.name + "; ignoring!");
2397 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2398 return false;
2399 }
2400 }
2401 } else {
2402 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2403 }
2404 return true;
2405 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002406
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002407 public boolean performDexOpt(String packageName) {
2408 if (!mNoDexOpt) {
2409 return false;
2410 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002411
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002412 PackageParser.Package p;
2413 synchronized (mPackages) {
2414 p = mPackages.get(packageName);
2415 if (p == null || p.mDidDexOpt) {
2416 return false;
2417 }
2418 }
2419 synchronized (mInstallLock) {
2420 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2421 }
2422 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002423
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002424 static final int DEX_OPT_SKIPPED = 0;
2425 static final int DEX_OPT_PERFORMED = 1;
2426 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002427
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002428 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2429 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002430 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002431 String path = pkg.mScanPath;
2432 int ret = 0;
2433 try {
2434 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002435 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002436 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002437 pkg.mDidDexOpt = true;
2438 performed = true;
2439 }
2440 } catch (FileNotFoundException e) {
2441 Log.w(TAG, "Apk not found for dexopt: " + path);
2442 ret = -1;
2443 } catch (IOException e) {
2444 Log.w(TAG, "Exception reading apk: " + path, e);
2445 ret = -1;
2446 }
2447 if (ret < 0) {
2448 //error from installer
2449 return DEX_OPT_FAILED;
2450 }
2451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002452
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002453 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2454 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002455
2456 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2457 return Environment.isEncryptedFilesystemEnabled() &&
2458 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2459 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002460
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002461 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2462 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2463 Log.w(TAG, "Unable to update from " + oldPkg.name
2464 + " to " + newPkg.packageName
2465 + ": old package not in system partition");
2466 return false;
2467 } else if (mPackages.get(oldPkg.name) != null) {
2468 Log.w(TAG, "Unable to update from " + oldPkg.name
2469 + " to " + newPkg.packageName
2470 + ": old package still exists");
2471 return false;
2472 }
2473 return true;
2474 }
2475
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002476 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2477 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002478 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002479 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2480 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002481 // Bail out. The resource and code paths haven't been set.
2482 Log.w(TAG, " Code and resource paths haven't been set correctly");
2483 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2484 return null;
2485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 mScanningPath = scanFile;
2487 if (pkg == null) {
2488 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2489 return null;
2490 }
2491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2493 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2494 }
2495
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002496 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 synchronized (mPackages) {
2498 if (mAndroidApplication != null) {
2499 Log.w(TAG, "*************************************************");
2500 Log.w(TAG, "Core android package being redefined. Skipping.");
2501 Log.w(TAG, " file=" + mScanningPath);
2502 Log.w(TAG, "*************************************************");
2503 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2504 return null;
2505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 // Set up information for our fall-back user intent resolution
2508 // activity.
2509 mPlatformPackage = pkg;
2510 pkg.mVersionCode = mSdkVersion;
2511 mAndroidApplication = pkg.applicationInfo;
2512 mResolveActivity.applicationInfo = mAndroidApplication;
2513 mResolveActivity.name = ResolverActivity.class.getName();
2514 mResolveActivity.packageName = mAndroidApplication.packageName;
2515 mResolveActivity.processName = mAndroidApplication.processName;
2516 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2517 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2518 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2519 mResolveActivity.exported = true;
2520 mResolveActivity.enabled = true;
2521 mResolveInfo.activityInfo = mResolveActivity;
2522 mResolveInfo.priority = 0;
2523 mResolveInfo.preferredOrder = 0;
2524 mResolveInfo.match = 0;
2525 mResolveComponentName = new ComponentName(
2526 mAndroidApplication.packageName, mResolveActivity.name);
2527 }
2528 }
2529
2530 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002531 TAG, "Scanning package " + pkg.packageName);
2532 if (mPackages.containsKey(pkg.packageName)
2533 || mSharedLibraries.containsKey(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 Log.w(TAG, "*************************************************");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002535 Log.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 + " already installed. Skipping duplicate.");
2537 Log.w(TAG, "*************************************************");
2538 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2539 return null;
2540 }
2541
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002542 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002543 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2544 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 SharedUserSetting suid = null;
2547 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002550
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002551 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2552 // Only system apps can use these features.
2553 pkg.mOriginalPackage = null;
2554 pkg.mRealPackage = null;
2555 pkg.mAdoptPermissions = null;
2556 }
2557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 synchronized (mPackages) {
2559 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002560 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2561 if (mTmpSharedLibraries == null ||
2562 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2563 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2564 }
2565 int num = 0;
2566 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2567 for (int i=0; i<N; i++) {
2568 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 if (file == null) {
2570 Log.e(TAG, "Package " + pkg.packageName
2571 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002572 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2574 return null;
2575 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002576 mTmpSharedLibraries[num] = file;
2577 num++;
2578 }
2579 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2580 for (int i=0; i<N; i++) {
2581 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2582 if (file == null) {
2583 Log.w(TAG, "Package " + pkg.packageName
2584 + " desires unavailable shared library "
2585 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2586 } else {
2587 mTmpSharedLibraries[num] = file;
2588 num++;
2589 }
2590 }
2591 if (num > 0) {
2592 pkg.usesLibraryFiles = new String[num];
2593 System.arraycopy(mTmpSharedLibraries, 0,
2594 pkg.usesLibraryFiles, 0, num);
2595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002596
Dianne Hackborn49237342009-08-27 20:08:01 -07002597 if (pkg.reqFeatures != null) {
2598 N = pkg.reqFeatures.size();
2599 for (int i=0; i<N; i++) {
2600 FeatureInfo fi = pkg.reqFeatures.get(i);
2601 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2602 // Don't care.
2603 continue;
2604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002605
Dianne Hackborn49237342009-08-27 20:08:01 -07002606 if (fi.name != null) {
2607 if (mAvailableFeatures.get(fi.name) == null) {
2608 Log.e(TAG, "Package " + pkg.packageName
2609 + " requires unavailable feature "
2610 + fi.name + "; failing!");
2611 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2612 return null;
2613 }
2614 }
2615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 }
2617 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 if (pkg.mSharedUserId != null) {
2620 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2621 pkg.applicationInfo.flags, true);
2622 if (suid == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002623 Log.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 + " for shared user failed");
2625 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2626 return null;
2627 }
2628 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2629 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2630 + suid.userId + "): packages=" + suid.packages);
2631 }
2632 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002633
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002634 if (false) {
2635 if (pkg.mOriginalPackage != null) {
2636 Log.w(TAG, "WAITING FOR DEBUGGER");
2637 Debug.waitForDebugger();
2638 Log.i(TAG, "Package " + pkg.packageName + " from original package"
2639 + pkg.mOriginalPackage);
2640 }
2641 }
2642
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002643 // Check if we are renaming from an original package name.
2644 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002645 String realName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002646 if (pkg.mOriginalPackage != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002647 // This package may need to be renamed to a previously
2648 // installed name. Let's check on that...
2649 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
2650 if (pkg.mOriginalPackage.equals(renamed)) {
2651 // This package had originally been installed as the
2652 // original name, and we have already taken care of
2653 // transitioning to the new one. Just update the new
2654 // one to continue using the old name.
2655 realName = pkg.mRealPackage;
2656 if (!pkg.packageName.equals(renamed)) {
2657 // Callers into this function may have already taken
2658 // care of renaming the package; only do it here if
2659 // it is not already done.
2660 pkg.setPackageName(renamed);
2661 }
2662
2663 } else if ((origPackage
2664 = mSettings.peekPackageLP(pkg.mOriginalPackage)) != null) {
2665 // We do have the package already installed under its
2666 // original name... should we use it?
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002667 if (!verifyPackageUpdate(origPackage, pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002668 // New package is not compatible with original.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002669 origPackage = null;
2670 } else if (origPackage.sharedUser != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002671 // Make sure uid is compatible between packages.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002672 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2673 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2674 + " to " + pkg.packageName + ": old uid "
2675 + origPackage.sharedUser.name
2676 + " differs from " + pkg.mSharedUserId);
2677 origPackage = null;
2678 }
2679 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002680 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2681 + pkg.packageName + " to old name " + origPackage.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002682 }
2683 }
2684 }
2685
2686 if (mTransferedPackages.contains(pkg.packageName)) {
2687 Log.w(TAG, "Package " + pkg.packageName
2688 + " was transferred to another, but its .apk remains");
2689 }
2690
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002691 // Just create the setting, don't add it yet. For already existing packages
2692 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002693 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 destResourceFile, pkg.applicationInfo.flags, true, false);
2695 if (pkgSetting == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002696 Log.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2698 return null;
2699 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002700
2701 if (pkgSetting.origPackage != null) {
2702 // If we are first transitioning from an original package,
2703 // fix up the new package's name now. We need to do this after
2704 // looking up the package under its new name, so getPackageLP
2705 // can take care of fiddling things correctly.
2706 pkg.setPackageName(origPackage.name);
2707
2708 // File a report about this.
2709 String msg = "New package " + pkgSetting.realName
2710 + " renamed to replace old package " + pkgSetting.name;
2711 reportSettingsProblem(Log.WARN, msg);
2712
2713 // Make a note of it.
2714 mTransferedPackages.add(origPackage.name);
2715
2716 // No longer need to retain this.
2717 pkgSetting.origPackage = null;
2718 }
2719
2720 if (realName != null) {
2721 // Make a note of it.
2722 mTransferedPackages.add(pkg.packageName);
2723 }
2724
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002725 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 pkg.applicationInfo.uid = pkgSetting.userId;
2730 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002731
2732 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2734 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2735 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2736 return null;
2737 }
2738 // The signature has changed, but this package is in the system
2739 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002740 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 // However... if this package is part of a shared user, but it
2742 // doesn't match the signature of the shared user, let's fail.
2743 // What this means is that you can't change the signatures
2744 // associated with an overall shared user, which doesn't seem all
2745 // that unreasonable.
2746 if (pkgSetting.sharedUser != null) {
2747 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2748 pkg.mSignatures, false)) {
2749 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2750 return null;
2751 }
2752 }
2753 removeExisting = true;
2754 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002755
The Android Open Source Project10592532009-03-18 17:39:46 -07002756 // Verify that this new package doesn't have any content providers
2757 // that conflict with existing packages. Only do this if the
2758 // package isn't already installed, since we don't want to break
2759 // things that are installed.
2760 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2761 int N = pkg.providers.size();
2762 int i;
2763 for (i=0; i<N; i++) {
2764 PackageParser.Provider p = pkg.providers.get(i);
2765 String names[] = p.info.authority.split(";");
2766 for (int j = 0; j < names.length; j++) {
2767 if (mProviders.containsKey(names[j])) {
2768 PackageParser.Provider other = mProviders.get(names[j]);
2769 Log.w(TAG, "Can't install because provider name " + names[j] +
2770 " (in package " + pkg.applicationInfo.packageName +
2771 ") is already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002772 + ((other != null && other.getComponentName() != null)
2773 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project10592532009-03-18 17:39:46 -07002774 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2775 return null;
2776 }
2777 }
2778 }
2779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 }
2781
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002782 final String pkgName = pkg.packageName;
2783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002785 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002787 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 if (ret != 0) {
2789 String msg = "System package " + pkg.packageName
2790 + " could not have data directory erased after signature change.";
2791 reportSettingsProblem(Log.WARN, msg);
2792 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2793 return null;
2794 }
2795 }
2796 Log.w(TAG, "System package " + pkg.packageName
2797 + " signature changed: existing data removed.");
2798 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2799 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002800
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002801 if (pkg.mAdoptPermissions != null) {
2802 // This package wants to adopt ownership of permissions from
2803 // another package.
2804 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2805 String origName = pkg.mAdoptPermissions.get(i);
2806 PackageSetting orig = mSettings.peekPackageLP(origName);
2807 if (orig != null) {
2808 if (verifyPackageUpdate(orig, pkg)) {
2809 Log.i(TAG, "Adopting permissions from "
2810 + origName + " to " + pkg.packageName);
2811 mSettings.transferPermissions(origName, pkg.packageName);
2812 }
2813 }
2814 }
2815 }
2816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 long scanFileTime = scanFile.lastModified();
2818 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2819 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2820 pkg.applicationInfo.processName = fixProcessName(
2821 pkg.applicationInfo.packageName,
2822 pkg.applicationInfo.processName,
2823 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824
2825 File dataPath;
2826 if (mPlatformPackage == pkg) {
2827 // The system package is special.
2828 dataPath = new File (Environment.getDataDirectory(), "system");
2829 pkg.applicationInfo.dataDir = dataPath.getPath();
2830 } else {
2831 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002832 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2833 if (useEncryptedFSDir) {
2834 dataPath = new File(mSecureAppDataDir, pkgName);
2835 } else {
2836 dataPath = new File(mAppDataDir, pkgName);
2837 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002838
2839 boolean uidError = false;
2840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 if (dataPath.exists()) {
2842 mOutPermissions[1] = 0;
2843 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2844 if (mOutPermissions[1] == pkg.applicationInfo.uid
2845 || !Process.supportsProcesses()) {
2846 pkg.applicationInfo.dataDir = dataPath.getPath();
2847 } else {
2848 boolean recovered = false;
2849 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2850 // If this is a system app, we can at least delete its
2851 // current data so the application will still work.
2852 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002853 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002854 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 // Old data gone!
2856 String msg = "System package " + pkg.packageName
2857 + " has changed from uid: "
2858 + mOutPermissions[1] + " to "
2859 + pkg.applicationInfo.uid + "; old data erased";
2860 reportSettingsProblem(Log.WARN, msg);
2861 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002864 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 pkg.applicationInfo.uid);
2866 if (ret == -1) {
2867 // Ack should not happen!
2868 msg = "System package " + pkg.packageName
2869 + " could not have data directory re-created after delete.";
2870 reportSettingsProblem(Log.WARN, msg);
2871 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2872 return null;
2873 }
2874 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 if (!recovered) {
2877 mHasSystemUidErrors = true;
2878 }
2879 }
2880 if (!recovered) {
2881 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2882 + pkg.applicationInfo.uid + "/fs_"
2883 + mOutPermissions[1];
2884 String msg = "Package " + pkg.packageName
2885 + " has mismatched uid: "
2886 + mOutPermissions[1] + " on disk, "
2887 + pkg.applicationInfo.uid + " in settings";
2888 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002889 mSettings.mReadMessages.append(msg);
2890 mSettings.mReadMessages.append('\n');
2891 uidError = true;
2892 if (!pkgSetting.uidError) {
2893 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 }
2896 }
2897 }
2898 pkg.applicationInfo.dataDir = dataPath.getPath();
2899 } else {
2900 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2901 Log.v(TAG, "Want this data dir: " + dataPath);
2902 //invoke installer to do the actual installation
2903 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002904 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 pkg.applicationInfo.uid);
2906 if(ret < 0) {
2907 // Error from installer
2908 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2909 return null;
2910 }
2911 } else {
2912 dataPath.mkdirs();
2913 if (dataPath.exists()) {
2914 FileUtils.setPermissions(
2915 dataPath.toString(),
2916 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2917 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2918 }
2919 }
2920 if (dataPath.exists()) {
2921 pkg.applicationInfo.dataDir = dataPath.getPath();
2922 } else {
2923 Log.w(TAG, "Unable to create data directory: " + dataPath);
2924 pkg.applicationInfo.dataDir = null;
2925 }
2926 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002927
2928 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
2930
2931 // Perform shared library installation and dex validation and
2932 // optimization, if this is not a system app.
2933 if (mInstaller != null) {
2934 String path = scanFile.getPath();
2935 if (scanFileNewer) {
2936 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002937 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2938 if (err != PackageManager.INSTALL_SUCCEEDED) {
2939 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 return null;
2941 }
2942 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002943 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002944
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002945 if ((scanMode&SCAN_NO_DEX) == 0) {
2946 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2948 return null;
2949 }
2950 }
2951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 if (mFactoryTest && pkg.requestedPermissions.contains(
2954 android.Manifest.permission.FACTORY_TEST)) {
2955 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2956 }
2957
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002958 // Request the ActivityManager to kill the process(only for existing packages)
2959 // so that we do not end up in a confused state while the user is still using the older
2960 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002961 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002962 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002963 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002964 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002967 // We don't expect installation to fail beyond this point,
2968 if ((scanMode&SCAN_MONITOR) != 0) {
2969 mAppDirs.put(pkg.mPath, pkg);
2970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002972 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002974 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08002975 // Make sure we don't accidentally delete its data.
2976 mSettings.mPackagesToBeCleaned.remove(pkgName);
2977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 int N = pkg.providers.size();
2979 StringBuilder r = null;
2980 int i;
2981 for (i=0; i<N; i++) {
2982 PackageParser.Provider p = pkg.providers.get(i);
2983 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2984 p.info.processName, pkg.applicationInfo.uid);
2985 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2986 p.info.name), p);
2987 p.syncable = p.info.isSyncable;
2988 String names[] = p.info.authority.split(";");
2989 p.info.authority = null;
2990 for (int j = 0; j < names.length; j++) {
2991 if (j == 1 && p.syncable) {
2992 // We only want the first authority for a provider to possibly be
2993 // syncable, so if we already added this provider using a different
2994 // authority clear the syncable flag. We copy the provider before
2995 // changing it because the mProviders object contains a reference
2996 // to a provider that we don't want to change.
2997 // Only do this for the second authority since the resulting provider
2998 // object can be the same for all future authorities for this provider.
2999 p = new PackageParser.Provider(p);
3000 p.syncable = false;
3001 }
3002 if (!mProviders.containsKey(names[j])) {
3003 mProviders.put(names[j], p);
3004 if (p.info.authority == null) {
3005 p.info.authority = names[j];
3006 } else {
3007 p.info.authority = p.info.authority + ";" + names[j];
3008 }
3009 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3010 Log.d(TAG, "Registered content provider: " + names[j] +
3011 ", className = " + p.info.name +
3012 ", isSyncable = " + p.info.isSyncable);
3013 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07003014 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 Log.w(TAG, "Skipping provider name " + names[j] +
3016 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07003017 "): name already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003018 + ((other != null && other.getComponentName() != null)
3019 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 }
3021 }
3022 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3023 if (r == null) {
3024 r = new StringBuilder(256);
3025 } else {
3026 r.append(' ');
3027 }
3028 r.append(p.info.name);
3029 }
3030 }
3031 if (r != null) {
3032 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3033 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 N = pkg.services.size();
3036 r = null;
3037 for (i=0; i<N; i++) {
3038 PackageParser.Service s = pkg.services.get(i);
3039 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3040 s.info.processName, pkg.applicationInfo.uid);
3041 mServices.addService(s);
3042 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3043 if (r == null) {
3044 r = new StringBuilder(256);
3045 } else {
3046 r.append(' ');
3047 }
3048 r.append(s.info.name);
3049 }
3050 }
3051 if (r != null) {
3052 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3053 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 N = pkg.receivers.size();
3056 r = null;
3057 for (i=0; i<N; i++) {
3058 PackageParser.Activity a = pkg.receivers.get(i);
3059 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3060 a.info.processName, pkg.applicationInfo.uid);
3061 mReceivers.addActivity(a, "receiver");
3062 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3063 if (r == null) {
3064 r = new StringBuilder(256);
3065 } else {
3066 r.append(' ');
3067 }
3068 r.append(a.info.name);
3069 }
3070 }
3071 if (r != null) {
3072 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3073 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 N = pkg.activities.size();
3076 r = null;
3077 for (i=0; i<N; i++) {
3078 PackageParser.Activity a = pkg.activities.get(i);
3079 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3080 a.info.processName, pkg.applicationInfo.uid);
3081 mActivities.addActivity(a, "activity");
3082 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3083 if (r == null) {
3084 r = new StringBuilder(256);
3085 } else {
3086 r.append(' ');
3087 }
3088 r.append(a.info.name);
3089 }
3090 }
3091 if (r != null) {
3092 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3093 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 N = pkg.permissionGroups.size();
3096 r = null;
3097 for (i=0; i<N; i++) {
3098 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3099 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3100 if (cur == null) {
3101 mPermissionGroups.put(pg.info.name, pg);
3102 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3103 if (r == null) {
3104 r = new StringBuilder(256);
3105 } else {
3106 r.append(' ');
3107 }
3108 r.append(pg.info.name);
3109 }
3110 } else {
3111 Log.w(TAG, "Permission group " + pg.info.name + " from package "
3112 + pg.info.packageName + " ignored: original from "
3113 + cur.info.packageName);
3114 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3115 if (r == null) {
3116 r = new StringBuilder(256);
3117 } else {
3118 r.append(' ');
3119 }
3120 r.append("DUP:");
3121 r.append(pg.info.name);
3122 }
3123 }
3124 }
3125 if (r != null) {
3126 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3127 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 N = pkg.permissions.size();
3130 r = null;
3131 for (i=0; i<N; i++) {
3132 PackageParser.Permission p = pkg.permissions.get(i);
3133 HashMap<String, BasePermission> permissionMap =
3134 p.tree ? mSettings.mPermissionTrees
3135 : mSettings.mPermissions;
3136 p.group = mPermissionGroups.get(p.info.group);
3137 if (p.info.group == null || p.group != null) {
3138 BasePermission bp = permissionMap.get(p.info.name);
3139 if (bp == null) {
3140 bp = new BasePermission(p.info.name, p.info.packageName,
3141 BasePermission.TYPE_NORMAL);
3142 permissionMap.put(p.info.name, bp);
3143 }
3144 if (bp.perm == null) {
3145 if (bp.sourcePackage == null
3146 || bp.sourcePackage.equals(p.info.packageName)) {
3147 BasePermission tree = findPermissionTreeLP(p.info.name);
3148 if (tree == null
3149 || tree.sourcePackage.equals(p.info.packageName)) {
3150 bp.perm = p;
3151 bp.uid = pkg.applicationInfo.uid;
3152 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3153 if (r == null) {
3154 r = new StringBuilder(256);
3155 } else {
3156 r.append(' ');
3157 }
3158 r.append(p.info.name);
3159 }
3160 } else {
3161 Log.w(TAG, "Permission " + p.info.name + " from package "
3162 + p.info.packageName + " ignored: base tree "
3163 + tree.name + " is from package "
3164 + tree.sourcePackage);
3165 }
3166 } else {
3167 Log.w(TAG, "Permission " + p.info.name + " from package "
3168 + p.info.packageName + " ignored: original from "
3169 + bp.sourcePackage);
3170 }
3171 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3172 if (r == null) {
3173 r = new StringBuilder(256);
3174 } else {
3175 r.append(' ');
3176 }
3177 r.append("DUP:");
3178 r.append(p.info.name);
3179 }
3180 } else {
3181 Log.w(TAG, "Permission " + p.info.name + " from package "
3182 + p.info.packageName + " ignored: no group "
3183 + p.group);
3184 }
3185 }
3186 if (r != null) {
3187 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3188 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 N = pkg.instrumentation.size();
3191 r = null;
3192 for (i=0; i<N; i++) {
3193 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3194 a.info.packageName = pkg.applicationInfo.packageName;
3195 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3196 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3197 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003198 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3200 if (r == null) {
3201 r = new StringBuilder(256);
3202 } else {
3203 r.append(' ');
3204 }
3205 r.append(a.info.name);
3206 }
3207 }
3208 if (r != null) {
3209 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3210 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003211
Dianne Hackborn854060af2009-07-09 18:14:31 -07003212 if (pkg.protectedBroadcasts != null) {
3213 N = pkg.protectedBroadcasts.size();
3214 for (i=0; i<N; i++) {
3215 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3216 }
3217 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 pkgSetting.setTimeStamp(scanFileTime);
3220 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 return pkg;
3223 }
3224
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003225 private void killApplication(String pkgName, int uid) {
3226 // Request the ActivityManager to kill the process(only for existing packages)
3227 // so that we do not end up in a confused state while the user is still using the older
3228 // version of the application while the new one gets installed.
3229 IActivityManager am = ActivityManagerNative.getDefault();
3230 if (am != null) {
3231 try {
3232 am.killApplicationWithUid(pkgName, uid);
3233 } catch (RemoteException e) {
3234 }
3235 }
3236 }
3237
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003238 // The following constants are returned by cachePackageSharedLibsForAbiLI
3239 // to indicate if native shared libraries were found in the package.
3240 // Values are:
3241 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3242 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3243 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3244 // in package (and not installed)
3245 //
3246 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3247 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3248 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003250 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3251 // and automatically copy them to /data/data/<appname>/lib if present.
3252 //
3253 // NOTE: this method may throw an IOException if the library cannot
3254 // be copied to its final destination, e.g. if there isn't enough
3255 // room left on the data partition, or a ZipException if the package
3256 // file is malformed.
3257 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003258 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3259 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003260 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3261 final String apkLib = "lib/";
3262 final int apkLibLen = apkLib.length();
3263 final int cpuAbiLen = cpuAbi.length();
3264 final String libPrefix = "lib";
3265 final int libPrefixLen = libPrefix.length();
3266 final String libSuffix = ".so";
3267 final int libSuffixLen = libSuffix.length();
3268 boolean hasNativeLibraries = false;
3269 boolean installedNativeLibraries = false;
3270
3271 // the minimum length of a valid native shared library of the form
3272 // lib/<something>/lib<name>.so.
3273 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3274
3275 ZipFile zipFile = new ZipFile(scanFile);
3276 Enumeration<ZipEntry> entries =
3277 (Enumeration<ZipEntry>) zipFile.entries();
3278
3279 while (entries.hasMoreElements()) {
3280 ZipEntry entry = entries.nextElement();
3281 // skip directories
3282 if (entry.isDirectory()) {
3283 continue;
3284 }
3285 String entryName = entry.getName();
3286
3287 // check that the entry looks like lib/<something>/lib<name>.so
3288 // here, but don't check the ABI just yet.
3289 //
3290 // - must be sufficiently long
3291 // - must end with libSuffix, i.e. ".so"
3292 // - must start with apkLib, i.e. "lib/"
3293 if (entryName.length() < minEntryLen ||
3294 !entryName.endsWith(libSuffix) ||
3295 !entryName.startsWith(apkLib) ) {
3296 continue;
3297 }
3298
3299 // file name must start with libPrefix, i.e. "lib"
3300 int lastSlash = entryName.lastIndexOf('/');
3301
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003302 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003303 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3304 continue;
3305 }
3306
3307 hasNativeLibraries = true;
3308
3309 // check the cpuAbi now, between lib/ and /lib<name>.so
3310 //
3311 if (lastSlash != apkLibLen + cpuAbiLen ||
3312 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3313 continue;
3314
3315 // extract the library file name, ensure it doesn't contain
3316 // weird characters. we're guaranteed here that it doesn't contain
3317 // a directory separator though.
3318 String libFileName = entryName.substring(lastSlash+1);
3319 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3320 continue;
3321 }
3322
3323 installedNativeLibraries = true;
3324
3325 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3326 File.separator + libFileName;
3327 File sharedLibraryFile = new File(sharedLibraryFilePath);
3328 if (! sharedLibraryFile.exists() ||
3329 sharedLibraryFile.length() != entry.getSize() ||
3330 sharedLibraryFile.lastModified() != entry.getTime()) {
3331 if (Config.LOGD) {
3332 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003334 if (mInstaller == null) {
3335 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003336 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003337 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003338 sharedLibraryFile);
3339 }
3340 }
3341 if (!hasNativeLibraries)
3342 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3343
3344 if (!installedNativeLibraries)
3345 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3346
3347 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3348 }
3349
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003350 // Find the gdbserver executable program in a package at
3351 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3352 //
3353 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3354 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3355 //
3356 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3357 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3358 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3359 final String GDBSERVER = "gdbserver";
3360 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3361
3362 ZipFile zipFile = new ZipFile(scanFile);
3363 Enumeration<ZipEntry> entries =
3364 (Enumeration<ZipEntry>) zipFile.entries();
3365
3366 while (entries.hasMoreElements()) {
3367 ZipEntry entry = entries.nextElement();
3368 // skip directories
3369 if (entry.isDirectory()) {
3370 continue;
3371 }
3372 String entryName = entry.getName();
3373
3374 if (!entryName.equals(apkGdbServerPath)) {
3375 continue;
3376 }
3377
3378 String installGdbServerPath = installGdbServerDir.getPath() +
3379 "/" + GDBSERVER;
3380 File installGdbServerFile = new File(installGdbServerPath);
3381 if (! installGdbServerFile.exists() ||
3382 installGdbServerFile.length() != entry.getSize() ||
3383 installGdbServerFile.lastModified() != entry.getTime()) {
3384 if (Config.LOGD) {
3385 Log.d(TAG, "Caching gdbserver " + entry.getName());
3386 }
3387 if (mInstaller == null) {
3388 installGdbServerDir.mkdir();
3389 }
3390 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3391 installGdbServerFile);
3392 }
3393 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3394 }
3395 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3396 }
3397
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003398 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3399 // and copy them to /data/data/<appname>/lib.
3400 //
3401 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3402 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3403 // one if ro.product.cpu.abi2 is defined.
3404 //
3405 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3406 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003407 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003408 try {
3409 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3410
3411 // some architectures are capable of supporting several CPU ABIs
3412 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3413 // this is indicated by the definition of the ro.product.cpu.abi2
3414 // system property.
3415 //
3416 // only scan the package twice in case of ABI mismatch
3417 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003418 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003419 if (cpuAbi2 != null) {
3420 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003422
3423 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3424 Log.w(TAG,"Native ABI mismatch from package file");
3425 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003427
3428 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3429 cpuAbi = cpuAbi2;
3430 }
3431 }
3432
3433 // for debuggable packages, also extract gdbserver from lib/<abi>
3434 // into /data/data/<appname>/lib too.
3435 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3436 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3437 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3438 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3439 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003442 } catch (ZipException e) {
3443 Log.w(TAG, "Failed to extract data from package file", e);
3444 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003446 Log.w(TAG, "Failed to cache package shared libs", e);
3447 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003449 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 }
3451
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003452 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003454 File binaryDir,
3455 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 InputStream inputStream = zipFile.getInputStream(entry);
3457 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003458 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003460 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 // now need to be left as world readable and owned by the system.
3462 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3463 ! tempFile.setLastModified(entry.getTime()) ||
3464 FileUtils.setPermissions(tempFilePath,
3465 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003466 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003468 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 // Failed to properly write file.
3470 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003471 throw new IOException("Couldn't create cached binary "
3472 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 }
3474 } finally {
3475 inputStream.close();
3476 }
3477 }
3478
3479 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3480 if (chatty && Config.LOGD) Log.d(
3481 TAG, "Removing package " + pkg.applicationInfo.packageName );
3482
3483 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 mPackages.remove(pkg.applicationInfo.packageName);
3487 if (pkg.mPath != null) {
3488 mAppDirs.remove(pkg.mPath);
3489 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 PackageSetting ps = (PackageSetting)pkg.mExtras;
3492 if (ps != null && ps.sharedUser != null) {
3493 // XXX don't do this until the data is removed.
3494 if (false) {
3495 ps.sharedUser.packages.remove(ps);
3496 if (ps.sharedUser.packages.size() == 0) {
3497 // Remove.
3498 }
3499 }
3500 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 int N = pkg.providers.size();
3503 StringBuilder r = null;
3504 int i;
3505 for (i=0; i<N; i++) {
3506 PackageParser.Provider p = pkg.providers.get(i);
3507 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3508 p.info.name));
3509 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 /* The is another ContentProvider with this authority when
3512 * this app was installed so this authority is null,
3513 * Ignore it as we don't have to unregister the provider.
3514 */
3515 continue;
3516 }
3517 String names[] = p.info.authority.split(";");
3518 for (int j = 0; j < names.length; j++) {
3519 if (mProviders.get(names[j]) == p) {
3520 mProviders.remove(names[j]);
3521 if (chatty && Config.LOGD) Log.d(
3522 TAG, "Unregistered content provider: " + names[j] +
3523 ", className = " + p.info.name +
3524 ", isSyncable = " + p.info.isSyncable);
3525 }
3526 }
3527 if (chatty) {
3528 if (r == null) {
3529 r = new StringBuilder(256);
3530 } else {
3531 r.append(' ');
3532 }
3533 r.append(p.info.name);
3534 }
3535 }
3536 if (r != null) {
3537 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3538 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 N = pkg.services.size();
3541 r = null;
3542 for (i=0; i<N; i++) {
3543 PackageParser.Service s = pkg.services.get(i);
3544 mServices.removeService(s);
3545 if (chatty) {
3546 if (r == null) {
3547 r = new StringBuilder(256);
3548 } else {
3549 r.append(' ');
3550 }
3551 r.append(s.info.name);
3552 }
3553 }
3554 if (r != null) {
3555 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3556 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 N = pkg.receivers.size();
3559 r = null;
3560 for (i=0; i<N; i++) {
3561 PackageParser.Activity a = pkg.receivers.get(i);
3562 mReceivers.removeActivity(a, "receiver");
3563 if (chatty) {
3564 if (r == null) {
3565 r = new StringBuilder(256);
3566 } else {
3567 r.append(' ');
3568 }
3569 r.append(a.info.name);
3570 }
3571 }
3572 if (r != null) {
3573 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3574 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 N = pkg.activities.size();
3577 r = null;
3578 for (i=0; i<N; i++) {
3579 PackageParser.Activity a = pkg.activities.get(i);
3580 mActivities.removeActivity(a, "activity");
3581 if (chatty) {
3582 if (r == null) {
3583 r = new StringBuilder(256);
3584 } else {
3585 r.append(' ');
3586 }
3587 r.append(a.info.name);
3588 }
3589 }
3590 if (r != null) {
3591 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3592 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 N = pkg.permissions.size();
3595 r = null;
3596 for (i=0; i<N; i++) {
3597 PackageParser.Permission p = pkg.permissions.get(i);
3598 boolean tree = false;
3599 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3600 if (bp == null) {
3601 tree = true;
3602 bp = mSettings.mPermissionTrees.get(p.info.name);
3603 }
3604 if (bp != null && bp.perm == p) {
3605 if (bp.type != BasePermission.TYPE_BUILTIN) {
3606 if (tree) {
3607 mSettings.mPermissionTrees.remove(p.info.name);
3608 } else {
3609 mSettings.mPermissions.remove(p.info.name);
3610 }
3611 } else {
3612 bp.perm = null;
3613 }
3614 if (chatty) {
3615 if (r == null) {
3616 r = new StringBuilder(256);
3617 } else {
3618 r.append(' ');
3619 }
3620 r.append(p.info.name);
3621 }
3622 }
3623 }
3624 if (r != null) {
3625 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3626 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 N = pkg.instrumentation.size();
3629 r = null;
3630 for (i=0; i<N; i++) {
3631 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003632 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 if (chatty) {
3634 if (r == null) {
3635 r = new StringBuilder(256);
3636 } else {
3637 r.append(' ');
3638 }
3639 r.append(a.info.name);
3640 }
3641 }
3642 if (r != null) {
3643 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3644 }
3645 }
3646 }
3647
3648 private static final boolean isPackageFilename(String name) {
3649 return name != null && name.endsWith(".apk");
3650 }
3651
3652 private void updatePermissionsLP() {
3653 // Make sure there are no dangling permission trees.
3654 Iterator<BasePermission> it = mSettings.mPermissionTrees
3655 .values().iterator();
3656 while (it.hasNext()) {
3657 BasePermission bp = it.next();
3658 if (bp.perm == null) {
3659 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3660 + " from package " + bp.sourcePackage);
3661 it.remove();
3662 }
3663 }
3664
3665 // Make sure all dynamic permissions have been assigned to a package,
3666 // and make sure there are no dangling permissions.
3667 it = mSettings.mPermissions.values().iterator();
3668 while (it.hasNext()) {
3669 BasePermission bp = it.next();
3670 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3671 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3672 + bp.name + " pkg=" + bp.sourcePackage
3673 + " info=" + bp.pendingInfo);
3674 if (bp.perm == null && bp.pendingInfo != null) {
3675 BasePermission tree = findPermissionTreeLP(bp.name);
3676 if (tree != null) {
3677 bp.perm = new PackageParser.Permission(tree.perm.owner,
3678 new PermissionInfo(bp.pendingInfo));
3679 bp.perm.info.packageName = tree.perm.info.packageName;
3680 bp.perm.info.name = bp.name;
3681 bp.uid = tree.uid;
3682 }
3683 }
3684 }
3685 if (bp.perm == null) {
3686 Log.w(TAG, "Removing dangling permission: " + bp.name
3687 + " from package " + bp.sourcePackage);
3688 it.remove();
3689 }
3690 }
3691
3692 // Now update the permissions for all packages, in particular
3693 // replace the granted permissions of the system packages.
3694 for (PackageParser.Package pkg : mPackages.values()) {
3695 grantPermissionsLP(pkg, false);
3696 }
3697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3700 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3701 if (ps == null) {
3702 return;
3703 }
3704 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3705 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 if (replace) {
3708 ps.permissionsFixed = false;
3709 if (gp == ps) {
3710 gp.grantedPermissions.clear();
3711 gp.gids = mGlobalGids;
3712 }
3713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 if (gp.gids == null) {
3716 gp.gids = mGlobalGids;
3717 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 final int N = pkg.requestedPermissions.size();
3720 for (int i=0; i<N; i++) {
3721 String name = pkg.requestedPermissions.get(i);
3722 BasePermission bp = mSettings.mPermissions.get(name);
3723 PackageParser.Permission p = bp != null ? bp.perm : null;
3724 if (false) {
3725 if (gp != ps) {
3726 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3727 + ": " + p);
3728 }
3729 }
3730 if (p != null) {
3731 final String perm = p.info.name;
3732 boolean allowed;
3733 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3734 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3735 allowed = true;
3736 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3737 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003738 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003740 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 == PackageManager.SIGNATURE_MATCH);
3742 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3743 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3744 // For updated system applications, the signatureOrSystem permission
3745 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003746 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3748 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3749 if(sysPs.grantedPermissions.contains(perm)) {
3750 allowed = true;
3751 } else {
3752 allowed = false;
3753 }
3754 } else {
3755 allowed = true;
3756 }
3757 }
3758 }
3759 } else {
3760 allowed = false;
3761 }
3762 if (false) {
3763 if (gp != ps) {
3764 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3765 }
3766 }
3767 if (allowed) {
3768 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3769 && ps.permissionsFixed) {
3770 // If this is an existing, non-system package, then
3771 // we can't add any new permissions to it.
3772 if (!gp.loadedPermissions.contains(perm)) {
3773 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003774 // Except... if this is a permission that was added
3775 // to the platform (note: need to only do this when
3776 // updating the platform).
3777 final int NP = PackageParser.NEW_PERMISSIONS.length;
3778 for (int ip=0; ip<NP; ip++) {
3779 final PackageParser.NewPermissionInfo npi
3780 = PackageParser.NEW_PERMISSIONS[ip];
3781 if (npi.name.equals(perm)
3782 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3783 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003784 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003785 + pkg.packageName);
3786 break;
3787 }
3788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 }
3790 }
3791 if (allowed) {
3792 if (!gp.grantedPermissions.contains(perm)) {
3793 addedPermission = true;
3794 gp.grantedPermissions.add(perm);
3795 gp.gids = appendInts(gp.gids, bp.gids);
3796 }
3797 } else {
3798 Log.w(TAG, "Not granting permission " + perm
3799 + " to package " + pkg.packageName
3800 + " because it was previously installed without");
3801 }
3802 } else {
3803 Log.w(TAG, "Not granting permission " + perm
3804 + " to package " + pkg.packageName
3805 + " (protectionLevel=" + p.info.protectionLevel
3806 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3807 + ")");
3808 }
3809 } else {
3810 Log.w(TAG, "Unknown permission " + name
3811 + " in package " + pkg.packageName);
3812 }
3813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003816 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3817 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818 // This is the first that we have heard about this package, so the
3819 // permissions we have now selected are fixed until explicitly
3820 // changed.
3821 ps.permissionsFixed = true;
3822 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3823 }
3824 }
3825
3826 private final class ActivityIntentResolver
3827 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003828 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003830 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 }
3832
Mihai Preda074edef2009-05-18 17:13:31 +02003833 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003835 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3837 }
3838
Mihai Predaeae850c2009-05-13 10:13:48 +02003839 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3840 ArrayList<PackageParser.Activity> packageActivities) {
3841 if (packageActivities == null) {
3842 return null;
3843 }
3844 mFlags = flags;
3845 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3846 int N = packageActivities.size();
3847 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3848 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003849
3850 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003851 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003852 intentFilters = packageActivities.get(i).intents;
3853 if (intentFilters != null && intentFilters.size() > 0) {
3854 listCut.add(intentFilters);
3855 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003856 }
3857 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3858 }
3859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003861 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 if (SHOW_INFO || Config.LOGV) Log.v(
3863 TAG, " " + type + " " +
3864 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3865 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3866 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003867 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3869 if (SHOW_INFO || Config.LOGV) {
3870 Log.v(TAG, " IntentFilter:");
3871 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3872 }
3873 if (!intent.debugCheck()) {
3874 Log.w(TAG, "==> For Activity " + a.info.name);
3875 }
3876 addFilter(intent);
3877 }
3878 }
3879
3880 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003881 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 if (SHOW_INFO || Config.LOGV) Log.v(
3883 TAG, " " + type + " " +
3884 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3885 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3886 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003887 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3889 if (SHOW_INFO || Config.LOGV) {
3890 Log.v(TAG, " IntentFilter:");
3891 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3892 }
3893 removeFilter(intent);
3894 }
3895 }
3896
3897 @Override
3898 protected boolean allowFilterResult(
3899 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3900 ActivityInfo filterAi = filter.activity.info;
3901 for (int i=dest.size()-1; i>=0; i--) {
3902 ActivityInfo destAi = dest.get(i).activityInfo;
3903 if (destAi.name == filterAi.name
3904 && destAi.packageName == filterAi.packageName) {
3905 return false;
3906 }
3907 }
3908 return true;
3909 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 @Override
3912 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3913 int match) {
3914 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3915 return null;
3916 }
3917 final PackageParser.Activity activity = info.activity;
3918 if (mSafeMode && (activity.info.applicationInfo.flags
3919 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3920 return null;
3921 }
3922 final ResolveInfo res = new ResolveInfo();
3923 res.activityInfo = PackageParser.generateActivityInfo(activity,
3924 mFlags);
3925 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3926 res.filter = info;
3927 }
3928 res.priority = info.getPriority();
3929 res.preferredOrder = activity.owner.mPreferredOrder;
3930 //System.out.println("Result: " + res.activityInfo.className +
3931 // " = " + res.priority);
3932 res.match = match;
3933 res.isDefault = info.hasDefault;
3934 res.labelRes = info.labelRes;
3935 res.nonLocalizedLabel = info.nonLocalizedLabel;
3936 res.icon = info.icon;
3937 return res;
3938 }
3939
3940 @Override
3941 protected void sortResults(List<ResolveInfo> results) {
3942 Collections.sort(results, mResolvePrioritySorter);
3943 }
3944
3945 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003946 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003948 out.print(prefix); out.print(
3949 Integer.toHexString(System.identityHashCode(filter.activity)));
3950 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003951 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 }
3953
3954// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3955// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3956// final List<ResolveInfo> retList = Lists.newArrayList();
3957// while (i.hasNext()) {
3958// final ResolveInfo resolveInfo = i.next();
3959// if (isEnabledLP(resolveInfo.activityInfo)) {
3960// retList.add(resolveInfo);
3961// }
3962// }
3963// return retList;
3964// }
3965
3966 // Keys are String (activity class name), values are Activity.
3967 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3968 = new HashMap<ComponentName, PackageParser.Activity>();
3969 private int mFlags;
3970 }
3971
3972 private final class ServiceIntentResolver
3973 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003974 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003976 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 }
3978
Mihai Preda074edef2009-05-18 17:13:31 +02003979 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003981 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3983 }
3984
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07003985 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3986 ArrayList<PackageParser.Service> packageServices) {
3987 if (packageServices == null) {
3988 return null;
3989 }
3990 mFlags = flags;
3991 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3992 int N = packageServices.size();
3993 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3994 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3995
3996 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3997 for (int i = 0; i < N; ++i) {
3998 intentFilters = packageServices.get(i).intents;
3999 if (intentFilters != null && intentFilters.size() > 0) {
4000 listCut.add(intentFilters);
4001 }
4002 }
4003 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4004 }
4005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004007 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 if (SHOW_INFO || Config.LOGV) Log.v(
4009 TAG, " " + (s.info.nonLocalizedLabel != null
4010 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4011 if (SHOW_INFO || Config.LOGV) Log.v(
4012 TAG, " Class=" + s.info.name);
4013 int NI = s.intents.size();
4014 int j;
4015 for (j=0; j<NI; j++) {
4016 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4017 if (SHOW_INFO || Config.LOGV) {
4018 Log.v(TAG, " IntentFilter:");
4019 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4020 }
4021 if (!intent.debugCheck()) {
4022 Log.w(TAG, "==> For Service " + s.info.name);
4023 }
4024 addFilter(intent);
4025 }
4026 }
4027
4028 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004029 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 if (SHOW_INFO || Config.LOGV) Log.v(
4031 TAG, " " + (s.info.nonLocalizedLabel != null
4032 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4033 if (SHOW_INFO || Config.LOGV) Log.v(
4034 TAG, " Class=" + s.info.name);
4035 int NI = s.intents.size();
4036 int j;
4037 for (j=0; j<NI; j++) {
4038 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4039 if (SHOW_INFO || Config.LOGV) {
4040 Log.v(TAG, " IntentFilter:");
4041 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4042 }
4043 removeFilter(intent);
4044 }
4045 }
4046
4047 @Override
4048 protected boolean allowFilterResult(
4049 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4050 ServiceInfo filterSi = filter.service.info;
4051 for (int i=dest.size()-1; i>=0; i--) {
4052 ServiceInfo destAi = dest.get(i).serviceInfo;
4053 if (destAi.name == filterSi.name
4054 && destAi.packageName == filterSi.packageName) {
4055 return false;
4056 }
4057 }
4058 return true;
4059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 @Override
4062 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4063 int match) {
4064 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4065 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4066 return null;
4067 }
4068 final PackageParser.Service service = info.service;
4069 if (mSafeMode && (service.info.applicationInfo.flags
4070 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4071 return null;
4072 }
4073 final ResolveInfo res = new ResolveInfo();
4074 res.serviceInfo = PackageParser.generateServiceInfo(service,
4075 mFlags);
4076 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4077 res.filter = filter;
4078 }
4079 res.priority = info.getPriority();
4080 res.preferredOrder = service.owner.mPreferredOrder;
4081 //System.out.println("Result: " + res.activityInfo.className +
4082 // " = " + res.priority);
4083 res.match = match;
4084 res.isDefault = info.hasDefault;
4085 res.labelRes = info.labelRes;
4086 res.nonLocalizedLabel = info.nonLocalizedLabel;
4087 res.icon = info.icon;
4088 return res;
4089 }
4090
4091 @Override
4092 protected void sortResults(List<ResolveInfo> results) {
4093 Collections.sort(results, mResolvePrioritySorter);
4094 }
4095
4096 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004097 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004099 out.print(prefix); out.print(
4100 Integer.toHexString(System.identityHashCode(filter.service)));
4101 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004102 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 }
4104
4105// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4106// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4107// final List<ResolveInfo> retList = Lists.newArrayList();
4108// while (i.hasNext()) {
4109// final ResolveInfo resolveInfo = (ResolveInfo) i;
4110// if (isEnabledLP(resolveInfo.serviceInfo)) {
4111// retList.add(resolveInfo);
4112// }
4113// }
4114// return retList;
4115// }
4116
4117 // Keys are String (activity class name), values are Activity.
4118 private final HashMap<ComponentName, PackageParser.Service> mServices
4119 = new HashMap<ComponentName, PackageParser.Service>();
4120 private int mFlags;
4121 };
4122
4123 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4124 new Comparator<ResolveInfo>() {
4125 public int compare(ResolveInfo r1, ResolveInfo r2) {
4126 int v1 = r1.priority;
4127 int v2 = r2.priority;
4128 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4129 if (v1 != v2) {
4130 return (v1 > v2) ? -1 : 1;
4131 }
4132 v1 = r1.preferredOrder;
4133 v2 = r2.preferredOrder;
4134 if (v1 != v2) {
4135 return (v1 > v2) ? -1 : 1;
4136 }
4137 if (r1.isDefault != r2.isDefault) {
4138 return r1.isDefault ? -1 : 1;
4139 }
4140 v1 = r1.match;
4141 v2 = r2.match;
4142 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4143 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4144 }
4145 };
4146
4147 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4148 new Comparator<ProviderInfo>() {
4149 public int compare(ProviderInfo p1, ProviderInfo p2) {
4150 final int v1 = p1.initOrder;
4151 final int v2 = p2.initOrder;
4152 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4153 }
4154 };
4155
4156 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4157 IActivityManager am = ActivityManagerNative.getDefault();
4158 if (am != null) {
4159 try {
4160 final Intent intent = new Intent(action,
4161 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4162 if (extras != null) {
4163 intent.putExtras(extras);
4164 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004165 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 am.broadcastIntent(
4167 null, intent,
4168 null, null, 0, null, null, null, false, false);
4169 } catch (RemoteException ex) {
4170 }
4171 }
4172 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004173
4174 public String nextPackageToClean(String lastPackage) {
4175 synchronized (mPackages) {
4176 if (!mMediaMounted) {
4177 // If the external storage is no longer mounted at this point,
4178 // the caller may not have been able to delete all of this
4179 // packages files and can not delete any more. Bail.
4180 return null;
4181 }
4182 if (lastPackage != null) {
4183 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4184 }
4185 return mSettings.mPackagesToBeCleaned.size() > 0
4186 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4187 }
4188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004189
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004190 void schedulePackageCleaning(String packageName) {
4191 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4192 }
4193
4194 void startCleaningPackages() {
4195 synchronized (mPackages) {
4196 if (!mMediaMounted) {
4197 return;
4198 }
4199 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4200 return;
4201 }
4202 }
4203 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4204 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4205 IActivityManager am = ActivityManagerNative.getDefault();
4206 if (am != null) {
4207 try {
4208 am.startService(null, intent, null);
4209 } catch (RemoteException e) {
4210 }
4211 }
4212 }
4213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 private final class AppDirObserver extends FileObserver {
4215 public AppDirObserver(String path, int mask, boolean isrom) {
4216 super(path, mask);
4217 mRootDir = path;
4218 mIsRom = isrom;
4219 }
4220
4221 public void onEvent(int event, String path) {
4222 String removedPackage = null;
4223 int removedUid = -1;
4224 String addedPackage = null;
4225 int addedUid = -1;
4226
4227 synchronized (mInstallLock) {
4228 String fullPathStr = null;
4229 File fullPath = null;
4230 if (path != null) {
4231 fullPath = new File(mRootDir, path);
4232 fullPathStr = fullPath.getPath();
4233 }
4234
4235 if (Config.LOGV) Log.v(
4236 TAG, "File " + fullPathStr + " changed: "
4237 + Integer.toHexString(event));
4238
4239 if (!isPackageFilename(path)) {
4240 if (Config.LOGV) Log.v(
4241 TAG, "Ignoring change of non-package file: " + fullPathStr);
4242 return;
4243 }
4244
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004245 // Ignore packages that are being installed or
4246 // have just been installed.
4247 if (ignoreCodePath(fullPathStr)) {
4248 return;
4249 }
4250 PackageParser.Package p = null;
4251 synchronized (mPackages) {
4252 p = mAppDirs.get(fullPathStr);
4253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004255 if (p != null) {
4256 removePackageLI(p, true);
4257 removedPackage = p.applicationInfo.packageName;
4258 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 }
4260 }
4261
4262 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004263 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004264 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4266 PackageParser.PARSE_CHATTY |
4267 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004268 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 if (p != null) {
4270 synchronized (mPackages) {
4271 grantPermissionsLP(p, false);
4272 }
4273 addedPackage = p.applicationInfo.packageName;
4274 addedUid = p.applicationInfo.uid;
4275 }
4276 }
4277 }
4278
4279 synchronized (mPackages) {
4280 mSettings.writeLP();
4281 }
4282 }
4283
4284 if (removedPackage != null) {
4285 Bundle extras = new Bundle(1);
4286 extras.putInt(Intent.EXTRA_UID, removedUid);
4287 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4288 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4289 }
4290 if (addedPackage != null) {
4291 Bundle extras = new Bundle(1);
4292 extras.putInt(Intent.EXTRA_UID, addedUid);
4293 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4294 }
4295 }
4296
4297 private final String mRootDir;
4298 private final boolean mIsRom;
4299 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 /* Called when a downloaded package installation has been confirmed by the user */
4302 public void installPackage(
4303 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004304 installPackage(packageURI, observer, flags, null);
4305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004306
Jacek Surazski65e13172009-04-28 15:26:38 +02004307 /* Called when a downloaded package installation has been confirmed by the user */
4308 public void installPackage(
4309 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4310 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 mContext.enforceCallingOrSelfPermission(
4312 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004313
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004314 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004315 msg.obj = new InstallParams(packageURI, observer, flags,
4316 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004317 mHandler.sendMessage(msg);
4318 }
4319
Christopher Tate1bb69062010-02-19 17:02:12 -08004320 public void finishPackageInstall(int token) {
4321 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4322 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4323 mHandler.sendMessage(msg);
4324 }
4325
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004326 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 // Queue up an async operation since the package installation may take a little while.
4328 mHandler.post(new Runnable() {
4329 public void run() {
4330 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004331 // Result object to be returned
4332 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004333 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004334 res.uid = -1;
4335 res.pkg = null;
4336 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004337 args.doPreInstall(res.returnCode);
4338 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004339 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004340 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004341 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004342 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004344
4345 // A restore should be performed at this point if (a) the install
4346 // succeeded, (b) the operation is not an update, and (c) the new
4347 // package has a backupAgent defined.
4348 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004349 boolean doRestore = (!update
4350 && res.pkg != null
4351 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004352
4353 // Set up the post-install work request bookkeeping. This will be used
4354 // and cleaned up by the post-install event handling regardless of whether
4355 // there's a restore pass performed. Token values are >= 1.
4356 int token;
4357 if (mNextInstallToken < 0) mNextInstallToken = 1;
4358 token = mNextInstallToken++;
4359
4360 PostInstallData data = new PostInstallData(args, res);
4361 mRunningInstalls.put(token, data);
4362 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4363
4364 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4365 // Pass responsibility to the Backup Manager. It will perform a
4366 // restore if appropriate, then pass responsibility back to the
4367 // Package Manager to run the post-install observer callbacks
4368 // and broadcasts.
4369 IBackupManager bm = IBackupManager.Stub.asInterface(
4370 ServiceManager.getService(Context.BACKUP_SERVICE));
4371 if (bm != null) {
4372 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4373 + " to BM for possible restore");
4374 try {
4375 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4376 } catch (RemoteException e) {
4377 // can't happen; the backup manager is local
4378 } catch (Exception e) {
4379 Log.e(TAG, "Exception trying to enqueue restore", e);
4380 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004381 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004382 } else {
4383 Log.e(TAG, "Backup Manager not found!");
4384 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004387
4388 if (!doRestore) {
4389 // No restore possible, or the Backup Manager was mysteriously not
4390 // available -- just fire the post-install work request directly.
4391 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4392 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4393 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004395 }
4396 });
4397 }
4398
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004399 interface HandlerParams {
4400 void handleStartCopy(IMediaContainerService imcs);
4401 void handleServiceError();
4402 }
4403
4404 class InstallParams implements HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004405 final IPackageInstallObserver observer;
4406 int flags;
4407 final Uri packageURI;
4408 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004409 private InstallArgs mArgs;
4410 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004411 InstallParams(Uri packageURI,
4412 IPackageInstallObserver observer, int flags,
4413 String installerPackageName) {
4414 this.packageURI = packageURI;
4415 this.flags = flags;
4416 this.observer = observer;
4417 this.installerPackageName = installerPackageName;
4418 }
4419
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004420 private int getInstallLocation(IMediaContainerService imcs) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004421 try {
4422 return imcs.getRecommendedInstallLocation(packageURI);
4423 } catch (RemoteException e) {
4424 }
4425 return -1;
4426 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004427
4428 public void handleStartCopy(IMediaContainerService imcs) {
4429 int ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4430 if (imcs != null) {
4431 // Remote call to find out default install location
4432 int loc = getInstallLocation(imcs);
4433 // Use install location to create InstallArgs and temporary
4434 // install location
4435 if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
4436 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4437 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4438 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
4439 } else {
4440 if ((flags & PackageManager.INSTALL_EXTERNAL) == 0){
4441 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4442 // Set the flag to install on external media.
4443 flags |= PackageManager.INSTALL_EXTERNAL;
4444 } else {
4445 // Make sure the flag for installing on external
4446 // media is unset
4447 flags &= ~PackageManager.INSTALL_EXTERNAL;
4448 }
4449 }
4450 // Disable forward locked apps on sdcard.
4451 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0 &&
4452 (flags & PackageManager.INSTALL_EXTERNAL) != 0) {
4453 // Make sure forward locked apps can only be installed
4454 // on internal storage
4455 Log.w(TAG, "Cannot install protected apps on sdcard");
4456 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4457 } else {
4458 ret = PackageManager.INSTALL_SUCCEEDED;
4459 }
4460 }
4461 }
4462 // Create the file args now.
4463 mArgs = createInstallArgs(this);
4464 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4465 // Create copy only if we are not in an erroneous state.
4466 // Remote call to initiate copy using temporary file
4467 ret = mArgs.copyApk(imcs, true);
4468 }
4469 mRet = ret;
4470 mHandler.sendEmptyMessage(MCS_UNBIND);
4471 handleReturnCode();
4472 }
4473
4474 void handleReturnCode() {
4475 processPendingInstall(mArgs, mRet);
4476 }
4477
4478 public void handleServiceError() {
4479 mArgs = createInstallArgs(this);
4480 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4481 handleReturnCode();
4482 }
4483 };
4484
4485 /*
4486 * Utility class used in movePackage api.
4487 * srcArgs and targetArgs are not set for invalid flags and make
4488 * sure to do null checks when invoking methods on them.
4489 * We probably want to return ErrorPrams for both failed installs
4490 * and moves.
4491 */
4492 class MoveParams implements HandlerParams {
4493 final IPackageMoveObserver observer;
4494 final int flags;
4495 final String packageName;
4496 final InstallArgs srcArgs;
4497 final InstallArgs targetArgs;
4498 int mRet;
4499 MoveParams(InstallArgs srcArgs,
4500 IPackageMoveObserver observer,
4501 int flags, String packageName) {
4502 this.srcArgs = srcArgs;
4503 this.observer = observer;
4504 this.flags = flags;
4505 this.packageName = packageName;
4506 if (srcArgs != null) {
4507 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4508 targetArgs = createInstallArgs(packageUri, flags, packageName);
4509 } else {
4510 targetArgs = null;
4511 }
4512 }
4513
4514 public void handleStartCopy(IMediaContainerService imcs) {
4515 // Create the file args now.
4516 mRet = targetArgs.copyApk(imcs, false);
4517 targetArgs.doPreInstall(mRet);
4518 mHandler.sendEmptyMessage(MCS_UNBIND);
4519 handleReturnCode();
4520 }
4521
4522 void handleReturnCode() {
4523 targetArgs.doPostInstall(mRet);
4524 // TODO invoke pending move
4525 processPendingMove(this, mRet);
4526 }
4527
4528 public void handleServiceError() {
4529 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4530 handleReturnCode();
4531 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004532 };
4533
4534 private InstallArgs createInstallArgs(InstallParams params) {
4535 if (installOnSd(params.flags)) {
4536 return new SdInstallArgs(params);
4537 } else {
4538 return new FileInstallArgs(params);
4539 }
4540 }
4541
4542 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4543 if (installOnSd(flags)) {
4544 return new SdInstallArgs(fullCodePath, fullResourcePath);
4545 } else {
4546 return new FileInstallArgs(fullCodePath, fullResourcePath);
4547 }
4548 }
4549
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004550 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4551 if (installOnSd(flags)) {
4552 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4553 return new SdInstallArgs(packageURI, cid);
4554 } else {
4555 return new FileInstallArgs(packageURI, pkgName);
4556 }
4557 }
4558
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004559 static abstract class InstallArgs {
4560 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004561 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004562 final int flags;
4563 final Uri packageURI;
4564 final String installerPackageName;
4565
4566 InstallArgs(Uri packageURI,
4567 IPackageInstallObserver observer, int flags,
4568 String installerPackageName) {
4569 this.packageURI = packageURI;
4570 this.flags = flags;
4571 this.observer = observer;
4572 this.installerPackageName = installerPackageName;
4573 }
4574
4575 abstract void createCopyFile();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004576 abstract int copyApk(IMediaContainerService imcs, boolean temp);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004577 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004578 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004579 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004580 abstract String getCodePath();
4581 abstract String getResourcePath();
4582 // Need installer lock especially for dex file removal.
4583 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004584 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004585 }
4586
4587 class FileInstallArgs extends InstallArgs {
4588 File installDir;
4589 String codeFileName;
4590 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004591 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004592
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004593 FileInstallArgs(InstallParams params) {
4594 super(params.packageURI, params.observer,
4595 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004596 }
4597
4598 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4599 super(null, null, 0, null);
4600 File codeFile = new File(fullCodePath);
4601 installDir = codeFile.getParentFile();
4602 codeFileName = fullCodePath;
4603 resourceFileName = fullResourcePath;
4604 }
4605
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004606 FileInstallArgs(Uri packageURI, String pkgName) {
4607 super(packageURI, null, 0, null);
4608 boolean fwdLocked = isFwdLocked(flags);
4609 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4610 String apkName = getNextCodePath(null, pkgName, ".apk");
4611 codeFileName = new File(installDir, apkName + ".apk").getPath();
4612 resourceFileName = getResourcePathFromCodePath();
4613 }
4614
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004615 String getCodePath() {
4616 return codeFileName;
4617 }
4618
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004619 void createCopyFile() {
4620 boolean fwdLocked = isFwdLocked(flags);
4621 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4622 codeFileName = createTempPackageFile(installDir).getPath();
4623 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004624 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004625 }
4626
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004627 int copyApk(IMediaContainerService imcs, boolean temp) {
4628 if (temp) {
4629 // Generate temp file name
4630 createCopyFile();
4631 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004632 // Get a ParcelFileDescriptor to write to the output file
4633 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004634 if (!created) {
4635 try {
4636 codeFile.createNewFile();
4637 // Set permissions
4638 if (!setPermissions()) {
4639 // Failed setting permissions.
4640 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4641 }
4642 } catch (IOException e) {
4643 Log.w(TAG, "Failed to create file " + codeFile);
4644 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4645 }
4646 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004647 ParcelFileDescriptor out = null;
4648 try {
4649 out = ParcelFileDescriptor.open(codeFile,
4650 ParcelFileDescriptor.MODE_READ_WRITE);
4651 } catch (FileNotFoundException e) {
4652 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4653 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4654 }
4655 // Copy the resource now
4656 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4657 try {
4658 if (imcs.copyResource(packageURI, out)) {
4659 ret = PackageManager.INSTALL_SUCCEEDED;
4660 }
4661 } catch (RemoteException e) {
4662 } finally {
4663 try { if (out != null) out.close(); } catch (IOException e) {}
4664 }
4665 return ret;
4666 }
4667
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004668 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004669 if (status != PackageManager.INSTALL_SUCCEEDED) {
4670 cleanUp();
4671 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004672 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004673 }
4674
4675 boolean doRename(int status, final String pkgName, String oldCodePath) {
4676 if (status != PackageManager.INSTALL_SUCCEEDED) {
4677 cleanUp();
4678 return false;
4679 } else {
4680 // Rename based on packageName
4681 File codeFile = new File(getCodePath());
4682 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4683 File desFile = new File(installDir, apkName + ".apk");
4684 if (!codeFile.renameTo(desFile)) {
4685 return false;
4686 }
4687 // Reset paths since the file has been renamed.
4688 codeFileName = desFile.getPath();
4689 resourceFileName = getResourcePathFromCodePath();
4690 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004691 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004692 // Failed setting permissions.
4693 return false;
4694 }
4695 return true;
4696 }
4697 }
4698
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004699 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004700 if (status != PackageManager.INSTALL_SUCCEEDED) {
4701 cleanUp();
4702 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004703 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004704 }
4705
4706 String getResourcePath() {
4707 return resourceFileName;
4708 }
4709
4710 String getResourcePathFromCodePath() {
4711 String codePath = getCodePath();
4712 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4713 String apkNameOnly = getApkName(codePath);
4714 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4715 } else {
4716 return codePath;
4717 }
4718 }
4719
4720 private boolean cleanUp() {
4721 boolean ret = true;
4722 String sourceDir = getCodePath();
4723 String publicSourceDir = getResourcePath();
4724 if (sourceDir != null) {
4725 File sourceFile = new File(sourceDir);
4726 if (!sourceFile.exists()) {
4727 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4728 ret = false;
4729 }
4730 // Delete application's code and resources
4731 sourceFile.delete();
4732 }
4733 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4734 final File publicSourceFile = new File(publicSourceDir);
4735 if (!publicSourceFile.exists()) {
4736 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4737 }
4738 if (publicSourceFile.exists()) {
4739 publicSourceFile.delete();
4740 }
4741 }
4742 return ret;
4743 }
4744
4745 void cleanUpResourcesLI() {
4746 String sourceDir = getCodePath();
4747 if (cleanUp() && mInstaller != null) {
4748 int retCode = mInstaller.rmdex(sourceDir);
4749 if (retCode < 0) {
4750 Log.w(TAG, "Couldn't remove dex file for package: "
4751 + " at location "
4752 + sourceDir + ", retcode=" + retCode);
4753 // we don't consider this to be a failure of the core package deletion
4754 }
4755 }
4756 }
4757
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004758 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004759 // TODO Do this in a more elegant way later on. for now just a hack
4760 if (!isFwdLocked(flags)) {
4761 final int filePermissions =
4762 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4763 |FileUtils.S_IROTH;
4764 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4765 if (retCode != 0) {
4766 Log.e(TAG, "Couldn't set new package file permissions for " +
4767 getCodePath()
4768 + ". The return code was: " + retCode);
4769 // TODO Define new internal error
4770 return false;
4771 }
4772 return true;
4773 }
4774 return true;
4775 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004776
4777 boolean doPostDeleteLI(boolean delete) {
4778 cleanUpResourcesLI();
4779 return true;
4780 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004781 }
4782
4783 class SdInstallArgs extends InstallArgs {
4784 String cid;
4785 String cachePath;
4786 static final String RES_FILE_NAME = "pkg.apk";
4787
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004788 SdInstallArgs(InstallParams params) {
4789 super(params.packageURI, params.observer,
4790 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004791 }
4792
4793 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004794 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004795 // Extract cid from fullCodePath
4796 int eidx = fullCodePath.lastIndexOf("/");
4797 String subStr1 = fullCodePath.substring(0, eidx);
4798 int sidx = subStr1.lastIndexOf("/");
4799 cid = subStr1.substring(sidx+1, eidx);
4800 cachePath = subStr1;
4801 }
4802
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004803 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004804 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
4805 this.cid = cid;
4806 }
4807
4808 SdInstallArgs(Uri packageURI, String cid) {
4809 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004810 this.cid = cid;
4811 }
4812
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004813 void createCopyFile() {
4814 cid = getTempContainerId();
4815 }
4816
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004817 int copyApk(IMediaContainerService imcs, boolean temp) {
4818 if (temp) {
4819 createCopyFile();
4820 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004821 try {
4822 cachePath = imcs.copyResourceToContainer(
4823 packageURI, cid,
4824 getEncryptKey(), RES_FILE_NAME);
4825 } catch (RemoteException e) {
4826 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004827 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4828 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004829 }
4830
4831 @Override
4832 String getCodePath() {
4833 return cachePath + "/" + RES_FILE_NAME;
4834 }
4835
4836 @Override
4837 String getResourcePath() {
4838 return cachePath + "/" + RES_FILE_NAME;
4839 }
4840
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004841 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004842 if (status != PackageManager.INSTALL_SUCCEEDED) {
4843 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004844 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004845 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004846 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004847 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004848 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004849 if (cachePath == null) {
4850 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4851 }
4852 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004853 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004854 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004855 }
4856
4857 boolean doRename(int status, final String pkgName,
4858 String oldCodePath) {
4859 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004860 String newCachePath = null;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004861 final int RENAME_FAILED = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004862 final int MOUNT_FAILED = 2;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004863 final int PASS = 4;
4864 int errCode = RENAME_FAILED;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004865 String errMsg = "RENAME_FAILED";
4866 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004867 if (mounted) {
4868 // Unmount the container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004869 if (!PackageHelper.unMountSdDir(cid)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004870 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
4871 return false;
4872 }
4873 mounted = false;
4874 }
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004875 if (PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004876 errCode = MOUNT_FAILED;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004877 errMsg = "MOUNT_FAILED";
4878 if ((newCachePath = PackageHelper.mountSdDir(newCacheId,
4879 getEncryptKey(), Process.SYSTEM_UID)) != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004880 errCode = PASS;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004881 errMsg = "PASS";
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004882 }
4883 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004884 if (errCode != PASS) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004885 Log.i(TAG, "Failed to rename " + cid + " to " + newCacheId +
4886 " at path: " + cachePath + " to new path: " + newCachePath +
4887 "err = " + errMsg);
4888 // Mount old container?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004889 return false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004890 } else {
4891 Log.i(TAG, "Succesfully renamed " + cid + " to " + newCacheId +
4892 " at path: " + cachePath + " to new path: " + newCachePath);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004893 }
4894 cid = newCacheId;
4895 cachePath = newCachePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004896 return true;
4897 }
4898
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004899 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004900 if (status != PackageManager.INSTALL_SUCCEEDED) {
4901 cleanUp();
4902 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004903 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004904 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004905 PackageHelper.mountSdDir(cid,
4906 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004907 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004908 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004909 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004910 }
4911
4912 private void cleanUp() {
4913 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004914 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004915 }
4916
4917 void cleanUpResourcesLI() {
4918 String sourceFile = getCodePath();
4919 // Remove dex file
4920 if (mInstaller != null) {
4921 int retCode = mInstaller.rmdex(sourceFile.toString());
4922 if (retCode < 0) {
4923 Log.w(TAG, "Couldn't remove dex file for package: "
4924 + " at location "
4925 + sourceFile.toString() + ", retcode=" + retCode);
4926 // we don't consider this to be a failure of the core package deletion
4927 }
4928 }
4929 cleanUp();
4930 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004931
4932 boolean matchContainer(String app) {
4933 if (cid.startsWith(app)) {
4934 return true;
4935 }
4936 return false;
4937 }
4938
4939 String getPackageName() {
4940 int idx = cid.lastIndexOf("-");
4941 if (idx == -1) {
4942 return cid;
4943 }
4944 return cid.substring(0, idx);
4945 }
4946
4947 boolean doPostDeleteLI(boolean delete) {
4948 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004949 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004950 if (mounted) {
4951 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004952 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004953 }
4954 if (ret && delete) {
4955 cleanUpResourcesLI();
4956 }
4957 return ret;
4958 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004959 };
4960
4961 // Utility method used to create code paths based on package name and available index.
4962 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4963 String idxStr = "";
4964 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004965 // Fall back to default value of idx=1 if prefix is not
4966 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004967 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004968 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004969 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004970 if (subStr.endsWith(suffix)) {
4971 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004972 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004973 // If oldCodePath already contains prefix find out the
4974 // ending index to either increment or decrement.
4975 int sidx = subStr.lastIndexOf(prefix);
4976 if (sidx != -1) {
4977 subStr = subStr.substring(sidx + prefix.length());
4978 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004979 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
4980 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004981 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004982 try {
4983 idx = Integer.parseInt(subStr);
4984 if (idx <= 1) {
4985 idx++;
4986 } else {
4987 idx--;
4988 }
4989 } catch(NumberFormatException e) {
4990 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004991 }
4992 }
4993 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004994 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004995 return prefix + idxStr;
4996 }
4997
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004998 // Utility method used to ignore ADD/REMOVE events
4999 // by directory observer.
5000 private static boolean ignoreCodePath(String fullPathStr) {
5001 String apkName = getApkName(fullPathStr);
5002 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5003 if (idx != -1 && ((idx+1) < apkName.length())) {
5004 // Make sure the package ends with a numeral
5005 String version = apkName.substring(idx+1);
5006 try {
5007 Integer.parseInt(version);
5008 return true;
5009 } catch (NumberFormatException e) {}
5010 }
5011 return false;
5012 }
5013
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005014 // Utility method that returns the relative package path with respect
5015 // to the installation directory. Like say for /data/data/com.test-1.apk
5016 // string com.test-1 is returned.
5017 static String getApkName(String codePath) {
5018 if (codePath == null) {
5019 return null;
5020 }
5021 int sidx = codePath.lastIndexOf("/");
5022 int eidx = codePath.lastIndexOf(".");
5023 if (eidx == -1) {
5024 eidx = codePath.length();
5025 } else if (eidx == 0) {
5026 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
5027 return null;
5028 }
5029 return codePath.substring(sidx+1, eidx);
5030 }
5031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005032 class PackageInstalledInfo {
5033 String name;
5034 int uid;
5035 PackageParser.Package pkg;
5036 int returnCode;
5037 PackageRemovedInfo removedInfo;
5038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005040 /*
5041 * Install a non-existing package.
5042 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005043 private void installNewPackageLI(PackageParser.Package pkg,
5044 int parseFlags,
5045 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005046 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005047 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08005048 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005049 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005050
5051 if (useEncryptedFilesystemForPackage(pkg)) {
5052 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
5053 } else {
5054 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
5055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005056 res.name = pkgName;
5057 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005058 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005060 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005061 + " without first uninstalling.");
5062 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5063 return;
5064 }
5065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005066 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005067 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005068 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005069 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5071 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5072 }
5073 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005074 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005075 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005076 res);
5077 // delete the partially installed application. the data directory will have to be
5078 // restored if it was already existing
5079 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5080 // remove package from internal structures. Note that we want deletePackageX to
5081 // delete the package data and cache directories that it created in
5082 // scanPackageLocked, unless those directories existed before we even tried to
5083 // install.
5084 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005085 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5087 res.removedInfo);
5088 }
5089 }
5090 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005091
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005092 private void replacePackageLI(PackageParser.Package pkg,
5093 int parseFlags,
5094 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005095 String installerPackageName, PackageInstalledInfo res) {
5096
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005097 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005098 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099 // First find the old package info and check signatures
5100 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005101 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005102 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005103 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5105 return;
5106 }
5107 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005108 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005109 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005110 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005112 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005113 }
5114 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005117 PackageParser.Package pkg,
5118 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005119 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005120 PackageParser.Package newPackage = null;
5121 String pkgName = deletedPackage.packageName;
5122 boolean deletedPkg = true;
5123 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005124
Jacek Surazski65e13172009-04-28 15:26:38 +02005125 String oldInstallerPackageName = null;
5126 synchronized (mPackages) {
5127 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5128 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005129
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005130 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005131 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005132 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005133 res.removedInfo)) {
5134 // If the existing package was'nt successfully deleted
5135 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5136 deletedPkg = false;
5137 } else {
5138 // Successfully deleted the old package. Now proceed with re-installation
5139 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005140 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005141 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005142 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5144 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005145 }
5146 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005147 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005148 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005149 res);
5150 updatedSettings = true;
5151 }
5152 }
5153
5154 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5155 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005156 // were keeping around in case we needed them (see below) can now be deleted.
5157 // This info will be set on the res.removedInfo to clean up later on as post
5158 // install action.
5159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005160 //update signature on the new package setting
5161 //this should always succeed, since we checked the
5162 //signature earlier.
5163 synchronized(mPackages) {
5164 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5165 parseFlags, true);
5166 }
5167 } else {
5168 // remove package from internal structures. Note that we want deletePackageX to
5169 // delete the package data and cache directories that it created in
5170 // scanPackageLocked, unless those directories existed before we even tried to
5171 // install.
5172 if(updatedSettings) {
5173 deletePackageLI(
5174 pkgName, true,
5175 PackageManager.DONT_DELETE_DATA,
5176 res.removedInfo);
5177 }
5178 // Since we failed to install the new package we need to restore the old
5179 // package that we deleted.
5180 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005181 File restoreFile = new File(deletedPackage.mPath);
5182 if (restoreFile == null) {
5183 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
5184 return;
5185 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005186 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5187 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005188 // Parse old package
5189 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5190 scanPackageLI(restoreFile, parseFlags, scanMode);
5191 synchronized (mPackages) {
5192 grantPermissionsLP(deletedPackage, false);
5193 mSettings.writeLP();
5194 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005195 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5196 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
5197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 }
5199 }
5200 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005203 PackageParser.Package pkg,
5204 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005205 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005206 PackageParser.Package newPackage = null;
5207 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005208 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 PackageParser.PARSE_IS_SYSTEM;
5210 String packageName = deletedPackage.packageName;
5211 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5212 if (packageName == null) {
5213 Log.w(TAG, "Attempt to delete null packageName.");
5214 return;
5215 }
5216 PackageParser.Package oldPkg;
5217 PackageSetting oldPkgSetting;
5218 synchronized (mPackages) {
5219 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005220 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005221 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5222 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005223 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 return;
5225 }
5226 }
5227 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5228 res.removedInfo.removedPackage = packageName;
5229 // Remove existing system package
5230 removePackageLI(oldPkg, true);
5231 synchronized (mPackages) {
5232 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5233 }
5234
5235 // Successfully disabled the old package. Now proceed with re-installation
5236 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5237 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005238 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005239 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005240 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005241 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5242 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5243 }
5244 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005245 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 updatedSettings = true;
5247 }
5248
5249 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5250 //update signature on the new package setting
5251 //this should always succeed, since we checked the
5252 //signature earlier.
5253 synchronized(mPackages) {
5254 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5255 parseFlags, true);
5256 }
5257 } else {
5258 // Re installation failed. Restore old information
5259 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005260 if (newPackage != null) {
5261 removePackageLI(newPackage, true);
5262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005264 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005265 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005266 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005267 // Restore the old system information in Settings
5268 synchronized(mPackages) {
5269 if(updatedSettings) {
5270 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005271 mSettings.setInstallerPackageName(packageName,
5272 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 }
5274 mSettings.writeLP();
5275 }
5276 }
5277 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005278
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005279 // Utility method used to move dex files during install.
5280 private int moveDexFiles(PackageParser.Package newPackage) {
5281 int retCode;
5282 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5283 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5284 if (retCode != 0) {
5285 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5286 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5287 }
5288 }
5289 return PackageManager.INSTALL_SUCCEEDED;
5290 }
5291
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005292 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005293 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005294 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005295 synchronized (mPackages) {
5296 //write settings. the installStatus will be incomplete at this stage.
5297 //note that the new package setting would have already been
5298 //added to mPackages. It hasn't been persisted yet.
5299 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5300 mSettings.writeLP();
5301 }
5302
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005303 if ((res.returnCode = moveDexFiles(newPackage))
5304 != PackageManager.INSTALL_SUCCEEDED) {
5305 // Discontinue if moving dex files failed.
5306 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005307 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005308 if((res.returnCode = setPermissionsLI(newPackage))
5309 != PackageManager.INSTALL_SUCCEEDED) {
5310 if (mInstaller != null) {
5311 mInstaller.rmdex(newPackage.mScanPath);
5312 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005313 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005315 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005317 synchronized (mPackages) {
5318 grantPermissionsLP(newPackage, true);
5319 res.name = pkgName;
5320 res.uid = newPackage.applicationInfo.uid;
5321 res.pkg = newPackage;
5322 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005323 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005324 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5325 //to update install status
5326 mSettings.writeLP();
5327 }
5328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005329
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005330 private void installPackageLI(InstallArgs args,
5331 boolean newInstall, PackageInstalledInfo res) {
5332 int pFlags = args.flags;
5333 String installerPackageName = args.installerPackageName;
5334 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005335 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005336 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005337 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005338 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5339 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005340 // Result object to be returned
5341 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5342
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005343 // Retrieve PackageSettings and parse package
5344 int parseFlags = PackageParser.PARSE_CHATTY |
5345 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5346 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5347 parseFlags |= mDefParseFlags;
5348 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5349 pp.setSeparateProcesses(mSeparateProcesses);
5350 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5351 null, mMetrics, parseFlags);
5352 if (pkg == null) {
5353 res.returnCode = pp.getParseError();
5354 return;
5355 }
5356 String pkgName = res.name = pkg.packageName;
5357 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5358 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5359 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5360 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005362 }
5363 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5364 res.returnCode = pp.getParseError();
5365 return;
5366 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005367 // Get rid of all references to package scan path via parser.
5368 pp = null;
5369 String oldCodePath = null;
5370 boolean systemApp = false;
5371 synchronized (mPackages) {
5372 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005373 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5374 String oldName = mSettings.mRenamedPackages.get(pkgName);
5375 if (oldName != null && oldName.equals(pkg.mOriginalPackage)
5376 && mPackages.containsKey(oldName)) {
5377 // This package is derived from an original package,
5378 // and this device has been updating from that original
5379 // name. We must continue using the original name, so
5380 // rename the new package here.
5381 pkg.setPackageName(pkg.mOriginalPackage);
5382 pkgName = pkg.packageName;
5383 replace = true;
5384 } else if (mPackages.containsKey(pkgName)) {
5385 // This package, under its official name, already exists
5386 // on the device; we should replace it.
5387 replace = true;
5388 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005389 }
5390 PackageSetting ps = mSettings.mPackages.get(pkgName);
5391 if (ps != null) {
5392 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5393 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5394 systemApp = (ps.pkg.applicationInfo.flags &
5395 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005396 }
5397 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005398 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005399
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005400 if (systemApp && onSd) {
5401 // Disable updates to system apps on sdcard
5402 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5403 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5404 return;
5405 }
5406 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5407 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5408 return;
5409 }
5410 // Set application objects path explicitly after the rename
5411 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005412 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005413 replacePackageLI(pkg, parseFlags, scanMode,
5414 installerPackageName, res);
5415 } else {
5416 installNewPackageLI(pkg, parseFlags, scanMode,
5417 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005418 }
5419 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005420
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005421 private int setPermissionsLI(PackageParser.Package newPackage) {
5422 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005423 int retCode = 0;
5424 // TODO Gross hack but fix later. Ideally move this to be a post installation
5425 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005426 if ((newPackage.applicationInfo.flags
5427 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5428 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 try {
5430 extractPublicFiles(newPackage, destResourceFile);
5431 } catch (IOException e) {
5432 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5433 " forward-locked app.");
5434 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5435 } finally {
5436 //TODO clean up the extracted public files
5437 }
5438 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005439 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 newPackage.applicationInfo.uid);
5441 } else {
5442 final int filePermissions =
5443 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005444 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 newPackage.applicationInfo.uid);
5446 }
5447 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005448 // The permissions on the resource file was set when it was copied for
5449 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005453 Log.e(TAG, "Couldn't set new package file permissions for " +
5454 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005456 // TODO Define new internal error
5457 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 }
5459 return PackageManager.INSTALL_SUCCEEDED;
5460 }
5461
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005462 private boolean isForwardLocked(PackageParser.Package pkg) {
5463 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 }
5465
5466 private void extractPublicFiles(PackageParser.Package newPackage,
5467 File publicZipFile) throws IOException {
5468 final ZipOutputStream publicZipOutStream =
5469 new ZipOutputStream(new FileOutputStream(publicZipFile));
5470 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5471
5472 // Copy manifest, resources.arsc and res directory to public zip
5473
5474 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5475 while (privateZipEntries.hasMoreElements()) {
5476 final ZipEntry zipEntry = privateZipEntries.nextElement();
5477 final String zipEntryName = zipEntry.getName();
5478 if ("AndroidManifest.xml".equals(zipEntryName)
5479 || "resources.arsc".equals(zipEntryName)
5480 || zipEntryName.startsWith("res/")) {
5481 try {
5482 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5483 } catch (IOException e) {
5484 try {
5485 publicZipOutStream.close();
5486 throw e;
5487 } finally {
5488 publicZipFile.delete();
5489 }
5490 }
5491 }
5492 }
5493
5494 publicZipOutStream.close();
5495 FileUtils.setPermissions(
5496 publicZipFile.getAbsolutePath(),
5497 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5498 -1, -1);
5499 }
5500
5501 private static void copyZipEntry(ZipEntry zipEntry,
5502 ZipFile inZipFile,
5503 ZipOutputStream outZipStream) throws IOException {
5504 byte[] buffer = new byte[4096];
5505 int num;
5506
5507 ZipEntry newEntry;
5508 if (zipEntry.getMethod() == ZipEntry.STORED) {
5509 // Preserve the STORED method of the input entry.
5510 newEntry = new ZipEntry(zipEntry);
5511 } else {
5512 // Create a new entry so that the compressed len is recomputed.
5513 newEntry = new ZipEntry(zipEntry.getName());
5514 }
5515 outZipStream.putNextEntry(newEntry);
5516
5517 InputStream data = inZipFile.getInputStream(zipEntry);
5518 while ((num = data.read(buffer)) > 0) {
5519 outZipStream.write(buffer, 0, num);
5520 }
5521 outZipStream.flush();
5522 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 private void deleteTempPackageFiles() {
5525 FilenameFilter filter = new FilenameFilter() {
5526 public boolean accept(File dir, String name) {
5527 return name.startsWith("vmdl") && name.endsWith(".tmp");
5528 }
5529 };
5530 String tmpFilesList[] = mAppInstallDir.list(filter);
5531 if(tmpFilesList == null) {
5532 return;
5533 }
5534 for(int i = 0; i < tmpFilesList.length; i++) {
5535 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5536 tmpFile.delete();
5537 }
5538 }
5539
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005540 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 File tmpPackageFile;
5542 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005543 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 } catch (IOException e) {
5545 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5546 return null;
5547 }
5548 try {
5549 FileUtils.setPermissions(
5550 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5551 -1, -1);
5552 } catch (IOException e) {
5553 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5554 return null;
5555 }
5556 return tmpPackageFile;
5557 }
5558
5559 public void deletePackage(final String packageName,
5560 final IPackageDeleteObserver observer,
5561 final int flags) {
5562 mContext.enforceCallingOrSelfPermission(
5563 android.Manifest.permission.DELETE_PACKAGES, null);
5564 // Queue up an async operation since the package deletion may take a little while.
5565 mHandler.post(new Runnable() {
5566 public void run() {
5567 mHandler.removeCallbacks(this);
5568 final boolean succeded = deletePackageX(packageName, true, true, flags);
5569 if (observer != null) {
5570 try {
5571 observer.packageDeleted(succeded);
5572 } catch (RemoteException e) {
5573 Log.i(TAG, "Observer no longer exists.");
5574 } //end catch
5575 } //end if
5576 } //end run
5577 });
5578 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005580 /**
5581 * This method is an internal method that could be get invoked either
5582 * to delete an installed package or to clean up a failed installation.
5583 * After deleting an installed package, a broadcast is sent to notify any
5584 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005585 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 * installation wouldn't have sent the initial broadcast either
5587 * The key steps in deleting a package are
5588 * deleting the package information in internal structures like mPackages,
5589 * deleting the packages base directories through installd
5590 * updating mSettings to reflect current status
5591 * persisting settings for later use
5592 * sending a broadcast if necessary
5593 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5595 boolean deleteCodeAndResources, int flags) {
5596 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005597 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005598
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005599 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5600 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5601 try {
5602 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
5603 Log.w(TAG, "Not removing package " + packageName + ": has active device admin");
5604 return false;
5605 }
5606 } catch (RemoteException e) {
5607 }
5608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 synchronized (mInstallLock) {
5610 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005614 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5615 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5616
5617 // If the removed package was a system update, the old system packaged
5618 // was re-enabled; we need to broadcast this information
5619 if (systemUpdate) {
5620 Bundle extras = new Bundle(1);
5621 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5622 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5623
5624 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5625 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005628 // Delete the resources here after sending the broadcast to let
5629 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005630 if (info.args != null) {
5631 synchronized (mInstallLock) {
5632 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005633 }
5634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 return res;
5636 }
5637
5638 static class PackageRemovedInfo {
5639 String removedPackage;
5640 int uid = -1;
5641 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005642 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005643 // Clean up resources deleted packages.
5644 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 void sendBroadcast(boolean fullRemove, boolean replacing) {
5647 Bundle extras = new Bundle(1);
5648 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5649 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5650 if (replacing) {
5651 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5652 }
5653 if (removedPackage != null) {
5654 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5655 }
5656 if (removedUid >= 0) {
5657 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5658 }
5659 }
5660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 /*
5663 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5664 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005665 * 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 -08005666 * delete a partially installed application.
5667 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005668 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 int flags) {
5670 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005671 if (outInfo != null) {
5672 outInfo.removedPackage = packageName;
5673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 removePackageLI(p, true);
5675 // Retrieve object to delete permissions for shared user later on
5676 PackageSetting deletedPs;
5677 synchronized (mPackages) {
5678 deletedPs = mSettings.mPackages.get(packageName);
5679 }
5680 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005681 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005683 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 if (retCode < 0) {
5685 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5686 + packageName + ", retcode=" + retCode);
5687 // we don't consider this to be a failure of the core package deletion
5688 }
5689 } else {
5690 //for emulator
5691 PackageParser.Package pkg = mPackages.get(packageName);
5692 File dataDir = new File(pkg.applicationInfo.dataDir);
5693 dataDir.delete();
5694 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005695 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005697 if (outInfo != null) {
5698 outInfo.removedUid = mSettings.removePackageLP(packageName);
5699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700 }
5701 }
5702 synchronized (mPackages) {
5703 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5704 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005705 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005707 if (deletedPs != null) {
5708 // remove from preferred activities.
5709 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
5710 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
5711 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
5712 removed.add(pa);
5713 }
5714 }
5715 for (PreferredActivity pa : removed) {
5716 mSettings.mPreferredActivities.removeFilter(pa);
5717 }
5718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005720 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 }
5722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 /*
5725 * Tries to delete system package.
5726 */
5727 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005728 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 ApplicationInfo applicationInfo = p.applicationInfo;
5730 //applicable for non-partially installed applications only
5731 if (applicationInfo == null) {
5732 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5733 return false;
5734 }
5735 PackageSetting ps = null;
5736 // Confirm if the system package has been updated
5737 // An updated system app can be deleted. This will also have to restore
5738 // the system pkg from system partition
5739 synchronized (mPackages) {
5740 ps = mSettings.getDisabledSystemPkg(p.packageName);
5741 }
5742 if (ps == null) {
5743 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5744 return false;
5745 } else {
5746 Log.i(TAG, "Deleting system pkg from data partition");
5747 }
5748 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005749 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005750 boolean deleteCodeAndResources = false;
5751 if (ps.versionCode < p.mVersionCode) {
5752 // Delete code and resources for downgrades
5753 deleteCodeAndResources = true;
5754 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5755 flags &= ~PackageManager.DONT_DELETE_DATA;
5756 }
5757 } else {
5758 // Preserve data by setting flag
5759 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5760 flags |= PackageManager.DONT_DELETE_DATA;
5761 }
5762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5764 if (!ret) {
5765 return false;
5766 }
5767 synchronized (mPackages) {
5768 // Reinstate the old system package
5769 mSettings.enableSystemPackageLP(p.packageName);
5770 }
5771 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005772 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005774 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005776 if (newPkg == null) {
5777 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5778 return false;
5779 }
5780 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005781 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 mSettings.writeLP();
5783 }
5784 return true;
5785 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5788 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5789 ApplicationInfo applicationInfo = p.applicationInfo;
5790 if (applicationInfo == null) {
5791 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5792 return false;
5793 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005794 if (outInfo != null) {
5795 outInfo.uid = applicationInfo.uid;
5796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797
5798 // Delete package data from internal structures and also remove data if flag is set
5799 removePackageDataLI(p, outInfo, flags);
5800
5801 // Delete application code and resources
5802 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005803 // TODO can pick up from PackageSettings as well
5804 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005805 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005806 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5807 PackageManager.INSTALL_FORWARD_LOCK : 0;
5808 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005809 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005810 }
5811 return true;
5812 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 /*
5815 * This method handles package deletion in general
5816 */
5817 private boolean deletePackageLI(String packageName,
5818 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5819 if (packageName == null) {
5820 Log.w(TAG, "Attempt to delete null packageName.");
5821 return false;
5822 }
5823 PackageParser.Package p;
5824 boolean dataOnly = false;
5825 synchronized (mPackages) {
5826 p = mPackages.get(packageName);
5827 if (p == null) {
5828 //this retrieves partially installed apps
5829 dataOnly = true;
5830 PackageSetting ps = mSettings.mPackages.get(packageName);
5831 if (ps == null) {
5832 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5833 return false;
5834 }
5835 p = ps.pkg;
5836 }
5837 }
5838 if (p == null) {
5839 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5840 return false;
5841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 if (dataOnly) {
5844 // Delete application data first
5845 removePackageDataLI(p, outInfo, flags);
5846 return true;
5847 }
5848 // At this point the package should have ApplicationInfo associated with it
5849 if (p.applicationInfo == null) {
5850 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5851 return false;
5852 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005853 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5855 Log.i(TAG, "Removing system package:"+p.packageName);
5856 // When an updated system application is deleted we delete the existing resources as well and
5857 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005858 ret = deleteSystemPackageLI(p, flags, outInfo);
5859 } else {
5860 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005861 // Kill application pre-emptively especially for apps on sd.
5862 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005863 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005865 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 public void clearApplicationUserData(final String packageName,
5869 final IPackageDataObserver observer) {
5870 mContext.enforceCallingOrSelfPermission(
5871 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5872 // Queue up an async operation since the package deletion may take a little while.
5873 mHandler.post(new Runnable() {
5874 public void run() {
5875 mHandler.removeCallbacks(this);
5876 final boolean succeeded;
5877 synchronized (mInstallLock) {
5878 succeeded = clearApplicationUserDataLI(packageName);
5879 }
5880 if (succeeded) {
5881 // invoke DeviceStorageMonitor's update method to clear any notifications
5882 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5883 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5884 if (dsm != null) {
5885 dsm.updateMemory();
5886 }
5887 }
5888 if(observer != null) {
5889 try {
5890 observer.onRemoveCompleted(packageName, succeeded);
5891 } catch (RemoteException e) {
5892 Log.i(TAG, "Observer no longer exists.");
5893 }
5894 } //end if observer
5895 } //end run
5896 });
5897 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 private boolean clearApplicationUserDataLI(String packageName) {
5900 if (packageName == null) {
5901 Log.w(TAG, "Attempt to delete null packageName.");
5902 return false;
5903 }
5904 PackageParser.Package p;
5905 boolean dataOnly = false;
5906 synchronized (mPackages) {
5907 p = mPackages.get(packageName);
5908 if(p == null) {
5909 dataOnly = true;
5910 PackageSetting ps = mSettings.mPackages.get(packageName);
5911 if((ps == null) || (ps.pkg == null)) {
5912 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5913 return false;
5914 }
5915 p = ps.pkg;
5916 }
5917 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005918 boolean useEncryptedFSDir = false;
5919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005920 if(!dataOnly) {
5921 //need to check this only for fully installed applications
5922 if (p == null) {
5923 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5924 return false;
5925 }
5926 final ApplicationInfo applicationInfo = p.applicationInfo;
5927 if (applicationInfo == null) {
5928 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5929 return false;
5930 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005931 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005932 }
5933 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005934 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005935 if (retCode < 0) {
5936 Log.w(TAG, "Couldn't remove cache files for package: "
5937 + packageName);
5938 return false;
5939 }
5940 }
5941 return true;
5942 }
5943
5944 public void deleteApplicationCacheFiles(final String packageName,
5945 final IPackageDataObserver observer) {
5946 mContext.enforceCallingOrSelfPermission(
5947 android.Manifest.permission.DELETE_CACHE_FILES, null);
5948 // Queue up an async operation since the package deletion may take a little while.
5949 mHandler.post(new Runnable() {
5950 public void run() {
5951 mHandler.removeCallbacks(this);
5952 final boolean succeded;
5953 synchronized (mInstallLock) {
5954 succeded = deleteApplicationCacheFilesLI(packageName);
5955 }
5956 if(observer != null) {
5957 try {
5958 observer.onRemoveCompleted(packageName, succeded);
5959 } catch (RemoteException e) {
5960 Log.i(TAG, "Observer no longer exists.");
5961 }
5962 } //end if observer
5963 } //end run
5964 });
5965 }
5966
5967 private boolean deleteApplicationCacheFilesLI(String packageName) {
5968 if (packageName == null) {
5969 Log.w(TAG, "Attempt to delete null packageName.");
5970 return false;
5971 }
5972 PackageParser.Package p;
5973 synchronized (mPackages) {
5974 p = mPackages.get(packageName);
5975 }
5976 if (p == null) {
5977 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5978 return false;
5979 }
5980 final ApplicationInfo applicationInfo = p.applicationInfo;
5981 if (applicationInfo == null) {
5982 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5983 return false;
5984 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005985 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005986 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005987 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 if (retCode < 0) {
5989 Log.w(TAG, "Couldn't remove cache files for package: "
5990 + packageName);
5991 return false;
5992 }
5993 }
5994 return true;
5995 }
5996
5997 public void getPackageSizeInfo(final String packageName,
5998 final IPackageStatsObserver observer) {
5999 mContext.enforceCallingOrSelfPermission(
6000 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6001 // Queue up an async operation since the package deletion may take a little while.
6002 mHandler.post(new Runnable() {
6003 public void run() {
6004 mHandler.removeCallbacks(this);
6005 PackageStats lStats = new PackageStats(packageName);
6006 final boolean succeded;
6007 synchronized (mInstallLock) {
6008 succeded = getPackageSizeInfoLI(packageName, lStats);
6009 }
6010 if(observer != null) {
6011 try {
6012 observer.onGetStatsCompleted(lStats, succeded);
6013 } catch (RemoteException e) {
6014 Log.i(TAG, "Observer no longer exists.");
6015 }
6016 } //end if observer
6017 } //end run
6018 });
6019 }
6020
6021 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6022 if (packageName == null) {
6023 Log.w(TAG, "Attempt to get size of null packageName.");
6024 return false;
6025 }
6026 PackageParser.Package p;
6027 boolean dataOnly = false;
6028 synchronized (mPackages) {
6029 p = mPackages.get(packageName);
6030 if(p == null) {
6031 dataOnly = true;
6032 PackageSetting ps = mSettings.mPackages.get(packageName);
6033 if((ps == null) || (ps.pkg == null)) {
6034 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6035 return false;
6036 }
6037 p = ps.pkg;
6038 }
6039 }
6040 String publicSrcDir = null;
6041 if(!dataOnly) {
6042 final ApplicationInfo applicationInfo = p.applicationInfo;
6043 if (applicationInfo == null) {
6044 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6045 return false;
6046 }
6047 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6048 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006049 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 if (mInstaller != null) {
6051 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006052 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 if (res < 0) {
6054 return false;
6055 } else {
6056 return true;
6057 }
6058 }
6059 return true;
6060 }
6061
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006063 public void addPackageToPreferred(String packageName) {
6064 mContext.enforceCallingOrSelfPermission(
6065 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006066 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006067 }
6068
6069 public void removePackageFromPreferred(String packageName) {
6070 mContext.enforceCallingOrSelfPermission(
6071 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006072 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006073 }
6074
6075 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006076 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 }
6078
6079 public void addPreferredActivity(IntentFilter filter, int match,
6080 ComponentName[] set, ComponentName activity) {
6081 mContext.enforceCallingOrSelfPermission(
6082 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6083
6084 synchronized (mPackages) {
6085 Log.i(TAG, "Adding preferred activity " + activity + ":");
6086 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6087 mSettings.mPreferredActivities.addFilter(
6088 new PreferredActivity(filter, match, set, activity));
6089 mSettings.writeLP();
6090 }
6091 }
6092
Satish Sampath8dbe6122009-06-02 23:35:54 +01006093 public void replacePreferredActivity(IntentFilter filter, int match,
6094 ComponentName[] set, ComponentName activity) {
6095 mContext.enforceCallingOrSelfPermission(
6096 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6097 if (filter.countActions() != 1) {
6098 throw new IllegalArgumentException(
6099 "replacePreferredActivity expects filter to have only 1 action.");
6100 }
6101 if (filter.countCategories() != 1) {
6102 throw new IllegalArgumentException(
6103 "replacePreferredActivity expects filter to have only 1 category.");
6104 }
6105 if (filter.countDataAuthorities() != 0
6106 || filter.countDataPaths() != 0
6107 || filter.countDataSchemes() != 0
6108 || filter.countDataTypes() != 0) {
6109 throw new IllegalArgumentException(
6110 "replacePreferredActivity expects filter to have no data authorities, " +
6111 "paths, schemes or types.");
6112 }
6113 synchronized (mPackages) {
6114 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6115 String action = filter.getAction(0);
6116 String category = filter.getCategory(0);
6117 while (it.hasNext()) {
6118 PreferredActivity pa = it.next();
6119 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6120 it.remove();
6121 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6122 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6123 }
6124 }
6125 addPreferredActivity(filter, match, set, activity);
6126 }
6127 }
6128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 public void clearPackagePreferredActivities(String packageName) {
6130 mContext.enforceCallingOrSelfPermission(
6131 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6132
6133 synchronized (mPackages) {
6134 if (clearPackagePreferredActivitiesLP(packageName)) {
6135 mSettings.writeLP();
6136 }
6137 }
6138 }
6139
6140 boolean clearPackagePreferredActivitiesLP(String packageName) {
6141 boolean changed = false;
6142 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6143 while (it.hasNext()) {
6144 PreferredActivity pa = it.next();
6145 if (pa.mActivity.getPackageName().equals(packageName)) {
6146 it.remove();
6147 changed = true;
6148 }
6149 }
6150 return changed;
6151 }
6152
6153 public int getPreferredActivities(List<IntentFilter> outFilters,
6154 List<ComponentName> outActivities, String packageName) {
6155
6156 int num = 0;
6157 synchronized (mPackages) {
6158 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6159 while (it.hasNext()) {
6160 PreferredActivity pa = it.next();
6161 if (packageName == null
6162 || pa.mActivity.getPackageName().equals(packageName)) {
6163 if (outFilters != null) {
6164 outFilters.add(new IntentFilter(pa));
6165 }
6166 if (outActivities != null) {
6167 outActivities.add(pa.mActivity);
6168 }
6169 }
6170 }
6171 }
6172
6173 return num;
6174 }
6175
6176 public void setApplicationEnabledSetting(String appPackageName,
6177 int newState, int flags) {
6178 setEnabledSetting(appPackageName, null, newState, flags);
6179 }
6180
6181 public void setComponentEnabledSetting(ComponentName componentName,
6182 int newState, int flags) {
6183 setEnabledSetting(componentName.getPackageName(),
6184 componentName.getClassName(), newState, flags);
6185 }
6186
6187 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006188 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6190 || newState == COMPONENT_ENABLED_STATE_ENABLED
6191 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6192 throw new IllegalArgumentException("Invalid new component state: "
6193 + newState);
6194 }
6195 PackageSetting pkgSetting;
6196 final int uid = Binder.getCallingUid();
6197 final int permission = mContext.checkCallingPermission(
6198 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6199 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006200 boolean sendNow = false;
6201 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006202 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006204 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006206 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006208 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006210 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 }
6212 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006213 "Unknown component: " + packageName
6214 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 }
6216 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6217 throw new SecurityException(
6218 "Permission Denial: attempt to change component state from pid="
6219 + Binder.getCallingPid()
6220 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6221 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006222 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 // We're dealing with an application/package level state change
6224 pkgSetting.enabled = newState;
6225 } else {
6226 // We're dealing with a component level state change
6227 switch (newState) {
6228 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006229 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 break;
6231 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006232 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 break;
6234 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006235 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 break;
6237 default:
6238 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006239 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240 }
6241 }
6242 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006243 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006244 components = mPendingBroadcasts.get(packageName);
6245 boolean newPackage = components == null;
6246 if (newPackage) {
6247 components = new ArrayList<String>();
6248 }
6249 if (!components.contains(componentName)) {
6250 components.add(componentName);
6251 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006252 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6253 sendNow = true;
6254 // Purge entry from pending broadcast list if another one exists already
6255 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006256 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006257 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006258 if (newPackage) {
6259 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006260 }
6261 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6262 // Schedule a message
6263 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6264 }
6265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 long callingId = Binder.clearCallingIdentity();
6269 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006270 if (sendNow) {
6271 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006272 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 } finally {
6275 Binder.restoreCallingIdentity(callingId);
6276 }
6277 }
6278
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006279 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006280 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6281 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6282 + " components=" + componentNames);
6283 Bundle extras = new Bundle(4);
6284 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6285 String nameList[] = new String[componentNames.size()];
6286 componentNames.toArray(nameList);
6287 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006288 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6289 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006290 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006291 }
6292
Jacek Surazski65e13172009-04-28 15:26:38 +02006293 public String getInstallerPackageName(String packageName) {
6294 synchronized (mPackages) {
6295 PackageSetting pkg = mSettings.mPackages.get(packageName);
6296 if (pkg == null) {
6297 throw new IllegalArgumentException("Unknown package: " + packageName);
6298 }
6299 return pkg.installerPackageName;
6300 }
6301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 public int getApplicationEnabledSetting(String appPackageName) {
6304 synchronized (mPackages) {
6305 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6306 if (pkg == null) {
6307 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6308 }
6309 return pkg.enabled;
6310 }
6311 }
6312
6313 public int getComponentEnabledSetting(ComponentName componentName) {
6314 synchronized (mPackages) {
6315 final String packageNameStr = componentName.getPackageName();
6316 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6317 if (pkg == null) {
6318 throw new IllegalArgumentException("Unknown component: " + componentName);
6319 }
6320 final String classNameStr = componentName.getClassName();
6321 return pkg.currentEnabledStateLP(classNameStr);
6322 }
6323 }
6324
6325 public void enterSafeMode() {
6326 if (!mSystemReady) {
6327 mSafeMode = true;
6328 }
6329 }
6330
6331 public void systemReady() {
6332 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006333
6334 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006335 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006336 mContext.getContentResolver(),
6337 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006338 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006339 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006340 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 }
6343
6344 public boolean isSafeMode() {
6345 return mSafeMode;
6346 }
6347
6348 public boolean hasSystemUidErrors() {
6349 return mHasSystemUidErrors;
6350 }
6351
6352 static String arrayToString(int[] array) {
6353 StringBuffer buf = new StringBuffer(128);
6354 buf.append('[');
6355 if (array != null) {
6356 for (int i=0; i<array.length; i++) {
6357 if (i > 0) buf.append(", ");
6358 buf.append(array[i]);
6359 }
6360 }
6361 buf.append(']');
6362 return buf.toString();
6363 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 @Override
6366 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6367 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6368 != PackageManager.PERMISSION_GRANTED) {
6369 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6370 + Binder.getCallingPid()
6371 + ", uid=" + Binder.getCallingUid()
6372 + " without permission "
6373 + android.Manifest.permission.DUMP);
6374 return;
6375 }
6376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 synchronized (mPackages) {
6378 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006379 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 pw.println(" ");
6381 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006382 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 pw.println(" ");
6384 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006385 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 pw.println(" ");
6387 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006388 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 pw.println("Permissions:");
6391 {
6392 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006393 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6394 pw.print(Integer.toHexString(System.identityHashCode(p)));
6395 pw.println("):");
6396 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6397 pw.print(" uid="); pw.print(p.uid);
6398 pw.print(" gids="); pw.print(arrayToString(p.gids));
6399 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 }
6401 }
6402 pw.println(" ");
6403 pw.println("Packages:");
6404 {
6405 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006406 pw.print(" Package [");
6407 pw.print(ps.realName != null ? ps.realName : ps.name);
6408 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006409 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6410 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006411 if (ps.realName != null) {
6412 pw.print(" compat name="); pw.println(ps.name);
6413 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006414 pw.print(" userId="); pw.print(ps.userId);
6415 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6416 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6417 pw.print(" pkg="); pw.println(ps.pkg);
6418 pw.print(" codePath="); pw.println(ps.codePathString);
6419 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006421 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006422 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006423 pw.print(" supportsScreens=[");
6424 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006425 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006426 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006427 if (!first) pw.print(", ");
6428 first = false;
6429 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006430 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006431 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006432 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006433 if (!first) pw.print(", ");
6434 first = false;
6435 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006436 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006437 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006438 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006439 if (!first) pw.print(", ");
6440 first = false;
6441 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006443 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006444 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006445 if (!first) pw.print(", ");
6446 first = false;
6447 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006448 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006449 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006450 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6451 if (!first) pw.print(", ");
6452 first = false;
6453 pw.print("anyDensity");
6454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006456 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006457 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6458 pw.print(" signatures="); pw.println(ps.signatures);
6459 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6460 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6461 pw.print(" installStatus="); pw.print(ps.installStatus);
6462 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463 if (ps.disabledComponents.size() > 0) {
6464 pw.println(" disabledComponents:");
6465 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006466 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 }
6468 }
6469 if (ps.enabledComponents.size() > 0) {
6470 pw.println(" enabledComponents:");
6471 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006472 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 }
6474 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006475 if (ps.grantedPermissions.size() > 0) {
6476 pw.println(" grantedPermissions:");
6477 for (String s : ps.grantedPermissions) {
6478 pw.print(" "); pw.println(s);
6479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006480 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006481 if (ps.loadedPermissions.size() > 0) {
6482 pw.println(" loadedPermissions:");
6483 for (String s : ps.loadedPermissions) {
6484 pw.print(" "); pw.println(s);
6485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 }
6487 }
6488 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006489 if (mSettings.mRenamedPackages.size() > 0) {
6490 pw.println(" ");
6491 pw.println("Renamed packages:");
6492 for (HashMap.Entry<String, String> e
6493 : mSettings.mRenamedPackages.entrySet()) {
6494 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6495 pw.println(e.getValue());
6496 }
6497 }
6498 if (mSettings.mDisabledSysPackages.size() > 0) {
6499 pw.println(" ");
6500 pw.println("Hidden system packages:");
6501 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6502 pw.print(" Package [");
6503 pw.print(ps.realName != null ? ps.realName : ps.name);
6504 pw.print("] (");
6505 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6506 pw.println("):");
6507 if (ps.realName != null) {
6508 pw.print(" compat name="); pw.println(ps.name);
6509 }
6510 pw.print(" userId="); pw.println(ps.userId);
6511 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6512 pw.print(" codePath="); pw.println(ps.codePathString);
6513 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6514 }
6515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 pw.println(" ");
6517 pw.println("Shared Users:");
6518 {
6519 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006520 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6521 pw.print(Integer.toHexString(System.identityHashCode(su)));
6522 pw.println("):");
6523 pw.print(" userId="); pw.print(su.userId);
6524 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 pw.println(" grantedPermissions:");
6526 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006527 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 }
6529 pw.println(" loadedPermissions:");
6530 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006531 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 }
6533 }
6534 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 pw.println(" ");
6537 pw.println("Settings parse messages:");
6538 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006539
6540 pw.println(" ");
6541 pw.println("Package warning messages:");
6542 File fname = getSettingsProblemFile();
6543 FileInputStream in;
6544 try {
6545 in = new FileInputStream(fname);
6546 int avail = in.available();
6547 byte[] data = new byte[avail];
6548 in.read(data);
6549 pw.println(new String(data));
6550 } catch (FileNotFoundException e) {
6551 } catch (IOException e) {
6552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006553 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006554
6555 synchronized (mProviders) {
6556 pw.println(" ");
6557 pw.println("Registered ContentProviders:");
6558 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006559 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006560 pw.println(p.toString());
6561 }
6562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006563 }
6564
6565 static final class BasePermission {
6566 final static int TYPE_NORMAL = 0;
6567 final static int TYPE_BUILTIN = 1;
6568 final static int TYPE_DYNAMIC = 2;
6569
6570 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006571 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 final int type;
6573 PackageParser.Permission perm;
6574 PermissionInfo pendingInfo;
6575 int uid;
6576 int[] gids;
6577
6578 BasePermission(String _name, String _sourcePackage, int _type) {
6579 name = _name;
6580 sourcePackage = _sourcePackage;
6581 type = _type;
6582 }
6583 }
6584
6585 static class PackageSignatures {
6586 private Signature[] mSignatures;
6587
6588 PackageSignatures(Signature[] sigs) {
6589 assignSignatures(sigs);
6590 }
6591
6592 PackageSignatures() {
6593 }
6594
6595 void writeXml(XmlSerializer serializer, String tagName,
6596 ArrayList<Signature> pastSignatures) throws IOException {
6597 if (mSignatures == null) {
6598 return;
6599 }
6600 serializer.startTag(null, tagName);
6601 serializer.attribute(null, "count",
6602 Integer.toString(mSignatures.length));
6603 for (int i=0; i<mSignatures.length; i++) {
6604 serializer.startTag(null, "cert");
6605 final Signature sig = mSignatures[i];
6606 final int sigHash = sig.hashCode();
6607 final int numPast = pastSignatures.size();
6608 int j;
6609 for (j=0; j<numPast; j++) {
6610 Signature pastSig = pastSignatures.get(j);
6611 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6612 serializer.attribute(null, "index", Integer.toString(j));
6613 break;
6614 }
6615 }
6616 if (j >= numPast) {
6617 pastSignatures.add(sig);
6618 serializer.attribute(null, "index", Integer.toString(numPast));
6619 serializer.attribute(null, "key", sig.toCharsString());
6620 }
6621 serializer.endTag(null, "cert");
6622 }
6623 serializer.endTag(null, tagName);
6624 }
6625
6626 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6627 throws IOException, XmlPullParserException {
6628 String countStr = parser.getAttributeValue(null, "count");
6629 if (countStr == null) {
6630 reportSettingsProblem(Log.WARN,
6631 "Error in package manager settings: <signatures> has"
6632 + " no count at " + parser.getPositionDescription());
6633 XmlUtils.skipCurrentTag(parser);
6634 }
6635 final int count = Integer.parseInt(countStr);
6636 mSignatures = new Signature[count];
6637 int pos = 0;
6638
6639 int outerDepth = parser.getDepth();
6640 int type;
6641 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6642 && (type != XmlPullParser.END_TAG
6643 || parser.getDepth() > outerDepth)) {
6644 if (type == XmlPullParser.END_TAG
6645 || type == XmlPullParser.TEXT) {
6646 continue;
6647 }
6648
6649 String tagName = parser.getName();
6650 if (tagName.equals("cert")) {
6651 if (pos < count) {
6652 String index = parser.getAttributeValue(null, "index");
6653 if (index != null) {
6654 try {
6655 int idx = Integer.parseInt(index);
6656 String key = parser.getAttributeValue(null, "key");
6657 if (key == null) {
6658 if (idx >= 0 && idx < pastSignatures.size()) {
6659 Signature sig = pastSignatures.get(idx);
6660 if (sig != null) {
6661 mSignatures[pos] = pastSignatures.get(idx);
6662 pos++;
6663 } else {
6664 reportSettingsProblem(Log.WARN,
6665 "Error in package manager settings: <cert> "
6666 + "index " + index + " is not defined at "
6667 + parser.getPositionDescription());
6668 }
6669 } else {
6670 reportSettingsProblem(Log.WARN,
6671 "Error in package manager settings: <cert> "
6672 + "index " + index + " is out of bounds at "
6673 + parser.getPositionDescription());
6674 }
6675 } else {
6676 while (pastSignatures.size() <= idx) {
6677 pastSignatures.add(null);
6678 }
6679 Signature sig = new Signature(key);
6680 pastSignatures.set(idx, sig);
6681 mSignatures[pos] = sig;
6682 pos++;
6683 }
6684 } catch (NumberFormatException e) {
6685 reportSettingsProblem(Log.WARN,
6686 "Error in package manager settings: <cert> "
6687 + "index " + index + " is not a number at "
6688 + parser.getPositionDescription());
6689 }
6690 } else {
6691 reportSettingsProblem(Log.WARN,
6692 "Error in package manager settings: <cert> has"
6693 + " no index at " + parser.getPositionDescription());
6694 }
6695 } else {
6696 reportSettingsProblem(Log.WARN,
6697 "Error in package manager settings: too "
6698 + "many <cert> tags, expected " + count
6699 + " at " + parser.getPositionDescription());
6700 }
6701 } else {
6702 reportSettingsProblem(Log.WARN,
6703 "Unknown element under <cert>: "
6704 + parser.getName());
6705 }
6706 XmlUtils.skipCurrentTag(parser);
6707 }
6708
6709 if (pos < count) {
6710 // Should never happen -- there is an error in the written
6711 // settings -- but if it does we don't want to generate
6712 // a bad array.
6713 Signature[] newSigs = new Signature[pos];
6714 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6715 mSignatures = newSigs;
6716 }
6717 }
6718
6719 /**
6720 * If any of the given 'sigs' is contained in the existing signatures,
6721 * then completely replace the current signatures with the ones in
6722 * 'sigs'. This is used for updating an existing package to a newly
6723 * installed version.
6724 */
6725 boolean updateSignatures(Signature[] sigs, boolean update) {
6726 if (mSignatures == null) {
6727 if (update) {
6728 assignSignatures(sigs);
6729 }
6730 return true;
6731 }
6732 if (sigs == null) {
6733 return false;
6734 }
6735
6736 for (int i=0; i<sigs.length; i++) {
6737 Signature sig = sigs[i];
6738 for (int j=0; j<mSignatures.length; j++) {
6739 if (mSignatures[j].equals(sig)) {
6740 if (update) {
6741 assignSignatures(sigs);
6742 }
6743 return true;
6744 }
6745 }
6746 }
6747 return false;
6748 }
6749
6750 /**
6751 * If any of the given 'sigs' is contained in the existing signatures,
6752 * then add in any new signatures found in 'sigs'. This is used for
6753 * including a new package into an existing shared user id.
6754 */
6755 boolean mergeSignatures(Signature[] sigs, boolean update) {
6756 if (mSignatures == null) {
6757 if (update) {
6758 assignSignatures(sigs);
6759 }
6760 return true;
6761 }
6762 if (sigs == null) {
6763 return false;
6764 }
6765
6766 Signature[] added = null;
6767 int addedCount = 0;
6768 boolean haveMatch = false;
6769 for (int i=0; i<sigs.length; i++) {
6770 Signature sig = sigs[i];
6771 boolean found = false;
6772 for (int j=0; j<mSignatures.length; j++) {
6773 if (mSignatures[j].equals(sig)) {
6774 found = true;
6775 haveMatch = true;
6776 break;
6777 }
6778 }
6779
6780 if (!found) {
6781 if (added == null) {
6782 added = new Signature[sigs.length];
6783 }
6784 added[i] = sig;
6785 addedCount++;
6786 }
6787 }
6788
6789 if (!haveMatch) {
6790 // Nothing matched -- reject the new signatures.
6791 return false;
6792 }
6793 if (added == null) {
6794 // Completely matched -- nothing else to do.
6795 return true;
6796 }
6797
6798 // Add additional signatures in.
6799 if (update) {
6800 Signature[] total = new Signature[addedCount+mSignatures.length];
6801 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6802 int j = mSignatures.length;
6803 for (int i=0; i<added.length; i++) {
6804 if (added[i] != null) {
6805 total[j] = added[i];
6806 j++;
6807 }
6808 }
6809 mSignatures = total;
6810 }
6811 return true;
6812 }
6813
6814 private void assignSignatures(Signature[] sigs) {
6815 if (sigs == null) {
6816 mSignatures = null;
6817 return;
6818 }
6819 mSignatures = new Signature[sigs.length];
6820 for (int i=0; i<sigs.length; i++) {
6821 mSignatures[i] = sigs[i];
6822 }
6823 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006825 @Override
6826 public String toString() {
6827 StringBuffer buf = new StringBuffer(128);
6828 buf.append("PackageSignatures{");
6829 buf.append(Integer.toHexString(System.identityHashCode(this)));
6830 buf.append(" [");
6831 if (mSignatures != null) {
6832 for (int i=0; i<mSignatures.length; i++) {
6833 if (i > 0) buf.append(", ");
6834 buf.append(Integer.toHexString(
6835 System.identityHashCode(mSignatures[i])));
6836 }
6837 }
6838 buf.append("]}");
6839 return buf.toString();
6840 }
6841 }
6842
6843 static class PreferredActivity extends IntentFilter {
6844 final int mMatch;
6845 final String[] mSetPackages;
6846 final String[] mSetClasses;
6847 final String[] mSetComponents;
6848 final ComponentName mActivity;
6849 final String mShortActivity;
6850 String mParseError;
6851
6852 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6853 ComponentName activity) {
6854 super(filter);
6855 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6856 mActivity = activity;
6857 mShortActivity = activity.flattenToShortString();
6858 mParseError = null;
6859 if (set != null) {
6860 final int N = set.length;
6861 String[] myPackages = new String[N];
6862 String[] myClasses = new String[N];
6863 String[] myComponents = new String[N];
6864 for (int i=0; i<N; i++) {
6865 ComponentName cn = set[i];
6866 if (cn == null) {
6867 mSetPackages = null;
6868 mSetClasses = null;
6869 mSetComponents = null;
6870 return;
6871 }
6872 myPackages[i] = cn.getPackageName().intern();
6873 myClasses[i] = cn.getClassName().intern();
6874 myComponents[i] = cn.flattenToShortString().intern();
6875 }
6876 mSetPackages = myPackages;
6877 mSetClasses = myClasses;
6878 mSetComponents = myComponents;
6879 } else {
6880 mSetPackages = null;
6881 mSetClasses = null;
6882 mSetComponents = null;
6883 }
6884 }
6885
6886 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6887 IOException {
6888 mShortActivity = parser.getAttributeValue(null, "name");
6889 mActivity = ComponentName.unflattenFromString(mShortActivity);
6890 if (mActivity == null) {
6891 mParseError = "Bad activity name " + mShortActivity;
6892 }
6893 String matchStr = parser.getAttributeValue(null, "match");
6894 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6895 String setCountStr = parser.getAttributeValue(null, "set");
6896 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6897
6898 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6899 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6900 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6901
6902 int setPos = 0;
6903
6904 int outerDepth = parser.getDepth();
6905 int type;
6906 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6907 && (type != XmlPullParser.END_TAG
6908 || parser.getDepth() > outerDepth)) {
6909 if (type == XmlPullParser.END_TAG
6910 || type == XmlPullParser.TEXT) {
6911 continue;
6912 }
6913
6914 String tagName = parser.getName();
6915 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6916 // + parser.getDepth() + " tag=" + tagName);
6917 if (tagName.equals("set")) {
6918 String name = parser.getAttributeValue(null, "name");
6919 if (name == null) {
6920 if (mParseError == null) {
6921 mParseError = "No name in set tag in preferred activity "
6922 + mShortActivity;
6923 }
6924 } else if (setPos >= setCount) {
6925 if (mParseError == null) {
6926 mParseError = "Too many set tags in preferred activity "
6927 + mShortActivity;
6928 }
6929 } else {
6930 ComponentName cn = ComponentName.unflattenFromString(name);
6931 if (cn == null) {
6932 if (mParseError == null) {
6933 mParseError = "Bad set name " + name + " in preferred activity "
6934 + mShortActivity;
6935 }
6936 } else {
6937 myPackages[setPos] = cn.getPackageName();
6938 myClasses[setPos] = cn.getClassName();
6939 myComponents[setPos] = name;
6940 setPos++;
6941 }
6942 }
6943 XmlUtils.skipCurrentTag(parser);
6944 } else if (tagName.equals("filter")) {
6945 //Log.i(TAG, "Starting to parse filter...");
6946 readFromXml(parser);
6947 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6948 // + parser.getDepth() + " tag=" + parser.getName());
6949 } else {
6950 reportSettingsProblem(Log.WARN,
6951 "Unknown element under <preferred-activities>: "
6952 + parser.getName());
6953 XmlUtils.skipCurrentTag(parser);
6954 }
6955 }
6956
6957 if (setPos != setCount) {
6958 if (mParseError == null) {
6959 mParseError = "Not enough set tags (expected " + setCount
6960 + " but found " + setPos + ") in " + mShortActivity;
6961 }
6962 }
6963
6964 mSetPackages = myPackages;
6965 mSetClasses = myClasses;
6966 mSetComponents = myComponents;
6967 }
6968
6969 public void writeToXml(XmlSerializer serializer) throws IOException {
6970 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6971 serializer.attribute(null, "name", mShortActivity);
6972 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6973 serializer.attribute(null, "set", Integer.toString(NS));
6974 for (int s=0; s<NS; s++) {
6975 serializer.startTag(null, "set");
6976 serializer.attribute(null, "name", mSetComponents[s]);
6977 serializer.endTag(null, "set");
6978 }
6979 serializer.startTag(null, "filter");
6980 super.writeToXml(serializer);
6981 serializer.endTag(null, "filter");
6982 }
6983
6984 boolean sameSet(List<ResolveInfo> query, int priority) {
6985 if (mSetPackages == null) return false;
6986 final int NQ = query.size();
6987 final int NS = mSetPackages.length;
6988 int numMatch = 0;
6989 for (int i=0; i<NQ; i++) {
6990 ResolveInfo ri = query.get(i);
6991 if (ri.priority != priority) continue;
6992 ActivityInfo ai = ri.activityInfo;
6993 boolean good = false;
6994 for (int j=0; j<NS; j++) {
6995 if (mSetPackages[j].equals(ai.packageName)
6996 && mSetClasses[j].equals(ai.name)) {
6997 numMatch++;
6998 good = true;
6999 break;
7000 }
7001 }
7002 if (!good) return false;
7003 }
7004 return numMatch == NS;
7005 }
7006 }
7007
7008 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007009 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 HashSet<String> grantedPermissions = new HashSet<String>();
7012 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007016 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007017 setFlags(pkgFlags);
7018 }
7019
7020 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007021 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007022 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
7023 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 }
7025 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 /**
7028 * Settings base class for pending and resolved classes.
7029 */
7030 static class PackageSettingBase extends GrantedPermissions {
7031 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007032 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007033 File codePath;
7034 String codePathString;
7035 File resourcePath;
7036 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 private long timeStamp;
7038 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007039 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007041 boolean uidError;
7042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 PackageSignatures signatures = new PackageSignatures();
7044
7045 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007047 /* Explicitly disabled components */
7048 HashSet<String> disabledComponents = new HashSet<String>(0);
7049 /* Explicitly enabled components */
7050 HashSet<String> enabledComponents = new HashSet<String>(0);
7051 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7052 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007053
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007054 PackageSettingBase origPackage;
7055
Jacek Surazski65e13172009-04-28 15:26:38 +02007056 /* package name of the app that installed this package */
7057 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007058
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007059 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007060 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 super(pkgFlags);
7062 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007063 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007064 init(codePath, resourcePath, pVersionCode);
7065 }
7066
7067 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007068 this.codePath = codePath;
7069 this.codePathString = codePath.toString();
7070 this.resourcePath = resourcePath;
7071 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007072 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007074
Jacek Surazski65e13172009-04-28 15:26:38 +02007075 public void setInstallerPackageName(String packageName) {
7076 installerPackageName = packageName;
7077 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007078
Jacek Surazski65e13172009-04-28 15:26:38 +02007079 String getInstallerPackageName() {
7080 return installerPackageName;
7081 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 public void setInstallStatus(int newStatus) {
7084 installStatus = newStatus;
7085 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 public int getInstallStatus() {
7088 return installStatus;
7089 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007091 public void setTimeStamp(long newStamp) {
7092 if (newStamp != timeStamp) {
7093 timeStamp = newStamp;
7094 timeStampString = Long.toString(newStamp);
7095 }
7096 }
7097
7098 public void setTimeStamp(long newStamp, String newStampStr) {
7099 timeStamp = newStamp;
7100 timeStampString = newStampStr;
7101 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 public long getTimeStamp() {
7104 return timeStamp;
7105 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 public String getTimeStampStr() {
7108 return timeStampString;
7109 }
7110
7111 public void copyFrom(PackageSettingBase base) {
7112 grantedPermissions = base.grantedPermissions;
7113 gids = base.gids;
7114 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007116 timeStamp = base.timeStamp;
7117 timeStampString = base.timeStampString;
7118 signatures = base.signatures;
7119 permissionsFixed = base.permissionsFixed;
7120 disabledComponents = base.disabledComponents;
7121 enabledComponents = base.enabledComponents;
7122 enabled = base.enabled;
7123 installStatus = base.installStatus;
7124 }
7125
7126 void enableComponentLP(String componentClassName) {
7127 disabledComponents.remove(componentClassName);
7128 enabledComponents.add(componentClassName);
7129 }
7130
7131 void disableComponentLP(String componentClassName) {
7132 enabledComponents.remove(componentClassName);
7133 disabledComponents.add(componentClassName);
7134 }
7135
7136 void restoreComponentLP(String componentClassName) {
7137 enabledComponents.remove(componentClassName);
7138 disabledComponents.remove(componentClassName);
7139 }
7140
7141 int currentEnabledStateLP(String componentName) {
7142 if (enabledComponents.contains(componentName)) {
7143 return COMPONENT_ENABLED_STATE_ENABLED;
7144 } else if (disabledComponents.contains(componentName)) {
7145 return COMPONENT_ENABLED_STATE_DISABLED;
7146 } else {
7147 return COMPONENT_ENABLED_STATE_DEFAULT;
7148 }
7149 }
7150 }
7151
7152 /**
7153 * Settings data for a particular package we know about.
7154 */
7155 static final class PackageSetting extends PackageSettingBase {
7156 int userId;
7157 PackageParser.Package pkg;
7158 SharedUserSetting sharedUser;
7159
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007160 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007161 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007162 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007163 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007165 @Override
7166 public String toString() {
7167 return "PackageSetting{"
7168 + Integer.toHexString(System.identityHashCode(this))
7169 + " " + name + "/" + userId + "}";
7170 }
7171 }
7172
7173 /**
7174 * Settings data for a particular shared user ID we know about.
7175 */
7176 static final class SharedUserSetting extends GrantedPermissions {
7177 final String name;
7178 int userId;
7179 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7180 final PackageSignatures signatures = new PackageSignatures();
7181
7182 SharedUserSetting(String _name, int _pkgFlags) {
7183 super(_pkgFlags);
7184 name = _name;
7185 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 @Override
7188 public String toString() {
7189 return "SharedUserSetting{"
7190 + Integer.toHexString(System.identityHashCode(this))
7191 + " " + name + "/" + userId + "}";
7192 }
7193 }
7194
7195 /**
7196 * Holds information about dynamic settings.
7197 */
7198 private static final class Settings {
7199 private final File mSettingsFilename;
7200 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007201 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007202 private final HashMap<String, PackageSetting> mPackages =
7203 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 // List of replaced system applications
7205 final HashMap<String, PackageSetting> mDisabledSysPackages =
7206 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 // The user's preferred activities associated with particular intent
7209 // filters.
7210 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7211 new IntentResolver<PreferredActivity, PreferredActivity>() {
7212 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007213 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007214 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007215 out.print(prefix); out.print(
7216 Integer.toHexString(System.identityHashCode(filter)));
7217 out.print(' ');
7218 out.print(filter.mActivity.flattenToShortString());
7219 out.print(" match=0x");
7220 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007222 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007223 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007224 out.print(prefix); out.print(" ");
7225 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007226 }
7227 }
7228 }
7229 };
7230 private final HashMap<String, SharedUserSetting> mSharedUsers =
7231 new HashMap<String, SharedUserSetting>();
7232 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7233 private final SparseArray<Object> mOtherUserIds =
7234 new SparseArray<Object>();
7235
7236 // For reading/writing settings file.
7237 private final ArrayList<Signature> mPastSignatures =
7238 new ArrayList<Signature>();
7239
7240 // Mapping from permission names to info about them.
7241 final HashMap<String, BasePermission> mPermissions =
7242 new HashMap<String, BasePermission>();
7243
7244 // Mapping from permission tree names to info about them.
7245 final HashMap<String, BasePermission> mPermissionTrees =
7246 new HashMap<String, BasePermission>();
7247
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007248 // Packages that have been uninstalled and still need their external
7249 // storage data deleted.
7250 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7251
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007252 // Packages that have been renamed since they were first installed.
7253 // Keys are the new names of the packages, values are the original
7254 // names. The packages appear everwhere else under their original
7255 // names.
7256 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007258 private final StringBuilder mReadMessages = new StringBuilder();
7259
7260 private static final class PendingPackage extends PackageSettingBase {
7261 final int sharedId;
7262
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007263 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007264 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007265 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 this.sharedId = sharedId;
7267 }
7268 }
7269 private final ArrayList<PendingPackage> mPendingPackages
7270 = new ArrayList<PendingPackage>();
7271
7272 Settings() {
7273 File dataDir = Environment.getDataDirectory();
7274 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007275 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7276 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007277 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007278 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007279 FileUtils.setPermissions(systemDir.toString(),
7280 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7281 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7282 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007283 FileUtils.setPermissions(systemSecureDir.toString(),
7284 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7285 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7286 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 mSettingsFilename = new File(systemDir, "packages.xml");
7288 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007289 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007290 }
7291
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007292 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007293 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007294 int pkgFlags, boolean create, boolean add) {
7295 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007296 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007297 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007298 return p;
7299 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007300
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007301 PackageSetting peekPackageLP(String name) {
7302 return mPackages.get(name);
7303 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007304 PackageSetting p = mPackages.get(name);
7305 if (p != null && p.codePath.getPath().equals(codePath)) {
7306 return p;
7307 }
7308 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007309 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007312 void setInstallStatus(String pkgName, int status) {
7313 PackageSetting p = mPackages.get(pkgName);
7314 if(p != null) {
7315 if(p.getInstallStatus() != status) {
7316 p.setInstallStatus(status);
7317 }
7318 }
7319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007320
Jacek Surazski65e13172009-04-28 15:26:38 +02007321 void setInstallerPackageName(String pkgName,
7322 String installerPkgName) {
7323 PackageSetting p = mPackages.get(pkgName);
7324 if(p != null) {
7325 p.setInstallerPackageName(installerPkgName);
7326 }
7327 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007328
Jacek Surazski65e13172009-04-28 15:26:38 +02007329 String getInstallerPackageName(String pkgName) {
7330 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007331 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007332 }
7333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 int getInstallStatus(String pkgName) {
7335 PackageSetting p = mPackages.get(pkgName);
7336 if(p != null) {
7337 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007339 return -1;
7340 }
7341
7342 SharedUserSetting getSharedUserLP(String name,
7343 int pkgFlags, boolean create) {
7344 SharedUserSetting s = mSharedUsers.get(name);
7345 if (s == null) {
7346 if (!create) {
7347 return null;
7348 }
7349 s = new SharedUserSetting(name, pkgFlags);
7350 if (MULTIPLE_APPLICATION_UIDS) {
7351 s.userId = newUserIdLP(s);
7352 } else {
7353 s.userId = FIRST_APPLICATION_UID;
7354 }
7355 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7356 // < 0 means we couldn't assign a userid; fall out and return
7357 // s, which is currently null
7358 if (s.userId >= 0) {
7359 mSharedUsers.put(name, s);
7360 }
7361 }
7362
7363 return s;
7364 }
7365
7366 int disableSystemPackageLP(String name) {
7367 PackageSetting p = mPackages.get(name);
7368 if(p == null) {
7369 Log.w(TAG, "Package:"+name+" is not an installed package");
7370 return -1;
7371 }
7372 PackageSetting dp = mDisabledSysPackages.get(name);
7373 // always make sure the system package code and resource paths dont change
7374 if(dp == null) {
7375 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7376 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7377 }
7378 mDisabledSysPackages.put(name, p);
7379 }
7380 return removePackageLP(name);
7381 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007383 PackageSetting enableSystemPackageLP(String name) {
7384 PackageSetting p = mDisabledSysPackages.get(name);
7385 if(p == null) {
7386 Log.w(TAG, "Package:"+name+" is not disabled");
7387 return null;
7388 }
7389 // Reset flag in ApplicationInfo object
7390 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7391 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7392 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007393 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007394 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395 mDisabledSysPackages.remove(name);
7396 return ret;
7397 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007398
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007399 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007400 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007401 PackageSetting p = mPackages.get(name);
7402 if (p != null) {
7403 if (p.userId == uid) {
7404 return p;
7405 }
7406 reportSettingsProblem(Log.ERROR,
7407 "Adding duplicate package, keeping first: " + name);
7408 return null;
7409 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007410 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007411 p.userId = uid;
7412 if (addUserIdLP(uid, p, name)) {
7413 mPackages.put(name, p);
7414 return p;
7415 }
7416 return null;
7417 }
7418
7419 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7420 SharedUserSetting s = mSharedUsers.get(name);
7421 if (s != null) {
7422 if (s.userId == uid) {
7423 return s;
7424 }
7425 reportSettingsProblem(Log.ERROR,
7426 "Adding duplicate shared user, keeping first: " + name);
7427 return null;
7428 }
7429 s = new SharedUserSetting(name, pkgFlags);
7430 s.userId = uid;
7431 if (addUserIdLP(uid, s, name)) {
7432 mSharedUsers.put(name, s);
7433 return s;
7434 }
7435 return null;
7436 }
7437
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007438 // Transfer ownership of permissions from one package to another.
7439 private void transferPermissions(String origPkg, String newPkg) {
7440 // Transfer ownership of permissions to the new package.
7441 for (int i=0; i<2; i++) {
7442 HashMap<String, BasePermission> permissions =
7443 i == 0 ? mPermissionTrees : mPermissions;
7444 for (BasePermission bp : permissions.values()) {
7445 if (origPkg.equals(bp.sourcePackage)) {
7446 if (DEBUG_UPGRADE) Log.v(TAG,
7447 "Moving permission " + bp.name
7448 + " from pkg " + bp.sourcePackage
7449 + " to " + newPkg);
7450 bp.sourcePackage = newPkg;
7451 bp.perm = null;
7452 if (bp.pendingInfo != null) {
7453 bp.sourcePackage = newPkg;
7454 }
7455 bp.uid = 0;
7456 bp.gids = null;
7457 }
7458 }
7459 }
7460 }
7461
7462 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007463 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007464 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007465 PackageSetting p = mPackages.get(name);
7466 if (p != null) {
7467 if (!p.codePath.equals(codePath)) {
7468 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007469 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007470 // This is an updated system app with versions in both system
7471 // and data partition. Just let the most recent version
7472 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007473 Log.w(TAG, "Trying to update system app code path from " +
7474 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007475 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007476 // Just a change in the code path is not an issue, but
7477 // let's log a message about it.
7478 Log.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007479 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007481 }
7482 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 reportSettingsProblem(Log.WARN,
7484 "Package " + name + " shared user changed from "
7485 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7486 + " to "
7487 + (sharedUser != null ? sharedUser.name : "<nothing>")
7488 + "; replacing with new");
7489 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007490 } else {
7491 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7492 // If what we are scanning is a system package, then
7493 // make it so, regardless of whether it was previously
7494 // installed only in the data partition.
7495 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007497 }
7498 }
7499 if (p == null) {
7500 // Create a new PackageSettings entry. this can end up here because
7501 // of code path mismatch or user id mismatch of an updated system partition
7502 if (!create) {
7503 return null;
7504 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007505 if (origPackage != null) {
7506 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007507 p = new PackageSetting(origPackage.name, name, codePath,
7508 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007509 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7510 + " is adopting original package " + origPackage.name);
7511 p.copyFrom(origPackage);
7512 p.sharedUser = origPackage.sharedUser;
7513 p.userId = origPackage.userId;
7514 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007515 mRenamedPackages.put(name, origPackage.name);
7516 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007517 // Update new package state.
7518 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007519 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007520 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007521 p.setTimeStamp(codePath.lastModified());
7522 p.sharedUser = sharedUser;
7523 if (sharedUser != null) {
7524 p.userId = sharedUser.userId;
7525 } else if (MULTIPLE_APPLICATION_UIDS) {
7526 // Clone the setting here for disabled system packages
7527 PackageSetting dis = mDisabledSysPackages.get(name);
7528 if (dis != null) {
7529 // For disabled packages a new setting is created
7530 // from the existing user id. This still has to be
7531 // added to list of user id's
7532 // Copy signatures from previous setting
7533 if (dis.signatures.mSignatures != null) {
7534 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7535 }
7536 p.userId = dis.userId;
7537 // Clone permissions
7538 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7539 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7540 // Clone component info
7541 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7542 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7543 // Add new setting to list of user ids
7544 addUserIdLP(p.userId, p, name);
7545 } else {
7546 // Assign new user id
7547 p.userId = newUserIdLP(p);
7548 }
7549 } else {
7550 p.userId = FIRST_APPLICATION_UID;
7551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 }
7553 if (p.userId < 0) {
7554 reportSettingsProblem(Log.WARN,
7555 "Package " + name + " could not be assigned a valid uid");
7556 return null;
7557 }
7558 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007559 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007561 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 }
7563 }
7564 return p;
7565 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007566
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007567 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007568 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007569 String codePath = pkg.applicationInfo.sourceDir;
7570 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007571 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007572 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007573 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007574 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007575 p.codePath = new File(codePath);
7576 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007577 }
7578 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007579 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007580 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007581 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007582 p.resourcePath = new File(resourcePath);
7583 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007584 }
7585 // Update version code if needed
7586 if (pkg.mVersionCode != p.versionCode) {
7587 p.versionCode = pkg.mVersionCode;
7588 }
7589 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7590 }
7591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 // Utility method that adds a PackageSetting to mPackages and
7593 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007594 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007595 SharedUserSetting sharedUser) {
7596 mPackages.put(name, p);
7597 if (sharedUser != null) {
7598 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7599 reportSettingsProblem(Log.ERROR,
7600 "Package " + p.name + " was user "
7601 + p.sharedUser + " but is now " + sharedUser
7602 + "; I am not changing its files so it will probably fail!");
7603 p.sharedUser.packages.remove(p);
7604 } else if (p.userId != sharedUser.userId) {
7605 reportSettingsProblem(Log.ERROR,
7606 "Package " + p.name + " was user id " + p.userId
7607 + " but is now user " + sharedUser
7608 + " with id " + sharedUser.userId
7609 + "; I am not changing its files so it will probably fail!");
7610 }
7611
7612 sharedUser.packages.add(p);
7613 p.sharedUser = sharedUser;
7614 p.userId = sharedUser.userId;
7615 }
7616 }
7617
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007618 /*
7619 * Update the shared user setting when a package using
7620 * specifying the shared user id is removed. The gids
7621 * associated with each permission of the deleted package
7622 * are removed from the shared user's gid list only if its
7623 * not in use by other permissions of packages in the
7624 * shared user setting.
7625 */
7626 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7628 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7629 return;
7630 }
7631 // No sharedUserId
7632 if (deletedPs.sharedUser == null) {
7633 return;
7634 }
7635 SharedUserSetting sus = deletedPs.sharedUser;
7636 // Update permissions
7637 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7638 boolean used = false;
7639 if (!sus.grantedPermissions.contains (eachPerm)) {
7640 continue;
7641 }
7642 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007643 if (pkg.pkg != null &&
7644 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7645 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007646 used = true;
7647 break;
7648 }
7649 }
7650 if (!used) {
7651 // can safely delete this permission from list
7652 sus.grantedPermissions.remove(eachPerm);
7653 sus.loadedPermissions.remove(eachPerm);
7654 }
7655 }
7656 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007657 int newGids[] = globalGids;
7658 for (String eachPerm : sus.grantedPermissions) {
7659 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007660 if (bp != null) {
7661 newGids = appendInts(newGids, bp.gids);
7662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007663 }
7664 sus.gids = newGids;
7665 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 private int removePackageLP(String name) {
7668 PackageSetting p = mPackages.get(name);
7669 if (p != null) {
7670 mPackages.remove(name);
7671 if (p.sharedUser != null) {
7672 p.sharedUser.packages.remove(p);
7673 if (p.sharedUser.packages.size() == 0) {
7674 mSharedUsers.remove(p.sharedUser.name);
7675 removeUserIdLP(p.sharedUser.userId);
7676 return p.sharedUser.userId;
7677 }
7678 } else {
7679 removeUserIdLP(p.userId);
7680 return p.userId;
7681 }
7682 }
7683 return -1;
7684 }
7685
7686 private boolean addUserIdLP(int uid, Object obj, Object name) {
7687 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7688 return false;
7689 }
7690
7691 if (uid >= FIRST_APPLICATION_UID) {
7692 int N = mUserIds.size();
7693 final int index = uid - FIRST_APPLICATION_UID;
7694 while (index >= N) {
7695 mUserIds.add(null);
7696 N++;
7697 }
7698 if (mUserIds.get(index) != null) {
7699 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007700 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 + " name=" + name);
7702 return false;
7703 }
7704 mUserIds.set(index, obj);
7705 } else {
7706 if (mOtherUserIds.get(uid) != null) {
7707 reportSettingsProblem(Log.ERROR,
7708 "Adding duplicate shared id: " + uid
7709 + " name=" + name);
7710 return false;
7711 }
7712 mOtherUserIds.put(uid, obj);
7713 }
7714 return true;
7715 }
7716
7717 public Object getUserIdLP(int uid) {
7718 if (uid >= FIRST_APPLICATION_UID) {
7719 int N = mUserIds.size();
7720 final int index = uid - FIRST_APPLICATION_UID;
7721 return index < N ? mUserIds.get(index) : null;
7722 } else {
7723 return mOtherUserIds.get(uid);
7724 }
7725 }
7726
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007727 private Set<String> findPackagesWithFlag(int flag) {
7728 Set<String> ret = new HashSet<String>();
7729 for (PackageSetting ps : mPackages.values()) {
7730 // Has to match atleast all the flag bits set on flag
7731 if ((ps.pkgFlags & flag) == flag) {
7732 ret.add(ps.name);
7733 }
7734 }
7735 return ret;
7736 }
7737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 private void removeUserIdLP(int uid) {
7739 if (uid >= FIRST_APPLICATION_UID) {
7740 int N = mUserIds.size();
7741 final int index = uid - FIRST_APPLICATION_UID;
7742 if (index < N) mUserIds.set(index, null);
7743 } else {
7744 mOtherUserIds.remove(uid);
7745 }
7746 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 void writeLP() {
7749 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7750
7751 // Keep the old settings around until we know the new ones have
7752 // been successfully written.
7753 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007754 // Presence of backup settings file indicates that we failed
7755 // to persist settings earlier. So preserve the older
7756 // backup for future reference since the current settings
7757 // might have been corrupted.
7758 if (!mBackupSettingsFilename.exists()) {
7759 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7760 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7761 return;
7762 }
7763 } else {
7764 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007766 }
7767
7768 mPastSignatures.clear();
7769
7770 try {
7771 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7772
7773 //XmlSerializer serializer = XmlUtils.serializerInstance();
7774 XmlSerializer serializer = new FastXmlSerializer();
7775 serializer.setOutput(str, "utf-8");
7776 serializer.startDocument(null, true);
7777 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7778
7779 serializer.startTag(null, "packages");
7780
7781 serializer.startTag(null, "permission-trees");
7782 for (BasePermission bp : mPermissionTrees.values()) {
7783 writePermission(serializer, bp);
7784 }
7785 serializer.endTag(null, "permission-trees");
7786
7787 serializer.startTag(null, "permissions");
7788 for (BasePermission bp : mPermissions.values()) {
7789 writePermission(serializer, bp);
7790 }
7791 serializer.endTag(null, "permissions");
7792
7793 for (PackageSetting pkg : mPackages.values()) {
7794 writePackage(serializer, pkg);
7795 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7798 writeDisabledSysPackage(serializer, pkg);
7799 }
7800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 serializer.startTag(null, "preferred-activities");
7802 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7803 serializer.startTag(null, "item");
7804 pa.writeToXml(serializer);
7805 serializer.endTag(null, "item");
7806 }
7807 serializer.endTag(null, "preferred-activities");
7808
7809 for (SharedUserSetting usr : mSharedUsers.values()) {
7810 serializer.startTag(null, "shared-user");
7811 serializer.attribute(null, "name", usr.name);
7812 serializer.attribute(null, "userId",
7813 Integer.toString(usr.userId));
7814 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7815 serializer.startTag(null, "perms");
7816 for (String name : usr.grantedPermissions) {
7817 serializer.startTag(null, "item");
7818 serializer.attribute(null, "name", name);
7819 serializer.endTag(null, "item");
7820 }
7821 serializer.endTag(null, "perms");
7822 serializer.endTag(null, "shared-user");
7823 }
7824
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007825 if (mPackagesToBeCleaned.size() > 0) {
7826 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7827 serializer.startTag(null, "cleaning-package");
7828 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7829 serializer.endTag(null, "cleaning-package");
7830 }
7831 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007832
7833 if (mRenamedPackages.size() > 0) {
7834 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
7835 serializer.startTag(null, "renamed-package");
7836 serializer.attribute(null, "new", e.getKey());
7837 serializer.attribute(null, "old", e.getValue());
7838 serializer.endTag(null, "renamed-package");
7839 }
7840 }
7841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 serializer.endTag(null, "packages");
7843
7844 serializer.endDocument();
7845
7846 str.flush();
7847 str.close();
7848
7849 // New settings successfully written, old ones are no longer
7850 // needed.
7851 mBackupSettingsFilename.delete();
7852 FileUtils.setPermissions(mSettingsFilename.toString(),
7853 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7854 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7855 |FileUtils.S_IROTH,
7856 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007857
7858 // Write package list file now, use a JournaledFile.
7859 //
7860 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
7861 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
7862
7863 str = new FileOutputStream(journal.chooseForWrite());
7864 try {
7865 StringBuilder sb = new StringBuilder();
7866 for (PackageSetting pkg : mPackages.values()) {
7867 ApplicationInfo ai = pkg.pkg.applicationInfo;
7868 String dataPath = ai.dataDir;
7869 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7870
7871 // Avoid any application that has a space in its path
7872 // or that is handled by the system.
7873 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
7874 continue;
7875
7876 // we store on each line the following information for now:
7877 //
7878 // pkgName - package name
7879 // userId - application-specific user id
7880 // debugFlag - 0 or 1 if the package is debuggable.
7881 // dataPath - path to package's data path
7882 //
7883 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
7884 //
7885 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
7886 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
7887 // system/core/run-as/run-as.c
7888 //
7889 sb.setLength(0);
7890 sb.append(ai.packageName);
7891 sb.append(" ");
7892 sb.append((int)ai.uid);
7893 sb.append(isDebug ? " 1 " : " 0 ");
7894 sb.append(dataPath);
7895 sb.append("\n");
7896 str.write(sb.toString().getBytes());
7897 }
7898 str.flush();
7899 str.close();
7900 journal.commit();
7901 }
7902 catch (Exception e) {
7903 journal.rollback();
7904 }
7905
7906 FileUtils.setPermissions(mPackageListFilename.toString(),
7907 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7908 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7909 |FileUtils.S_IROTH,
7910 -1, -1);
7911
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007912 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007913
7914 } catch(XmlPullParserException e) {
7915 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 -08007916 } catch(java.io.IOException e) {
7917 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 -08007918 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007919 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007920 if (mSettingsFilename.exists()) {
7921 if (!mSettingsFilename.delete()) {
7922 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7923 }
7924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925 //Debug.stopMethodTracing();
7926 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007927
7928 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007929 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 serializer.startTag(null, "updated-package");
7931 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007932 if (pkg.realName != null) {
7933 serializer.attribute(null, "realName", pkg.realName);
7934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007935 serializer.attribute(null, "codePath", pkg.codePathString);
7936 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007937 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007938 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7939 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7940 }
7941 if (pkg.sharedUser == null) {
7942 serializer.attribute(null, "userId",
7943 Integer.toString(pkg.userId));
7944 } else {
7945 serializer.attribute(null, "sharedUserId",
7946 Integer.toString(pkg.userId));
7947 }
7948 serializer.startTag(null, "perms");
7949 if (pkg.sharedUser == null) {
7950 // If this is a shared user, the permissions will
7951 // be written there. We still need to write an
7952 // empty permissions list so permissionsFixed will
7953 // be set.
7954 for (final String name : pkg.grantedPermissions) {
7955 BasePermission bp = mPermissions.get(name);
7956 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7957 // We only need to write signature or system permissions but this wont
7958 // match the semantics of grantedPermissions. So write all permissions.
7959 serializer.startTag(null, "item");
7960 serializer.attribute(null, "name", name);
7961 serializer.endTag(null, "item");
7962 }
7963 }
7964 }
7965 serializer.endTag(null, "perms");
7966 serializer.endTag(null, "updated-package");
7967 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007968
7969 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007970 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 serializer.startTag(null, "package");
7972 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007973 if (pkg.realName != null) {
7974 serializer.attribute(null, "realName", pkg.realName);
7975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007976 serializer.attribute(null, "codePath", pkg.codePathString);
7977 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7978 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7979 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007980 serializer.attribute(null, "flags",
7981 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007983 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 if (pkg.sharedUser == null) {
7985 serializer.attribute(null, "userId",
7986 Integer.toString(pkg.userId));
7987 } else {
7988 serializer.attribute(null, "sharedUserId",
7989 Integer.toString(pkg.userId));
7990 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007991 if (pkg.uidError) {
7992 serializer.attribute(null, "uidError", "true");
7993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007994 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7995 serializer.attribute(null, "enabled",
7996 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7997 ? "true" : "false");
7998 }
7999 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8000 serializer.attribute(null, "installStatus", "false");
8001 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008002 if (pkg.installerPackageName != null) {
8003 serializer.attribute(null, "installer", pkg.installerPackageName);
8004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8006 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8007 serializer.startTag(null, "perms");
8008 if (pkg.sharedUser == null) {
8009 // If this is a shared user, the permissions will
8010 // be written there. We still need to write an
8011 // empty permissions list so permissionsFixed will
8012 // be set.
8013 for (final String name : pkg.grantedPermissions) {
8014 serializer.startTag(null, "item");
8015 serializer.attribute(null, "name", name);
8016 serializer.endTag(null, "item");
8017 }
8018 }
8019 serializer.endTag(null, "perms");
8020 }
8021 if (pkg.disabledComponents.size() > 0) {
8022 serializer.startTag(null, "disabled-components");
8023 for (final String name : pkg.disabledComponents) {
8024 serializer.startTag(null, "item");
8025 serializer.attribute(null, "name", name);
8026 serializer.endTag(null, "item");
8027 }
8028 serializer.endTag(null, "disabled-components");
8029 }
8030 if (pkg.enabledComponents.size() > 0) {
8031 serializer.startTag(null, "enabled-components");
8032 for (final String name : pkg.enabledComponents) {
8033 serializer.startTag(null, "item");
8034 serializer.attribute(null, "name", name);
8035 serializer.endTag(null, "item");
8036 }
8037 serializer.endTag(null, "enabled-components");
8038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 serializer.endTag(null, "package");
8041 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008043 void writePermission(XmlSerializer serializer, BasePermission bp)
8044 throws XmlPullParserException, java.io.IOException {
8045 if (bp.type != BasePermission.TYPE_BUILTIN
8046 && bp.sourcePackage != null) {
8047 serializer.startTag(null, "item");
8048 serializer.attribute(null, "name", bp.name);
8049 serializer.attribute(null, "package", bp.sourcePackage);
8050 if (DEBUG_SETTINGS) Log.v(TAG,
8051 "Writing perm: name=" + bp.name + " type=" + bp.type);
8052 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8053 PermissionInfo pi = bp.perm != null ? bp.perm.info
8054 : bp.pendingInfo;
8055 if (pi != null) {
8056 serializer.attribute(null, "type", "dynamic");
8057 if (pi.icon != 0) {
8058 serializer.attribute(null, "icon",
8059 Integer.toString(pi.icon));
8060 }
8061 if (pi.nonLocalizedLabel != null) {
8062 serializer.attribute(null, "label",
8063 pi.nonLocalizedLabel.toString());
8064 }
8065 if (pi.protectionLevel !=
8066 PermissionInfo.PROTECTION_NORMAL) {
8067 serializer.attribute(null, "protection",
8068 Integer.toString(pi.protectionLevel));
8069 }
8070 }
8071 }
8072 serializer.endTag(null, "item");
8073 }
8074 }
8075
8076 String getReadMessagesLP() {
8077 return mReadMessages.toString();
8078 }
8079
Oscar Montemayora8529f62009-11-18 10:14:20 -08008080 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008081 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8082 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008083 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 while(its.hasNext()) {
8085 String key = its.next();
8086 PackageSetting ps = mPackages.get(key);
8087 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008088 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 }
8090 }
8091 return ret;
8092 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008094 boolean readLP() {
8095 FileInputStream str = null;
8096 if (mBackupSettingsFilename.exists()) {
8097 try {
8098 str = new FileInputStream(mBackupSettingsFilename);
8099 mReadMessages.append("Reading from backup settings file\n");
8100 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008101 if (mSettingsFilename.exists()) {
8102 // If both the backup and settings file exist, we
8103 // ignore the settings since it might have been
8104 // corrupted.
8105 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
8106 mSettingsFilename.delete();
8107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 } catch (java.io.IOException e) {
8109 // We'll try for the normal settings file.
8110 }
8111 }
8112
8113 mPastSignatures.clear();
8114
8115 try {
8116 if (str == null) {
8117 if (!mSettingsFilename.exists()) {
8118 mReadMessages.append("No settings file found\n");
8119 Log.i(TAG, "No current settings file!");
8120 return false;
8121 }
8122 str = new FileInputStream(mSettingsFilename);
8123 }
8124 XmlPullParser parser = Xml.newPullParser();
8125 parser.setInput(str, null);
8126
8127 int type;
8128 while ((type=parser.next()) != XmlPullParser.START_TAG
8129 && type != XmlPullParser.END_DOCUMENT) {
8130 ;
8131 }
8132
8133 if (type != XmlPullParser.START_TAG) {
8134 mReadMessages.append("No start tag found in settings file\n");
8135 Log.e(TAG, "No start tag found in package manager settings");
8136 return false;
8137 }
8138
8139 int outerDepth = parser.getDepth();
8140 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8141 && (type != XmlPullParser.END_TAG
8142 || parser.getDepth() > outerDepth)) {
8143 if (type == XmlPullParser.END_TAG
8144 || type == XmlPullParser.TEXT) {
8145 continue;
8146 }
8147
8148 String tagName = parser.getName();
8149 if (tagName.equals("package")) {
8150 readPackageLP(parser);
8151 } else if (tagName.equals("permissions")) {
8152 readPermissionsLP(mPermissions, parser);
8153 } else if (tagName.equals("permission-trees")) {
8154 readPermissionsLP(mPermissionTrees, parser);
8155 } else if (tagName.equals("shared-user")) {
8156 readSharedUserLP(parser);
8157 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008158 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 } else if (tagName.equals("preferred-activities")) {
8160 readPreferredActivitiesLP(parser);
8161 } else if(tagName.equals("updated-package")) {
8162 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008163 } else if (tagName.equals("cleaning-package")) {
8164 String name = parser.getAttributeValue(null, "name");
8165 if (name != null) {
8166 mPackagesToBeCleaned.add(name);
8167 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008168 } else if (tagName.equals("renamed-package")) {
8169 String nname = parser.getAttributeValue(null, "new");
8170 String oname = parser.getAttributeValue(null, "old");
8171 if (nname != null && oname != null) {
8172 mRenamedPackages.put(nname, oname);
8173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008174 } else {
8175 Log.w(TAG, "Unknown element under <packages>: "
8176 + parser.getName());
8177 XmlUtils.skipCurrentTag(parser);
8178 }
8179 }
8180
8181 str.close();
8182
8183 } catch(XmlPullParserException e) {
8184 mReadMessages.append("Error reading: " + e.toString());
8185 Log.e(TAG, "Error reading package manager settings", e);
8186
8187 } catch(java.io.IOException e) {
8188 mReadMessages.append("Error reading: " + e.toString());
8189 Log.e(TAG, "Error reading package manager settings", e);
8190
8191 }
8192
8193 int N = mPendingPackages.size();
8194 for (int i=0; i<N; i++) {
8195 final PendingPackage pp = mPendingPackages.get(i);
8196 Object idObj = getUserIdLP(pp.sharedId);
8197 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008198 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008199 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008200 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008201 if (p == null) {
8202 Log.w(TAG, "Unable to create application package for "
8203 + pp.name);
8204 continue;
8205 }
8206 p.copyFrom(pp);
8207 } else if (idObj != null) {
8208 String msg = "Bad package setting: package " + pp.name
8209 + " has shared uid " + pp.sharedId
8210 + " that is not a shared uid\n";
8211 mReadMessages.append(msg);
8212 Log.e(TAG, msg);
8213 } else {
8214 String msg = "Bad package setting: package " + pp.name
8215 + " has shared uid " + pp.sharedId
8216 + " that is not defined\n";
8217 mReadMessages.append(msg);
8218 Log.e(TAG, msg);
8219 }
8220 }
8221 mPendingPackages.clear();
8222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008223 mReadMessages.append("Read completed successfully: "
8224 + mPackages.size() + " packages, "
8225 + mSharedUsers.size() + " shared uids\n");
8226
8227 return true;
8228 }
8229
8230 private int readInt(XmlPullParser parser, String ns, String name,
8231 int defValue) {
8232 String v = parser.getAttributeValue(ns, name);
8233 try {
8234 if (v == null) {
8235 return defValue;
8236 }
8237 return Integer.parseInt(v);
8238 } catch (NumberFormatException e) {
8239 reportSettingsProblem(Log.WARN,
8240 "Error in package manager settings: attribute " +
8241 name + " has bad integer value " + v + " at "
8242 + parser.getPositionDescription());
8243 }
8244 return defValue;
8245 }
8246
8247 private void readPermissionsLP(HashMap<String, BasePermission> out,
8248 XmlPullParser parser)
8249 throws IOException, XmlPullParserException {
8250 int outerDepth = parser.getDepth();
8251 int type;
8252 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8253 && (type != XmlPullParser.END_TAG
8254 || parser.getDepth() > outerDepth)) {
8255 if (type == XmlPullParser.END_TAG
8256 || type == XmlPullParser.TEXT) {
8257 continue;
8258 }
8259
8260 String tagName = parser.getName();
8261 if (tagName.equals("item")) {
8262 String name = parser.getAttributeValue(null, "name");
8263 String sourcePackage = parser.getAttributeValue(null, "package");
8264 String ptype = parser.getAttributeValue(null, "type");
8265 if (name != null && sourcePackage != null) {
8266 boolean dynamic = "dynamic".equals(ptype);
8267 BasePermission bp = new BasePermission(name, sourcePackage,
8268 dynamic
8269 ? BasePermission.TYPE_DYNAMIC
8270 : BasePermission.TYPE_NORMAL);
8271 if (dynamic) {
8272 PermissionInfo pi = new PermissionInfo();
8273 pi.packageName = sourcePackage.intern();
8274 pi.name = name.intern();
8275 pi.icon = readInt(parser, null, "icon", 0);
8276 pi.nonLocalizedLabel = parser.getAttributeValue(
8277 null, "label");
8278 pi.protectionLevel = readInt(parser, null, "protection",
8279 PermissionInfo.PROTECTION_NORMAL);
8280 bp.pendingInfo = pi;
8281 }
8282 out.put(bp.name, bp);
8283 } else {
8284 reportSettingsProblem(Log.WARN,
8285 "Error in package manager settings: permissions has"
8286 + " no name at " + parser.getPositionDescription());
8287 }
8288 } else {
8289 reportSettingsProblem(Log.WARN,
8290 "Unknown element reading permissions: "
8291 + parser.getName() + " at "
8292 + parser.getPositionDescription());
8293 }
8294 XmlUtils.skipCurrentTag(parser);
8295 }
8296 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008298 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008299 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008300 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008301 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 String codePathStr = parser.getAttributeValue(null, "codePath");
8303 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008304 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008305 resourcePathStr = codePathStr;
8306 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008307 String version = parser.getAttributeValue(null, "version");
8308 int versionCode = 0;
8309 if (version != null) {
8310 try {
8311 versionCode = Integer.parseInt(version);
8312 } catch (NumberFormatException e) {
8313 }
8314 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008316 int pkgFlags = 0;
8317 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008318 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008319 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008320 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008321 String timeStampStr = parser.getAttributeValue(null, "ts");
8322 if (timeStampStr != null) {
8323 try {
8324 long timeStamp = Long.parseLong(timeStampStr);
8325 ps.setTimeStamp(timeStamp, timeStampStr);
8326 } catch (NumberFormatException e) {
8327 }
8328 }
8329 String idStr = parser.getAttributeValue(null, "userId");
8330 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8331 if(ps.userId <= 0) {
8332 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8333 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8334 }
8335 int outerDepth = parser.getDepth();
8336 int type;
8337 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8338 && (type != XmlPullParser.END_TAG
8339 || parser.getDepth() > outerDepth)) {
8340 if (type == XmlPullParser.END_TAG
8341 || type == XmlPullParser.TEXT) {
8342 continue;
8343 }
8344
8345 String tagName = parser.getName();
8346 if (tagName.equals("perms")) {
8347 readGrantedPermissionsLP(parser,
8348 ps.grantedPermissions);
8349 } else {
8350 reportSettingsProblem(Log.WARN,
8351 "Unknown element under <updated-package>: "
8352 + parser.getName());
8353 XmlUtils.skipCurrentTag(parser);
8354 }
8355 }
8356 mDisabledSysPackages.put(name, ps);
8357 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008359 private void readPackageLP(XmlPullParser parser)
8360 throws XmlPullParserException, IOException {
8361 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008362 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008363 String idStr = null;
8364 String sharedIdStr = null;
8365 String codePathStr = null;
8366 String resourcePathStr = null;
8367 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008368 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008369 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008370 int pkgFlags = 0;
8371 String timeStampStr;
8372 long timeStamp = 0;
8373 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008374 String version = null;
8375 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008376 try {
8377 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008378 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008379 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008380 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008381 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8382 codePathStr = parser.getAttributeValue(null, "codePath");
8383 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008384 version = parser.getAttributeValue(null, "version");
8385 if (version != null) {
8386 try {
8387 versionCode = Integer.parseInt(version);
8388 } catch (NumberFormatException e) {
8389 }
8390 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008391 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008392
8393 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008394 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008395 try {
8396 pkgFlags = Integer.parseInt(systemStr);
8397 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008398 }
8399 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008400 // For backward compatibility
8401 systemStr = parser.getAttributeValue(null, "system");
8402 if (systemStr != null) {
8403 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8404 } else {
8405 // Old settings that don't specify system... just treat
8406 // them as system, good enough.
8407 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 }
8410 timeStampStr = parser.getAttributeValue(null, "ts");
8411 if (timeStampStr != null) {
8412 try {
8413 timeStamp = Long.parseLong(timeStampStr);
8414 } catch (NumberFormatException e) {
8415 }
8416 }
8417 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8418 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8419 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8420 if (resourcePathStr == null) {
8421 resourcePathStr = codePathStr;
8422 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008423 if (realName != null) {
8424 realName = realName.intern();
8425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008426 if (name == null) {
8427 reportSettingsProblem(Log.WARN,
8428 "Error in package manager settings: <package> has no name at "
8429 + parser.getPositionDescription());
8430 } else if (codePathStr == null) {
8431 reportSettingsProblem(Log.WARN,
8432 "Error in package manager settings: <package> has no codePath at "
8433 + parser.getPositionDescription());
8434 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008435 packageSetting = addPackageLP(name.intern(), realName,
8436 new File(codePathStr), new File(resourcePathStr),
8437 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008438 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8439 + ": userId=" + userId + " pkg=" + packageSetting);
8440 if (packageSetting == null) {
8441 reportSettingsProblem(Log.ERROR,
8442 "Failure adding uid " + userId
8443 + " while parsing settings at "
8444 + parser.getPositionDescription());
8445 } else {
8446 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8447 }
8448 } else if (sharedIdStr != null) {
8449 userId = sharedIdStr != null
8450 ? Integer.parseInt(sharedIdStr) : 0;
8451 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008452 packageSetting = new PendingPackage(name.intern(), realName,
8453 new File(codePathStr), new File(resourcePathStr),
8454 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8456 mPendingPackages.add((PendingPackage) packageSetting);
8457 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8458 + ": sharedUserId=" + userId + " pkg="
8459 + packageSetting);
8460 } else {
8461 reportSettingsProblem(Log.WARN,
8462 "Error in package manager settings: package "
8463 + name + " has bad sharedId " + sharedIdStr
8464 + " at " + parser.getPositionDescription());
8465 }
8466 } else {
8467 reportSettingsProblem(Log.WARN,
8468 "Error in package manager settings: package "
8469 + name + " has bad userId " + idStr + " at "
8470 + parser.getPositionDescription());
8471 }
8472 } catch (NumberFormatException e) {
8473 reportSettingsProblem(Log.WARN,
8474 "Error in package manager settings: package "
8475 + name + " has bad userId " + idStr + " at "
8476 + parser.getPositionDescription());
8477 }
8478 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008479 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008480 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 final String enabledStr = parser.getAttributeValue(null, "enabled");
8482 if (enabledStr != null) {
8483 if (enabledStr.equalsIgnoreCase("true")) {
8484 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8485 } else if (enabledStr.equalsIgnoreCase("false")) {
8486 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8487 } else if (enabledStr.equalsIgnoreCase("default")) {
8488 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8489 } else {
8490 reportSettingsProblem(Log.WARN,
8491 "Error in package manager settings: package "
8492 + name + " has bad enabled value: " + idStr
8493 + " at " + parser.getPositionDescription());
8494 }
8495 } else {
8496 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8497 }
8498 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8499 if (installStatusStr != null) {
8500 if (installStatusStr.equalsIgnoreCase("false")) {
8501 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8502 } else {
8503 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8504 }
8505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008507 int outerDepth = parser.getDepth();
8508 int type;
8509 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8510 && (type != XmlPullParser.END_TAG
8511 || parser.getDepth() > outerDepth)) {
8512 if (type == XmlPullParser.END_TAG
8513 || type == XmlPullParser.TEXT) {
8514 continue;
8515 }
8516
8517 String tagName = parser.getName();
8518 if (tagName.equals("disabled-components")) {
8519 readDisabledComponentsLP(packageSetting, parser);
8520 } else if (tagName.equals("enabled-components")) {
8521 readEnabledComponentsLP(packageSetting, parser);
8522 } else if (tagName.equals("sigs")) {
8523 packageSetting.signatures.readXml(parser, mPastSignatures);
8524 } else if (tagName.equals("perms")) {
8525 readGrantedPermissionsLP(parser,
8526 packageSetting.loadedPermissions);
8527 packageSetting.permissionsFixed = true;
8528 } else {
8529 reportSettingsProblem(Log.WARN,
8530 "Unknown element under <package>: "
8531 + parser.getName());
8532 XmlUtils.skipCurrentTag(parser);
8533 }
8534 }
8535 } else {
8536 XmlUtils.skipCurrentTag(parser);
8537 }
8538 }
8539
8540 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8541 XmlPullParser parser)
8542 throws IOException, XmlPullParserException {
8543 int outerDepth = parser.getDepth();
8544 int type;
8545 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8546 && (type != XmlPullParser.END_TAG
8547 || parser.getDepth() > outerDepth)) {
8548 if (type == XmlPullParser.END_TAG
8549 || type == XmlPullParser.TEXT) {
8550 continue;
8551 }
8552
8553 String tagName = parser.getName();
8554 if (tagName.equals("item")) {
8555 String name = parser.getAttributeValue(null, "name");
8556 if (name != null) {
8557 packageSetting.disabledComponents.add(name.intern());
8558 } else {
8559 reportSettingsProblem(Log.WARN,
8560 "Error in package manager settings: <disabled-components> has"
8561 + " no name at " + parser.getPositionDescription());
8562 }
8563 } else {
8564 reportSettingsProblem(Log.WARN,
8565 "Unknown element under <disabled-components>: "
8566 + parser.getName());
8567 }
8568 XmlUtils.skipCurrentTag(parser);
8569 }
8570 }
8571
8572 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8573 XmlPullParser parser)
8574 throws IOException, XmlPullParserException {
8575 int outerDepth = parser.getDepth();
8576 int type;
8577 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8578 && (type != XmlPullParser.END_TAG
8579 || parser.getDepth() > outerDepth)) {
8580 if (type == XmlPullParser.END_TAG
8581 || type == XmlPullParser.TEXT) {
8582 continue;
8583 }
8584
8585 String tagName = parser.getName();
8586 if (tagName.equals("item")) {
8587 String name = parser.getAttributeValue(null, "name");
8588 if (name != null) {
8589 packageSetting.enabledComponents.add(name.intern());
8590 } else {
8591 reportSettingsProblem(Log.WARN,
8592 "Error in package manager settings: <enabled-components> has"
8593 + " no name at " + parser.getPositionDescription());
8594 }
8595 } else {
8596 reportSettingsProblem(Log.WARN,
8597 "Unknown element under <enabled-components>: "
8598 + parser.getName());
8599 }
8600 XmlUtils.skipCurrentTag(parser);
8601 }
8602 }
8603
8604 private void readSharedUserLP(XmlPullParser parser)
8605 throws XmlPullParserException, IOException {
8606 String name = null;
8607 String idStr = null;
8608 int pkgFlags = 0;
8609 SharedUserSetting su = null;
8610 try {
8611 name = parser.getAttributeValue(null, "name");
8612 idStr = parser.getAttributeValue(null, "userId");
8613 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8614 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8615 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8616 }
8617 if (name == null) {
8618 reportSettingsProblem(Log.WARN,
8619 "Error in package manager settings: <shared-user> has no name at "
8620 + parser.getPositionDescription());
8621 } else if (userId == 0) {
8622 reportSettingsProblem(Log.WARN,
8623 "Error in package manager settings: shared-user "
8624 + name + " has bad userId " + idStr + " at "
8625 + parser.getPositionDescription());
8626 } else {
8627 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8628 reportSettingsProblem(Log.ERROR,
8629 "Occurred while parsing settings at "
8630 + parser.getPositionDescription());
8631 }
8632 }
8633 } catch (NumberFormatException e) {
8634 reportSettingsProblem(Log.WARN,
8635 "Error in package manager settings: package "
8636 + name + " has bad userId " + idStr + " at "
8637 + parser.getPositionDescription());
8638 };
8639
8640 if (su != null) {
8641 int outerDepth = parser.getDepth();
8642 int type;
8643 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8644 && (type != XmlPullParser.END_TAG
8645 || parser.getDepth() > outerDepth)) {
8646 if (type == XmlPullParser.END_TAG
8647 || type == XmlPullParser.TEXT) {
8648 continue;
8649 }
8650
8651 String tagName = parser.getName();
8652 if (tagName.equals("sigs")) {
8653 su.signatures.readXml(parser, mPastSignatures);
8654 } else if (tagName.equals("perms")) {
8655 readGrantedPermissionsLP(parser, su.loadedPermissions);
8656 } else {
8657 reportSettingsProblem(Log.WARN,
8658 "Unknown element under <shared-user>: "
8659 + parser.getName());
8660 XmlUtils.skipCurrentTag(parser);
8661 }
8662 }
8663
8664 } else {
8665 XmlUtils.skipCurrentTag(parser);
8666 }
8667 }
8668
8669 private void readGrantedPermissionsLP(XmlPullParser parser,
8670 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8671 int outerDepth = parser.getDepth();
8672 int type;
8673 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8674 && (type != XmlPullParser.END_TAG
8675 || parser.getDepth() > outerDepth)) {
8676 if (type == XmlPullParser.END_TAG
8677 || type == XmlPullParser.TEXT) {
8678 continue;
8679 }
8680
8681 String tagName = parser.getName();
8682 if (tagName.equals("item")) {
8683 String name = parser.getAttributeValue(null, "name");
8684 if (name != null) {
8685 outPerms.add(name.intern());
8686 } else {
8687 reportSettingsProblem(Log.WARN,
8688 "Error in package manager settings: <perms> has"
8689 + " no name at " + parser.getPositionDescription());
8690 }
8691 } else {
8692 reportSettingsProblem(Log.WARN,
8693 "Unknown element under <perms>: "
8694 + parser.getName());
8695 }
8696 XmlUtils.skipCurrentTag(parser);
8697 }
8698 }
8699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008700 private void readPreferredActivitiesLP(XmlPullParser parser)
8701 throws XmlPullParserException, IOException {
8702 int outerDepth = parser.getDepth();
8703 int type;
8704 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8705 && (type != XmlPullParser.END_TAG
8706 || parser.getDepth() > outerDepth)) {
8707 if (type == XmlPullParser.END_TAG
8708 || type == XmlPullParser.TEXT) {
8709 continue;
8710 }
8711
8712 String tagName = parser.getName();
8713 if (tagName.equals("item")) {
8714 PreferredActivity pa = new PreferredActivity(parser);
8715 if (pa.mParseError == null) {
8716 mPreferredActivities.addFilter(pa);
8717 } else {
8718 reportSettingsProblem(Log.WARN,
8719 "Error in package manager settings: <preferred-activity> "
8720 + pa.mParseError + " at "
8721 + parser.getPositionDescription());
8722 }
8723 } else {
8724 reportSettingsProblem(Log.WARN,
8725 "Unknown element under <preferred-activities>: "
8726 + parser.getName());
8727 XmlUtils.skipCurrentTag(parser);
8728 }
8729 }
8730 }
8731
8732 // Returns -1 if we could not find an available UserId to assign
8733 private int newUserIdLP(Object obj) {
8734 // Let's be stupidly inefficient for now...
8735 final int N = mUserIds.size();
8736 for (int i=0; i<N; i++) {
8737 if (mUserIds.get(i) == null) {
8738 mUserIds.set(i, obj);
8739 return FIRST_APPLICATION_UID + i;
8740 }
8741 }
8742
8743 // None left?
8744 if (N >= MAX_APPLICATION_UIDS) {
8745 return -1;
8746 }
8747
8748 mUserIds.add(obj);
8749 return FIRST_APPLICATION_UID + N;
8750 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 public PackageSetting getDisabledSystemPkg(String name) {
8753 synchronized(mPackages) {
8754 PackageSetting ps = mDisabledSysPackages.get(name);
8755 return ps;
8756 }
8757 }
8758
8759 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8760 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8761 if (Config.LOGV) {
8762 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8763 + " componentName = " + componentInfo.name);
8764 Log.v(TAG, "enabledComponents: "
8765 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8766 Log.v(TAG, "disabledComponents: "
8767 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8768 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008769 if (packageSettings == null) {
8770 if (false) {
8771 Log.w(TAG, "WAITING FOR DEBUGGER");
8772 Debug.waitForDebugger();
8773 Log.i(TAG, "We will crash!");
8774 }
8775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8777 || ((componentInfo.enabled
8778 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8779 || (componentInfo.applicationInfo.enabled
8780 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8781 && !packageSettings.disabledComponents.contains(componentInfo.name))
8782 || packageSettings.enabledComponents.contains(componentInfo.name));
8783 }
8784 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008785
8786 // ------- apps on sdcard specific code -------
8787 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008788 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008789 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008790 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008791 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008792
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008793 private String getEncryptKey() {
8794 try {
8795 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8796 if (sdEncKey == null) {
8797 sdEncKey = SystemKeyStore.getInstance().
8798 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8799 if (sdEncKey == null) {
8800 Log.e(TAG, "Failed to create encryption keys");
8801 return null;
8802 }
8803 }
8804 return sdEncKey;
8805 } catch (NoSuchAlgorithmException nsae) {
8806 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8807 return null;
8808 }
8809 }
8810
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008811 static String getTempContainerId() {
8812 String prefix = "smdl1tmp";
8813 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008814 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008815 if (list != null) {
8816 int idx = 0;
8817 int idList[] = new int[MAX_CONTAINERS];
8818 boolean neverFound = true;
8819 for (String name : list) {
8820 // Ignore null entries
8821 if (name == null) {
8822 continue;
8823 }
8824 int sidx = name.indexOf(prefix);
8825 if (sidx == -1) {
8826 // Not a temp file. just ignore
8827 continue;
8828 }
8829 String subStr = name.substring(sidx + prefix.length());
8830 idList[idx] = -1;
8831 if (subStr != null) {
8832 try {
8833 int cid = Integer.parseInt(subStr);
8834 idList[idx++] = cid;
8835 neverFound = false;
8836 } catch (NumberFormatException e) {
8837 }
8838 }
8839 }
8840 if (!neverFound) {
8841 // Sort idList
8842 Arrays.sort(idList);
8843 for (int j = 1; j <= idList.length; j++) {
8844 if (idList[j-1] != j) {
8845 tmpIdx = j;
8846 break;
8847 }
8848 }
8849 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008850 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008851 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008852 }
8853
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008854 public void updateExternalMediaStatus(final boolean mediaStatus) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008855 synchronized (mPackages) {
8856 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8857 mediaStatus+", mMediaMounted=" + mMediaMounted);
8858 if (mediaStatus == mMediaMounted) {
8859 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008860 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008861 mMediaMounted = mediaStatus;
8862 // Queue up an async operation since the package installation may take a little while.
8863 mHandler.post(new Runnable() {
8864 public void run() {
8865 mHandler.removeCallbacks(this);
8866 updateExternalMediaStatusInner(mediaStatus);
8867 }
8868 });
8869 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008870 }
8871
8872 void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008873 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008874 if (list == null || list.length == 0) {
8875 return;
8876 }
8877 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8878 int uidList[] = new int[list.length];
8879 int num = 0;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008880 synchronized (mPackages) {
8881 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8882 for (String cid : list) {
8883 SdInstallArgs args = new SdInstallArgs(cid);
8884 String removeEntry = null;
8885 for (String app : appList) {
8886 if (args.matchContainer(app)) {
8887 removeEntry = app;
8888 break;
8889 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008890 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008891 if (removeEntry == null) {
8892 // No matching app on device. Skip entry or may be cleanup?
8893 // Ignore default package
8894 continue;
8895 }
8896 appList.remove(removeEntry);
8897 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8898 processCids.put(args, ps.codePathString);
8899 int uid = ps.userId;
8900 if (uid != -1) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008901 uidList[num++] = uid;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008902 }
8903 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008904 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008905 int uidArr[] = null;
8906 if (num > 0) {
8907 // Sort uid list
8908 Arrays.sort(uidList, 0, num);
8909 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008910 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008911 uidArr[0] = uidList[0];
8912 int di = 0;
8913 for (int i = 1; i < num; i++) {
8914 if (uidList[i-1] != uidList[i]) {
8915 uidArr[di++] = uidList[i];
8916 }
8917 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008918 }
8919 if (mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008920 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008921 loadMediaPackages(processCids, uidArr);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008922 startCleaningPackages();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008923 } else {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008924 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008925 unloadMediaPackages(processCids, uidArr);
8926 }
8927 }
8928
8929 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8930 ArrayList<String> pkgList, int uidArr[]) {
8931 int size = pkgList.size();
8932 if (size > 0) {
8933 // Send broadcasts here
8934 Bundle extras = new Bundle();
8935 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8936 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008937 if (uidArr != null) {
8938 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8939 }
8940 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8941 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008942 sendPackageBroadcast(action, null, extras);
8943 }
8944 }
8945
8946 void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8947 ArrayList<String> pkgList = new ArrayList<String>();
8948 Set<SdInstallArgs> keys = processCids.keySet();
8949 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008950 String codePath = processCids.get(args);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008951 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install pkg : "
8952 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008953 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008954 Log.e(TAG, "Failed to install package: " + codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008955 continue;
8956 }
8957 // Parse package
8958 int parseFlags = PackageParser.PARSE_CHATTY |
8959 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8960 PackageParser pp = new PackageParser(codePath);
8961 pp.setSeparateProcesses(mSeparateProcesses);
8962 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
8963 codePath, mMetrics, parseFlags);
8964 if (pkg == null) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008965 Log.e(TAG, "Trying to install pkg : "
8966 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008967 continue;
8968 }
8969 setApplicationInfoPaths(pkg, codePath, codePath);
8970 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8971 synchronized (mInstallLock) {
8972 // Scan the package
8973 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
8974 synchronized (mPackages) {
8975 // Grant permissions
8976 grantPermissionsLP(pkg, false);
8977 // Persist settings
8978 mSettings.writeLP();
8979 retCode = PackageManager.INSTALL_SUCCEEDED;
8980 pkgList.add(pkg.packageName);
8981 }
8982 } else {
8983 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
8984 }
8985 }
8986 args.doPostInstall(retCode);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008987 }
8988 // Send broadcasts first
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008989 if (pkgList.size() > 0) {
8990 sendResourcesChangedBroadcast(true, pkgList, uidArr);
8991 Runtime.getRuntime().gc();
8992 // If something failed do we clean up here or next install?
8993 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008994 }
8995
8996 void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008997 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008998 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008999 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009000 Set<SdInstallArgs> keys = processCids.keySet();
9001 for (SdInstallArgs args : keys) {
9002 String cid = args.cid;
9003 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009004 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009005 // Delete package internally
9006 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9007 synchronized (mInstallLock) {
9008 boolean res = deletePackageLI(pkgName, false,
9009 PackageManager.DONT_DELETE_DATA, outInfo);
9010 if (res) {
9011 pkgList.add(pkgName);
9012 } else {
9013 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009014 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009015 }
9016 }
9017 }
9018 // Send broadcasts
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009019 if (pkgList.size() > 0) {
9020 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9021 Runtime.getRuntime().gc();
9022 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009023 // Do clean up. Just unmount
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009024 for (SdInstallArgs args : failedList) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009025 synchronized (mInstallLock) {
9026 args.doPostDeleteLI(false);
9027 }
9028 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009029 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009030
9031 public void movePackage(final String packageName,
9032 final IPackageMoveObserver observer, final int flags) {
9033 if (packageName == null) {
9034 return;
9035 }
9036 mContext.enforceCallingOrSelfPermission(
9037 android.Manifest.permission.MOVE_PACKAGE, null);
9038 int returnCode = PackageManager.MOVE_SUCCEEDED;
9039 int currFlags = 0;
9040 int newFlags = 0;
9041 synchronized (mPackages) {
9042 PackageParser.Package pkg = mPackages.get(packageName);
9043 if (pkg == null) {
9044 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9045 }
9046 // Disable moving fwd locked apps and system packages
9047 if (pkg.applicationInfo != null &&
9048 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9049 Log.w(TAG, "Cannot move system application");
9050 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9051 } else if (pkg.applicationInfo != null &&
9052 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9053 Log.w(TAG, "Cannot move forward locked app.");
9054 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9055 } else {
9056 // Find install location first
9057 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9058 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9059 Log.w(TAG, "Ambigous flags specified for move location.");
9060 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9061 } else {
9062 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9063 PackageManager.INSTALL_EXTERNAL : 0;
9064 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0 ?
9065 PackageManager.INSTALL_EXTERNAL : 0;
9066 if (newFlags == currFlags) {
9067 Log.w(TAG, "No move required. Trying to move to same location");
9068 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9069 }
9070 }
9071 }
9072 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9073 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9074 } else {
9075 Message msg = mHandler.obtainMessage(INIT_COPY);
9076 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9077 pkg.applicationInfo.publicSourceDir);
9078 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9079 packageName);
9080 msg.obj = mp;
9081 mHandler.sendMessage(msg);
9082 }
9083 }
9084 }
9085
9086 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9087 // Queue up an async operation since the package deletion may take a little while.
9088 mHandler.post(new Runnable() {
9089 public void run() {
9090 mHandler.removeCallbacks(this);
9091 int returnCode = currentStatus;
9092 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9093 if (moveSucceeded) {
9094 int uid = -1;
9095 synchronized (mPackages) {
9096 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9097 }
9098 ArrayList<String> pkgList = new ArrayList<String>();
9099 pkgList.add(mp.packageName);
9100 int uidArr[] = new int[] { uid };
9101 // Send resources unavailable broadcast
9102 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9103
9104 // Update package code and resource paths
9105 synchronized (mPackages) {
9106 PackageParser.Package pkg = mPackages.get(mp.packageName);
9107 if (pkg != null) {
9108 String oldCodePath = pkg.mPath;
9109 String newCodePath = mp.targetArgs.getCodePath();
9110 String newResPath = mp.targetArgs.getResourcePath();
9111 pkg.mPath = newCodePath;
9112 // Move dex files around
9113 if (moveDexFiles(pkg)
9114 != PackageManager.INSTALL_SUCCEEDED) {
9115 // Moving of dex files failed. Set
9116 // error code and abort move.
9117 pkg.mPath = pkg.mScanPath;
9118 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9119 moveSucceeded = false;
9120 } else {
9121 pkg.mScanPath = newCodePath;
9122 pkg.applicationInfo.sourceDir = newCodePath;
9123 pkg.applicationInfo.publicSourceDir = newResPath;
9124 PackageSetting ps = (PackageSetting) pkg.mExtras;
9125 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9126 ps.codePathString = ps.codePath.getPath();
9127 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9128 ps.resourcePathString = ps.resourcePath.getPath();
9129 // Set the application info flag correctly.
9130 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9131 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_ON_SDCARD;
9132 } else {
9133 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_ON_SDCARD;
9134 }
9135 ps.setFlags(pkg.applicationInfo.flags);
9136 mAppDirs.remove(oldCodePath);
9137 mAppDirs.put(newCodePath, pkg);
9138 // Persist settings
9139 mSettings.writeLP();
9140 }
9141 }
9142 }
9143 if (moveSucceeded) {
9144 // Delete older code
9145 synchronized (mInstallLock) {
9146 mp.srcArgs.cleanUpResourcesLI();
9147 }
9148 // Send resources available broadcast
9149 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9150 Runtime.getRuntime().gc();
9151 }
9152 }
9153 if (!moveSucceeded){
9154 // Clean up failed installation
9155 if (mp.targetArgs != null) {
9156 mp.targetArgs.doPostInstall(
9157 PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
9158 }
9159 }
9160 IPackageMoveObserver observer = mp.observer;
9161 if (observer != null) {
9162 try {
9163 observer.packageMoved(mp.packageName, returnCode);
9164 } catch (RemoteException e) {
9165 Log.i(TAG, "Observer no longer exists.");
9166 }
9167 }
9168 }
9169 });
9170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009171}