blob: 63fdaef3d4a78e63cd6082c65746559e3caca048 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
23import com.android.internal.util.XmlUtils;
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 Amalapurapudaec17222010-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 Amalapurapudaec17222010-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 Amalapurapudaec17222010-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 Hackbornc14b9ccd2009-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 Hackbornc14b9ccd2009-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 Hackbornc14b9ccd2009-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 Hackbornc14b9ccd2009-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 Hackbornc14b9ccd2009-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 Amalapurapucf6eaea2010-02-23 19:37:45 -08004861 boolean enableRename = false;
4862 if (enableRename) {
4863 if (PackageHelper.isContainerMounted(cid)) {
4864 // Unmount the container
4865 if (!PackageHelper.unMountSdDir(cid)) {
4866 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
4867 return false;
4868 }
4869 }
4870 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
4871 Log.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004872 return false;
4873 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08004874 if (!PackageHelper.isContainerMounted(newCacheId)) {
4875 Log.w(TAG, "Mounting container " + newCacheId);
4876 newCachePath = PackageHelper.mountSdDir(newCacheId,
4877 getEncryptKey(), Process.SYSTEM_UID);
4878 } else {
4879 newCachePath = PackageHelper.getSdDir(newCacheId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004880 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08004881 if (newCachePath == null) {
4882 Log.w(TAG, "Failed to get cache path for " + newCacheId);
4883 return false;
4884 }
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004885 // Mount old container?
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08004886 Log.i(TAG, "Succesfully renamed " + cid +
4887 " at path: " + cachePath + " to " + newCacheId +
4888 " at new path: " + newCachePath);
4889 cid = newCacheId;
4890 cachePath = newCachePath;
4891 return true;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004892 } else {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08004893 // STOPSHIP work around for rename
4894 Log.i(TAG, "Copying instead of renaming");
4895 File srcFile = new File(getCodePath());
4896 // Create new container
4897 newCachePath = PackageHelper.createSdDir(srcFile, newCacheId,
4898 getEncryptKey(), Process.SYSTEM_UID);
4899 Log.i(TAG, "Created rename container " + newCacheId);
4900 File destFile = new File(newCachePath + "/" + RES_FILE_NAME);
4901 if (!FileUtils.copyFile(srcFile, destFile)) {
4902 Log.e(TAG, "Failed to copy " + srcFile + " to " + destFile);
4903 return false;
4904 }
4905 Log.i(TAG, "Successfully copied resource to " + newCachePath);
4906 if (!PackageHelper.finalizeSdDir(newCacheId)) {
4907 Log.e(TAG, "Failed to finalize " + newCacheId);
4908 PackageHelper.destroySdDir(newCacheId);
4909 return false;
4910 }
4911 Log.i(TAG, "Finalized " + newCacheId);
4912 Runtime.getRuntime().gc();
4913 // Unmount first
4914 PackageHelper.unMountSdDir(cid);
4915 // Delete old container
4916 PackageHelper.destroySdDir(cid);
4917 // Dont have to mount. Already mounted.
4918 cid = newCacheId;
4919 cachePath = newCachePath;
4920 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004921 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004922 }
4923
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004924 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004925 if (status != PackageManager.INSTALL_SUCCEEDED) {
4926 cleanUp();
4927 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004928 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004929 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004930 PackageHelper.mountSdDir(cid,
4931 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004932 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004933 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004934 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004935 }
4936
4937 private void cleanUp() {
4938 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004939 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004940 }
4941
4942 void cleanUpResourcesLI() {
4943 String sourceFile = getCodePath();
4944 // Remove dex file
4945 if (mInstaller != null) {
4946 int retCode = mInstaller.rmdex(sourceFile.toString());
4947 if (retCode < 0) {
4948 Log.w(TAG, "Couldn't remove dex file for package: "
4949 + " at location "
4950 + sourceFile.toString() + ", retcode=" + retCode);
4951 // we don't consider this to be a failure of the core package deletion
4952 }
4953 }
4954 cleanUp();
4955 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004956
4957 boolean matchContainer(String app) {
4958 if (cid.startsWith(app)) {
4959 return true;
4960 }
4961 return false;
4962 }
4963
4964 String getPackageName() {
4965 int idx = cid.lastIndexOf("-");
4966 if (idx == -1) {
4967 return cid;
4968 }
4969 return cid.substring(0, idx);
4970 }
4971
4972 boolean doPostDeleteLI(boolean delete) {
4973 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004974 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004975 if (mounted) {
4976 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004977 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004978 }
4979 if (ret && delete) {
4980 cleanUpResourcesLI();
4981 }
4982 return ret;
4983 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004984 };
4985
4986 // Utility method used to create code paths based on package name and available index.
4987 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4988 String idxStr = "";
4989 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004990 // Fall back to default value of idx=1 if prefix is not
4991 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004992 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004993 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004994 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004995 if (subStr.endsWith(suffix)) {
4996 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004997 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004998 // If oldCodePath already contains prefix find out the
4999 // ending index to either increment or decrement.
5000 int sidx = subStr.lastIndexOf(prefix);
5001 if (sidx != -1) {
5002 subStr = subStr.substring(sidx + prefix.length());
5003 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005004 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5005 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005006 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005007 try {
5008 idx = Integer.parseInt(subStr);
5009 if (idx <= 1) {
5010 idx++;
5011 } else {
5012 idx--;
5013 }
5014 } catch(NumberFormatException e) {
5015 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005016 }
5017 }
5018 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005019 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005020 return prefix + idxStr;
5021 }
5022
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005023 // Utility method used to ignore ADD/REMOVE events
5024 // by directory observer.
5025 private static boolean ignoreCodePath(String fullPathStr) {
5026 String apkName = getApkName(fullPathStr);
5027 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5028 if (idx != -1 && ((idx+1) < apkName.length())) {
5029 // Make sure the package ends with a numeral
5030 String version = apkName.substring(idx+1);
5031 try {
5032 Integer.parseInt(version);
5033 return true;
5034 } catch (NumberFormatException e) {}
5035 }
5036 return false;
5037 }
5038
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005039 // Utility method that returns the relative package path with respect
5040 // to the installation directory. Like say for /data/data/com.test-1.apk
5041 // string com.test-1 is returned.
5042 static String getApkName(String codePath) {
5043 if (codePath == null) {
5044 return null;
5045 }
5046 int sidx = codePath.lastIndexOf("/");
5047 int eidx = codePath.lastIndexOf(".");
5048 if (eidx == -1) {
5049 eidx = codePath.length();
5050 } else if (eidx == 0) {
5051 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
5052 return null;
5053 }
5054 return codePath.substring(sidx+1, eidx);
5055 }
5056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 class PackageInstalledInfo {
5058 String name;
5059 int uid;
5060 PackageParser.Package pkg;
5061 int returnCode;
5062 PackageRemovedInfo removedInfo;
5063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 /*
5066 * Install a non-existing package.
5067 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005068 private void installNewPackageLI(PackageParser.Package pkg,
5069 int parseFlags,
5070 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005071 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08005073 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005074 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005075
5076 if (useEncryptedFilesystemForPackage(pkg)) {
5077 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
5078 } else {
5079 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
5080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005081 res.name = pkgName;
5082 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005083 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005085 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 + " without first uninstalling.");
5087 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5088 return;
5089 }
5090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005092 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005094 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005095 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5096 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5097 }
5098 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005099 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005100 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005101 res);
5102 // delete the partially installed application. the data directory will have to be
5103 // restored if it was already existing
5104 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5105 // remove package from internal structures. Note that we want deletePackageX to
5106 // delete the package data and cache directories that it created in
5107 // scanPackageLocked, unless those directories existed before we even tried to
5108 // install.
5109 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005110 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5112 res.removedInfo);
5113 }
5114 }
5115 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005116
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005117 private void replacePackageLI(PackageParser.Package pkg,
5118 int parseFlags,
5119 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005120 String installerPackageName, PackageInstalledInfo res) {
5121
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005122 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005123 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 // First find the old package info and check signatures
5125 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005126 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005127 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005128 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5130 return;
5131 }
5132 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005133 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005134 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005135 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005137 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005138 }
5139 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005141 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005142 PackageParser.Package pkg,
5143 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005144 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 PackageParser.Package newPackage = null;
5146 String pkgName = deletedPackage.packageName;
5147 boolean deletedPkg = true;
5148 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005149
Jacek Surazski65e13172009-04-28 15:26:38 +02005150 String oldInstallerPackageName = null;
5151 synchronized (mPackages) {
5152 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5153 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005154
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005155 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005157 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005158 res.removedInfo)) {
5159 // If the existing package was'nt successfully deleted
5160 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5161 deletedPkg = false;
5162 } else {
5163 // Successfully deleted the old package. Now proceed with re-installation
5164 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005165 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005166 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005167 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005168 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5169 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005170 }
5171 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005172 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005173 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005174 res);
5175 updatedSettings = true;
5176 }
5177 }
5178
5179 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5180 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005181 // were keeping around in case we needed them (see below) can now be deleted.
5182 // This info will be set on the res.removedInfo to clean up later on as post
5183 // install action.
5184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005185 //update signature on the new package setting
5186 //this should always succeed, since we checked the
5187 //signature earlier.
5188 synchronized(mPackages) {
5189 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5190 parseFlags, true);
5191 }
5192 } else {
5193 // remove package from internal structures. Note that we want deletePackageX to
5194 // delete the package data and cache directories that it created in
5195 // scanPackageLocked, unless those directories existed before we even tried to
5196 // install.
5197 if(updatedSettings) {
5198 deletePackageLI(
5199 pkgName, true,
5200 PackageManager.DONT_DELETE_DATA,
5201 res.removedInfo);
5202 }
5203 // Since we failed to install the new package we need to restore the old
5204 // package that we deleted.
5205 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005206 File restoreFile = new File(deletedPackage.mPath);
5207 if (restoreFile == null) {
5208 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
5209 return;
5210 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005211 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5212 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005213 // Parse old package
5214 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5215 scanPackageLI(restoreFile, parseFlags, scanMode);
5216 synchronized (mPackages) {
5217 grantPermissionsLP(deletedPackage, false);
5218 mSettings.writeLP();
5219 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005220 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5221 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
5222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 }
5224 }
5225 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005228 PackageParser.Package pkg,
5229 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005230 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005231 PackageParser.Package newPackage = null;
5232 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005233 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 PackageParser.PARSE_IS_SYSTEM;
5235 String packageName = deletedPackage.packageName;
5236 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5237 if (packageName == null) {
5238 Log.w(TAG, "Attempt to delete null packageName.");
5239 return;
5240 }
5241 PackageParser.Package oldPkg;
5242 PackageSetting oldPkgSetting;
5243 synchronized (mPackages) {
5244 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005245 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5247 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005248 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005249 return;
5250 }
5251 }
5252 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5253 res.removedInfo.removedPackage = packageName;
5254 // Remove existing system package
5255 removePackageLI(oldPkg, true);
5256 synchronized (mPackages) {
5257 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5258 }
5259
5260 // Successfully disabled the old package. Now proceed with re-installation
5261 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5262 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005263 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005264 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005265 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005266 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5267 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5268 }
5269 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005270 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005271 updatedSettings = true;
5272 }
5273
5274 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5275 //update signature on the new package setting
5276 //this should always succeed, since we checked the
5277 //signature earlier.
5278 synchronized(mPackages) {
5279 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5280 parseFlags, true);
5281 }
5282 } else {
5283 // Re installation failed. Restore old information
5284 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005285 if (newPackage != null) {
5286 removePackageLI(newPackage, true);
5287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005289 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005290 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005291 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005292 // Restore the old system information in Settings
5293 synchronized(mPackages) {
5294 if(updatedSettings) {
5295 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005296 mSettings.setInstallerPackageName(packageName,
5297 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005298 }
5299 mSettings.writeLP();
5300 }
5301 }
5302 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005303
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005304 // Utility method used to move dex files during install.
5305 private int moveDexFiles(PackageParser.Package newPackage) {
5306 int retCode;
5307 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5308 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5309 if (retCode != 0) {
5310 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5311 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5312 }
5313 }
5314 return PackageManager.INSTALL_SUCCEEDED;
5315 }
5316
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005317 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005318 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005319 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320 synchronized (mPackages) {
5321 //write settings. the installStatus will be incomplete at this stage.
5322 //note that the new package setting would have already been
5323 //added to mPackages. It hasn't been persisted yet.
5324 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5325 mSettings.writeLP();
5326 }
5327
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005328 if ((res.returnCode = moveDexFiles(newPackage))
5329 != PackageManager.INSTALL_SUCCEEDED) {
5330 // Discontinue if moving dex files failed.
5331 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005333 if((res.returnCode = setPermissionsLI(newPackage))
5334 != PackageManager.INSTALL_SUCCEEDED) {
5335 if (mInstaller != null) {
5336 mInstaller.rmdex(newPackage.mScanPath);
5337 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005338 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005339 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005340 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005342 synchronized (mPackages) {
5343 grantPermissionsLP(newPackage, true);
5344 res.name = pkgName;
5345 res.uid = newPackage.applicationInfo.uid;
5346 res.pkg = newPackage;
5347 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005348 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5350 //to update install status
5351 mSettings.writeLP();
5352 }
5353 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005354
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005355 private void installPackageLI(InstallArgs args,
5356 boolean newInstall, PackageInstalledInfo res) {
5357 int pFlags = args.flags;
5358 String installerPackageName = args.installerPackageName;
5359 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005360 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005361 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005362 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005363 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5364 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005365 // Result object to be returned
5366 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5367
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005368 // Retrieve PackageSettings and parse package
5369 int parseFlags = PackageParser.PARSE_CHATTY |
5370 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5371 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5372 parseFlags |= mDefParseFlags;
5373 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5374 pp.setSeparateProcesses(mSeparateProcesses);
5375 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5376 null, mMetrics, parseFlags);
5377 if (pkg == null) {
5378 res.returnCode = pp.getParseError();
5379 return;
5380 }
5381 String pkgName = res.name = pkg.packageName;
5382 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5383 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5384 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5385 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005387 }
5388 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5389 res.returnCode = pp.getParseError();
5390 return;
5391 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005392 // Get rid of all references to package scan path via parser.
5393 pp = null;
5394 String oldCodePath = null;
5395 boolean systemApp = false;
5396 synchronized (mPackages) {
5397 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005398 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5399 String oldName = mSettings.mRenamedPackages.get(pkgName);
5400 if (oldName != null && oldName.equals(pkg.mOriginalPackage)
5401 && mPackages.containsKey(oldName)) {
5402 // This package is derived from an original package,
5403 // and this device has been updating from that original
5404 // name. We must continue using the original name, so
5405 // rename the new package here.
5406 pkg.setPackageName(pkg.mOriginalPackage);
5407 pkgName = pkg.packageName;
5408 replace = true;
5409 } else if (mPackages.containsKey(pkgName)) {
5410 // This package, under its official name, already exists
5411 // on the device; we should replace it.
5412 replace = true;
5413 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005414 }
5415 PackageSetting ps = mSettings.mPackages.get(pkgName);
5416 if (ps != null) {
5417 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5418 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5419 systemApp = (ps.pkg.applicationInfo.flags &
5420 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005421 }
5422 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005423 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005424
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005425 if (systemApp && onSd) {
5426 // Disable updates to system apps on sdcard
5427 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5428 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5429 return;
5430 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005431
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005432 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5433 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5434 return;
5435 }
5436 // Set application objects path explicitly after the rename
5437 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005438 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005439 replacePackageLI(pkg, parseFlags, scanMode,
5440 installerPackageName, res);
5441 } else {
5442 installNewPackageLI(pkg, parseFlags, scanMode,
5443 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444 }
5445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005446
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005447 private int setPermissionsLI(PackageParser.Package newPackage) {
5448 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005449 int retCode = 0;
5450 // TODO Gross hack but fix later. Ideally move this to be a post installation
5451 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005452 if ((newPackage.applicationInfo.flags
5453 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5454 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 try {
5456 extractPublicFiles(newPackage, destResourceFile);
5457 } catch (IOException e) {
5458 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5459 " forward-locked app.");
5460 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5461 } finally {
5462 //TODO clean up the extracted public files
5463 }
5464 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005465 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 newPackage.applicationInfo.uid);
5467 } else {
5468 final int filePermissions =
5469 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005470 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005471 newPackage.applicationInfo.uid);
5472 }
5473 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005474 // The permissions on the resource file was set when it was copied for
5475 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005479 Log.e(TAG, "Couldn't set new package file permissions for " +
5480 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005481 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005482 // TODO Define new internal error
5483 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 }
5485 return PackageManager.INSTALL_SUCCEEDED;
5486 }
5487
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005488 private boolean isForwardLocked(PackageParser.Package pkg) {
5489 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490 }
5491
5492 private void extractPublicFiles(PackageParser.Package newPackage,
5493 File publicZipFile) throws IOException {
5494 final ZipOutputStream publicZipOutStream =
5495 new ZipOutputStream(new FileOutputStream(publicZipFile));
5496 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5497
5498 // Copy manifest, resources.arsc and res directory to public zip
5499
5500 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5501 while (privateZipEntries.hasMoreElements()) {
5502 final ZipEntry zipEntry = privateZipEntries.nextElement();
5503 final String zipEntryName = zipEntry.getName();
5504 if ("AndroidManifest.xml".equals(zipEntryName)
5505 || "resources.arsc".equals(zipEntryName)
5506 || zipEntryName.startsWith("res/")) {
5507 try {
5508 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5509 } catch (IOException e) {
5510 try {
5511 publicZipOutStream.close();
5512 throw e;
5513 } finally {
5514 publicZipFile.delete();
5515 }
5516 }
5517 }
5518 }
5519
5520 publicZipOutStream.close();
5521 FileUtils.setPermissions(
5522 publicZipFile.getAbsolutePath(),
5523 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5524 -1, -1);
5525 }
5526
5527 private static void copyZipEntry(ZipEntry zipEntry,
5528 ZipFile inZipFile,
5529 ZipOutputStream outZipStream) throws IOException {
5530 byte[] buffer = new byte[4096];
5531 int num;
5532
5533 ZipEntry newEntry;
5534 if (zipEntry.getMethod() == ZipEntry.STORED) {
5535 // Preserve the STORED method of the input entry.
5536 newEntry = new ZipEntry(zipEntry);
5537 } else {
5538 // Create a new entry so that the compressed len is recomputed.
5539 newEntry = new ZipEntry(zipEntry.getName());
5540 }
5541 outZipStream.putNextEntry(newEntry);
5542
5543 InputStream data = inZipFile.getInputStream(zipEntry);
5544 while ((num = data.read(buffer)) > 0) {
5545 outZipStream.write(buffer, 0, num);
5546 }
5547 outZipStream.flush();
5548 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 private void deleteTempPackageFiles() {
5551 FilenameFilter filter = new FilenameFilter() {
5552 public boolean accept(File dir, String name) {
5553 return name.startsWith("vmdl") && name.endsWith(".tmp");
5554 }
5555 };
5556 String tmpFilesList[] = mAppInstallDir.list(filter);
5557 if(tmpFilesList == null) {
5558 return;
5559 }
5560 for(int i = 0; i < tmpFilesList.length; i++) {
5561 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5562 tmpFile.delete();
5563 }
5564 }
5565
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005566 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 File tmpPackageFile;
5568 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005569 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 } catch (IOException e) {
5571 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5572 return null;
5573 }
5574 try {
5575 FileUtils.setPermissions(
5576 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5577 -1, -1);
5578 } catch (IOException e) {
5579 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5580 return null;
5581 }
5582 return tmpPackageFile;
5583 }
5584
5585 public void deletePackage(final String packageName,
5586 final IPackageDeleteObserver observer,
5587 final int flags) {
5588 mContext.enforceCallingOrSelfPermission(
5589 android.Manifest.permission.DELETE_PACKAGES, null);
5590 // Queue up an async operation since the package deletion may take a little while.
5591 mHandler.post(new Runnable() {
5592 public void run() {
5593 mHandler.removeCallbacks(this);
5594 final boolean succeded = deletePackageX(packageName, true, true, flags);
5595 if (observer != null) {
5596 try {
5597 observer.packageDeleted(succeded);
5598 } catch (RemoteException e) {
5599 Log.i(TAG, "Observer no longer exists.");
5600 } //end catch
5601 } //end if
5602 } //end run
5603 });
5604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 /**
5607 * This method is an internal method that could be get invoked either
5608 * to delete an installed package or to clean up a failed installation.
5609 * After deleting an installed package, a broadcast is sent to notify any
5610 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005611 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 * installation wouldn't have sent the initial broadcast either
5613 * The key steps in deleting a package are
5614 * deleting the package information in internal structures like mPackages,
5615 * deleting the packages base directories through installd
5616 * updating mSettings to reflect current status
5617 * persisting settings for later use
5618 * sending a broadcast if necessary
5619 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005620 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5621 boolean deleteCodeAndResources, int flags) {
5622 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005623 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005625 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5626 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5627 try {
5628 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
5629 Log.w(TAG, "Not removing package " + packageName + ": has active device admin");
5630 return false;
5631 }
5632 } catch (RemoteException e) {
5633 }
5634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 synchronized (mInstallLock) {
5636 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005640 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5641 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5642
5643 // If the removed package was a system update, the old system packaged
5644 // was re-enabled; we need to broadcast this information
5645 if (systemUpdate) {
5646 Bundle extras = new Bundle(1);
5647 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5648 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5649
5650 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5651 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005654 // Delete the resources here after sending the broadcast to let
5655 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005656 if (info.args != null) {
5657 synchronized (mInstallLock) {
5658 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005659 }
5660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 return res;
5662 }
5663
5664 static class PackageRemovedInfo {
5665 String removedPackage;
5666 int uid = -1;
5667 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005668 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005669 // Clean up resources deleted packages.
5670 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 void sendBroadcast(boolean fullRemove, boolean replacing) {
5673 Bundle extras = new Bundle(1);
5674 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5675 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5676 if (replacing) {
5677 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5678 }
5679 if (removedPackage != null) {
5680 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5681 }
5682 if (removedUid >= 0) {
5683 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5684 }
5685 }
5686 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 /*
5689 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5690 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005691 * 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 -08005692 * delete a partially installed application.
5693 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005694 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 int flags) {
5696 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005697 if (outInfo != null) {
5698 outInfo.removedPackage = packageName;
5699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700 removePackageLI(p, true);
5701 // Retrieve object to delete permissions for shared user later on
5702 PackageSetting deletedPs;
5703 synchronized (mPackages) {
5704 deletedPs = mSettings.mPackages.get(packageName);
5705 }
5706 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005707 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005709 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 if (retCode < 0) {
5711 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5712 + packageName + ", retcode=" + retCode);
5713 // we don't consider this to be a failure of the core package deletion
5714 }
5715 } else {
5716 //for emulator
5717 PackageParser.Package pkg = mPackages.get(packageName);
5718 File dataDir = new File(pkg.applicationInfo.dataDir);
5719 dataDir.delete();
5720 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005721 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005723 if (outInfo != null) {
5724 outInfo.removedUid = mSettings.removePackageLP(packageName);
5725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 }
5727 }
5728 synchronized (mPackages) {
5729 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5730 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005731 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005733 if (deletedPs != null) {
5734 // remove from preferred activities.
5735 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
5736 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
5737 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
5738 removed.add(pa);
5739 }
5740 }
5741 for (PreferredActivity pa : removed) {
5742 mSettings.mPreferredActivities.removeFilter(pa);
5743 }
5744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005746 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005747 }
5748 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005750 /*
5751 * Tries to delete system package.
5752 */
5753 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005754 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 ApplicationInfo applicationInfo = p.applicationInfo;
5756 //applicable for non-partially installed applications only
5757 if (applicationInfo == null) {
5758 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5759 return false;
5760 }
5761 PackageSetting ps = null;
5762 // Confirm if the system package has been updated
5763 // An updated system app can be deleted. This will also have to restore
5764 // the system pkg from system partition
5765 synchronized (mPackages) {
5766 ps = mSettings.getDisabledSystemPkg(p.packageName);
5767 }
5768 if (ps == null) {
5769 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5770 return false;
5771 } else {
5772 Log.i(TAG, "Deleting system pkg from data partition");
5773 }
5774 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005775 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005776 boolean deleteCodeAndResources = false;
5777 if (ps.versionCode < p.mVersionCode) {
5778 // Delete code and resources for downgrades
5779 deleteCodeAndResources = true;
5780 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5781 flags &= ~PackageManager.DONT_DELETE_DATA;
5782 }
5783 } else {
5784 // Preserve data by setting flag
5785 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5786 flags |= PackageManager.DONT_DELETE_DATA;
5787 }
5788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5790 if (!ret) {
5791 return false;
5792 }
5793 synchronized (mPackages) {
5794 // Reinstate the old system package
5795 mSettings.enableSystemPackageLP(p.packageName);
5796 }
5797 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005798 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005800 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 if (newPkg == null) {
5803 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5804 return false;
5805 }
5806 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005807 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 mSettings.writeLP();
5809 }
5810 return true;
5811 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005813 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5814 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5815 ApplicationInfo applicationInfo = p.applicationInfo;
5816 if (applicationInfo == null) {
5817 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5818 return false;
5819 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005820 if (outInfo != null) {
5821 outInfo.uid = applicationInfo.uid;
5822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823
5824 // Delete package data from internal structures and also remove data if flag is set
5825 removePackageDataLI(p, outInfo, flags);
5826
5827 // Delete application code and resources
5828 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005829 // TODO can pick up from PackageSettings as well
5830 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005831 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005832 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5833 PackageManager.INSTALL_FORWARD_LOCK : 0;
5834 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005835 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 }
5837 return true;
5838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 /*
5841 * This method handles package deletion in general
5842 */
5843 private boolean deletePackageLI(String packageName,
5844 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5845 if (packageName == null) {
5846 Log.w(TAG, "Attempt to delete null packageName.");
5847 return false;
5848 }
5849 PackageParser.Package p;
5850 boolean dataOnly = false;
5851 synchronized (mPackages) {
5852 p = mPackages.get(packageName);
5853 if (p == null) {
5854 //this retrieves partially installed apps
5855 dataOnly = true;
5856 PackageSetting ps = mSettings.mPackages.get(packageName);
5857 if (ps == null) {
5858 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5859 return false;
5860 }
5861 p = ps.pkg;
5862 }
5863 }
5864 if (p == null) {
5865 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5866 return false;
5867 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 if (dataOnly) {
5870 // Delete application data first
5871 removePackageDataLI(p, outInfo, flags);
5872 return true;
5873 }
5874 // At this point the package should have ApplicationInfo associated with it
5875 if (p.applicationInfo == null) {
5876 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5877 return false;
5878 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005879 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5881 Log.i(TAG, "Removing system package:"+p.packageName);
5882 // When an updated system application is deleted we delete the existing resources as well and
5883 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005884 ret = deleteSystemPackageLI(p, flags, outInfo);
5885 } else {
5886 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005887 // Kill application pre-emptively especially for apps on sd.
5888 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005889 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005891 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 public void clearApplicationUserData(final String packageName,
5895 final IPackageDataObserver observer) {
5896 mContext.enforceCallingOrSelfPermission(
5897 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5898 // Queue up an async operation since the package deletion may take a little while.
5899 mHandler.post(new Runnable() {
5900 public void run() {
5901 mHandler.removeCallbacks(this);
5902 final boolean succeeded;
5903 synchronized (mInstallLock) {
5904 succeeded = clearApplicationUserDataLI(packageName);
5905 }
5906 if (succeeded) {
5907 // invoke DeviceStorageMonitor's update method to clear any notifications
5908 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5909 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5910 if (dsm != null) {
5911 dsm.updateMemory();
5912 }
5913 }
5914 if(observer != null) {
5915 try {
5916 observer.onRemoveCompleted(packageName, succeeded);
5917 } catch (RemoteException e) {
5918 Log.i(TAG, "Observer no longer exists.");
5919 }
5920 } //end if observer
5921 } //end run
5922 });
5923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 private boolean clearApplicationUserDataLI(String packageName) {
5926 if (packageName == null) {
5927 Log.w(TAG, "Attempt to delete null packageName.");
5928 return false;
5929 }
5930 PackageParser.Package p;
5931 boolean dataOnly = false;
5932 synchronized (mPackages) {
5933 p = mPackages.get(packageName);
5934 if(p == null) {
5935 dataOnly = true;
5936 PackageSetting ps = mSettings.mPackages.get(packageName);
5937 if((ps == null) || (ps.pkg == null)) {
5938 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5939 return false;
5940 }
5941 p = ps.pkg;
5942 }
5943 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005944 boolean useEncryptedFSDir = false;
5945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 if(!dataOnly) {
5947 //need to check this only for fully installed applications
5948 if (p == null) {
5949 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5950 return false;
5951 }
5952 final ApplicationInfo applicationInfo = p.applicationInfo;
5953 if (applicationInfo == null) {
5954 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5955 return false;
5956 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005957 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005958 }
5959 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005960 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 if (retCode < 0) {
5962 Log.w(TAG, "Couldn't remove cache files for package: "
5963 + packageName);
5964 return false;
5965 }
5966 }
5967 return true;
5968 }
5969
5970 public void deleteApplicationCacheFiles(final String packageName,
5971 final IPackageDataObserver observer) {
5972 mContext.enforceCallingOrSelfPermission(
5973 android.Manifest.permission.DELETE_CACHE_FILES, null);
5974 // Queue up an async operation since the package deletion may take a little while.
5975 mHandler.post(new Runnable() {
5976 public void run() {
5977 mHandler.removeCallbacks(this);
5978 final boolean succeded;
5979 synchronized (mInstallLock) {
5980 succeded = deleteApplicationCacheFilesLI(packageName);
5981 }
5982 if(observer != null) {
5983 try {
5984 observer.onRemoveCompleted(packageName, succeded);
5985 } catch (RemoteException e) {
5986 Log.i(TAG, "Observer no longer exists.");
5987 }
5988 } //end if observer
5989 } //end run
5990 });
5991 }
5992
5993 private boolean deleteApplicationCacheFilesLI(String packageName) {
5994 if (packageName == null) {
5995 Log.w(TAG, "Attempt to delete null packageName.");
5996 return false;
5997 }
5998 PackageParser.Package p;
5999 synchronized (mPackages) {
6000 p = mPackages.get(packageName);
6001 }
6002 if (p == null) {
6003 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6004 return false;
6005 }
6006 final ApplicationInfo applicationInfo = p.applicationInfo;
6007 if (applicationInfo == null) {
6008 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6009 return false;
6010 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006011 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006013 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014 if (retCode < 0) {
6015 Log.w(TAG, "Couldn't remove cache files for package: "
6016 + packageName);
6017 return false;
6018 }
6019 }
6020 return true;
6021 }
6022
6023 public void getPackageSizeInfo(final String packageName,
6024 final IPackageStatsObserver observer) {
6025 mContext.enforceCallingOrSelfPermission(
6026 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6027 // Queue up an async operation since the package deletion may take a little while.
6028 mHandler.post(new Runnable() {
6029 public void run() {
6030 mHandler.removeCallbacks(this);
6031 PackageStats lStats = new PackageStats(packageName);
6032 final boolean succeded;
6033 synchronized (mInstallLock) {
6034 succeded = getPackageSizeInfoLI(packageName, lStats);
6035 }
6036 if(observer != null) {
6037 try {
6038 observer.onGetStatsCompleted(lStats, succeded);
6039 } catch (RemoteException e) {
6040 Log.i(TAG, "Observer no longer exists.");
6041 }
6042 } //end if observer
6043 } //end run
6044 });
6045 }
6046
6047 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6048 if (packageName == null) {
6049 Log.w(TAG, "Attempt to get size of null packageName.");
6050 return false;
6051 }
6052 PackageParser.Package p;
6053 boolean dataOnly = false;
6054 synchronized (mPackages) {
6055 p = mPackages.get(packageName);
6056 if(p == null) {
6057 dataOnly = true;
6058 PackageSetting ps = mSettings.mPackages.get(packageName);
6059 if((ps == null) || (ps.pkg == null)) {
6060 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6061 return false;
6062 }
6063 p = ps.pkg;
6064 }
6065 }
6066 String publicSrcDir = null;
6067 if(!dataOnly) {
6068 final ApplicationInfo applicationInfo = p.applicationInfo;
6069 if (applicationInfo == null) {
6070 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6071 return false;
6072 }
6073 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6074 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006075 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 if (mInstaller != null) {
6077 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006078 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 if (res < 0) {
6080 return false;
6081 } else {
6082 return true;
6083 }
6084 }
6085 return true;
6086 }
6087
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 public void addPackageToPreferred(String packageName) {
6090 mContext.enforceCallingOrSelfPermission(
6091 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006092 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 }
6094
6095 public void removePackageFromPreferred(String packageName) {
6096 mContext.enforceCallingOrSelfPermission(
6097 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006098 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 }
6100
6101 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006102 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 }
6104
6105 public void addPreferredActivity(IntentFilter filter, int match,
6106 ComponentName[] set, ComponentName activity) {
6107 mContext.enforceCallingOrSelfPermission(
6108 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6109
6110 synchronized (mPackages) {
6111 Log.i(TAG, "Adding preferred activity " + activity + ":");
6112 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6113 mSettings.mPreferredActivities.addFilter(
6114 new PreferredActivity(filter, match, set, activity));
6115 mSettings.writeLP();
6116 }
6117 }
6118
Satish Sampath8dbe6122009-06-02 23:35:54 +01006119 public void replacePreferredActivity(IntentFilter filter, int match,
6120 ComponentName[] set, ComponentName activity) {
6121 mContext.enforceCallingOrSelfPermission(
6122 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6123 if (filter.countActions() != 1) {
6124 throw new IllegalArgumentException(
6125 "replacePreferredActivity expects filter to have only 1 action.");
6126 }
6127 if (filter.countCategories() != 1) {
6128 throw new IllegalArgumentException(
6129 "replacePreferredActivity expects filter to have only 1 category.");
6130 }
6131 if (filter.countDataAuthorities() != 0
6132 || filter.countDataPaths() != 0
6133 || filter.countDataSchemes() != 0
6134 || filter.countDataTypes() != 0) {
6135 throw new IllegalArgumentException(
6136 "replacePreferredActivity expects filter to have no data authorities, " +
6137 "paths, schemes or types.");
6138 }
6139 synchronized (mPackages) {
6140 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6141 String action = filter.getAction(0);
6142 String category = filter.getCategory(0);
6143 while (it.hasNext()) {
6144 PreferredActivity pa = it.next();
6145 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6146 it.remove();
6147 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6148 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6149 }
6150 }
6151 addPreferredActivity(filter, match, set, activity);
6152 }
6153 }
6154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 public void clearPackagePreferredActivities(String packageName) {
6156 mContext.enforceCallingOrSelfPermission(
6157 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6158
6159 synchronized (mPackages) {
6160 if (clearPackagePreferredActivitiesLP(packageName)) {
6161 mSettings.writeLP();
6162 }
6163 }
6164 }
6165
6166 boolean clearPackagePreferredActivitiesLP(String packageName) {
6167 boolean changed = false;
6168 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6169 while (it.hasNext()) {
6170 PreferredActivity pa = it.next();
6171 if (pa.mActivity.getPackageName().equals(packageName)) {
6172 it.remove();
6173 changed = true;
6174 }
6175 }
6176 return changed;
6177 }
6178
6179 public int getPreferredActivities(List<IntentFilter> outFilters,
6180 List<ComponentName> outActivities, String packageName) {
6181
6182 int num = 0;
6183 synchronized (mPackages) {
6184 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6185 while (it.hasNext()) {
6186 PreferredActivity pa = it.next();
6187 if (packageName == null
6188 || pa.mActivity.getPackageName().equals(packageName)) {
6189 if (outFilters != null) {
6190 outFilters.add(new IntentFilter(pa));
6191 }
6192 if (outActivities != null) {
6193 outActivities.add(pa.mActivity);
6194 }
6195 }
6196 }
6197 }
6198
6199 return num;
6200 }
6201
6202 public void setApplicationEnabledSetting(String appPackageName,
6203 int newState, int flags) {
6204 setEnabledSetting(appPackageName, null, newState, flags);
6205 }
6206
6207 public void setComponentEnabledSetting(ComponentName componentName,
6208 int newState, int flags) {
6209 setEnabledSetting(componentName.getPackageName(),
6210 componentName.getClassName(), newState, flags);
6211 }
6212
6213 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006214 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6216 || newState == COMPONENT_ENABLED_STATE_ENABLED
6217 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6218 throw new IllegalArgumentException("Invalid new component state: "
6219 + newState);
6220 }
6221 PackageSetting pkgSetting;
6222 final int uid = Binder.getCallingUid();
6223 final int permission = mContext.checkCallingPermission(
6224 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6225 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006226 boolean sendNow = false;
6227 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006228 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006230 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006232 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006234 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006236 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 }
6238 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006239 "Unknown component: " + packageName
6240 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 }
6242 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6243 throw new SecurityException(
6244 "Permission Denial: attempt to change component state from pid="
6245 + Binder.getCallingPid()
6246 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6247 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006248 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006249 // We're dealing with an application/package level state change
6250 pkgSetting.enabled = newState;
6251 } else {
6252 // We're dealing with a component level state change
6253 switch (newState) {
6254 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006255 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 break;
6257 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006258 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 break;
6260 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006261 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 break;
6263 default:
6264 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006265 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 }
6267 }
6268 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006269 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006270 components = mPendingBroadcasts.get(packageName);
6271 boolean newPackage = components == null;
6272 if (newPackage) {
6273 components = new ArrayList<String>();
6274 }
6275 if (!components.contains(componentName)) {
6276 components.add(componentName);
6277 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006278 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6279 sendNow = true;
6280 // Purge entry from pending broadcast list if another one exists already
6281 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006282 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006283 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006284 if (newPackage) {
6285 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006286 }
6287 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6288 // Schedule a message
6289 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6290 }
6291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 long callingId = Binder.clearCallingIdentity();
6295 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006296 if (sendNow) {
6297 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006298 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 } finally {
6301 Binder.restoreCallingIdentity(callingId);
6302 }
6303 }
6304
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006305 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006306 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6307 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6308 + " components=" + componentNames);
6309 Bundle extras = new Bundle(4);
6310 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6311 String nameList[] = new String[componentNames.size()];
6312 componentNames.toArray(nameList);
6313 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006314 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6315 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006316 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006317 }
6318
Jacek Surazski65e13172009-04-28 15:26:38 +02006319 public String getInstallerPackageName(String packageName) {
6320 synchronized (mPackages) {
6321 PackageSetting pkg = mSettings.mPackages.get(packageName);
6322 if (pkg == null) {
6323 throw new IllegalArgumentException("Unknown package: " + packageName);
6324 }
6325 return pkg.installerPackageName;
6326 }
6327 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 public int getApplicationEnabledSetting(String appPackageName) {
6330 synchronized (mPackages) {
6331 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6332 if (pkg == null) {
6333 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6334 }
6335 return pkg.enabled;
6336 }
6337 }
6338
6339 public int getComponentEnabledSetting(ComponentName componentName) {
6340 synchronized (mPackages) {
6341 final String packageNameStr = componentName.getPackageName();
6342 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6343 if (pkg == null) {
6344 throw new IllegalArgumentException("Unknown component: " + componentName);
6345 }
6346 final String classNameStr = componentName.getClassName();
6347 return pkg.currentEnabledStateLP(classNameStr);
6348 }
6349 }
6350
6351 public void enterSafeMode() {
6352 if (!mSystemReady) {
6353 mSafeMode = true;
6354 }
6355 }
6356
6357 public void systemReady() {
6358 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006359
6360 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006361 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006362 mContext.getContentResolver(),
6363 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006364 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006365 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006366 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 }
6369
6370 public boolean isSafeMode() {
6371 return mSafeMode;
6372 }
6373
6374 public boolean hasSystemUidErrors() {
6375 return mHasSystemUidErrors;
6376 }
6377
6378 static String arrayToString(int[] array) {
6379 StringBuffer buf = new StringBuffer(128);
6380 buf.append('[');
6381 if (array != null) {
6382 for (int i=0; i<array.length; i++) {
6383 if (i > 0) buf.append(", ");
6384 buf.append(array[i]);
6385 }
6386 }
6387 buf.append(']');
6388 return buf.toString();
6389 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 @Override
6392 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6393 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6394 != PackageManager.PERMISSION_GRANTED) {
6395 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6396 + Binder.getCallingPid()
6397 + ", uid=" + Binder.getCallingUid()
6398 + " without permission "
6399 + android.Manifest.permission.DUMP);
6400 return;
6401 }
6402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 synchronized (mPackages) {
6404 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006405 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 pw.println(" ");
6407 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006408 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 pw.println(" ");
6410 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006411 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 pw.println(" ");
6413 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006414 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 pw.println("Permissions:");
6417 {
6418 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006419 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6420 pw.print(Integer.toHexString(System.identityHashCode(p)));
6421 pw.println("):");
6422 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6423 pw.print(" uid="); pw.print(p.uid);
6424 pw.print(" gids="); pw.print(arrayToString(p.gids));
6425 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 }
6427 }
6428 pw.println(" ");
6429 pw.println("Packages:");
6430 {
6431 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006432 pw.print(" Package [");
6433 pw.print(ps.realName != null ? ps.realName : ps.name);
6434 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006435 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6436 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006437 if (ps.realName != null) {
6438 pw.print(" compat name="); pw.println(ps.name);
6439 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006440 pw.print(" userId="); pw.print(ps.userId);
6441 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6442 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6443 pw.print(" pkg="); pw.println(ps.pkg);
6444 pw.print(" codePath="); pw.println(ps.codePathString);
6445 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006447 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006448 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006449 pw.print(" supportsScreens=[");
6450 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006451 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006452 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006453 if (!first) pw.print(", ");
6454 first = false;
6455 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006456 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006457 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006458 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006459 if (!first) pw.print(", ");
6460 first = false;
6461 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006462 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006463 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006464 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006465 if (!first) pw.print(", ");
6466 first = false;
6467 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006468 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006469 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006470 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006471 if (!first) pw.print(", ");
6472 first = false;
6473 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006474 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006475 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006476 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6477 if (!first) pw.print(", ");
6478 first = false;
6479 pw.print("anyDensity");
6480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006482 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006483 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6484 pw.print(" signatures="); pw.println(ps.signatures);
6485 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6486 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6487 pw.print(" installStatus="); pw.print(ps.installStatus);
6488 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 if (ps.disabledComponents.size() > 0) {
6490 pw.println(" disabledComponents:");
6491 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006492 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 }
6494 }
6495 if (ps.enabledComponents.size() > 0) {
6496 pw.println(" enabledComponents:");
6497 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006498 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 }
6500 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006501 if (ps.grantedPermissions.size() > 0) {
6502 pw.println(" grantedPermissions:");
6503 for (String s : ps.grantedPermissions) {
6504 pw.print(" "); pw.println(s);
6505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006507 if (ps.loadedPermissions.size() > 0) {
6508 pw.println(" loadedPermissions:");
6509 for (String s : ps.loadedPermissions) {
6510 pw.print(" "); pw.println(s);
6511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 }
6513 }
6514 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006515 if (mSettings.mRenamedPackages.size() > 0) {
6516 pw.println(" ");
6517 pw.println("Renamed packages:");
6518 for (HashMap.Entry<String, String> e
6519 : mSettings.mRenamedPackages.entrySet()) {
6520 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6521 pw.println(e.getValue());
6522 }
6523 }
6524 if (mSettings.mDisabledSysPackages.size() > 0) {
6525 pw.println(" ");
6526 pw.println("Hidden system packages:");
6527 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6528 pw.print(" Package [");
6529 pw.print(ps.realName != null ? ps.realName : ps.name);
6530 pw.print("] (");
6531 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6532 pw.println("):");
6533 if (ps.realName != null) {
6534 pw.print(" compat name="); pw.println(ps.name);
6535 }
6536 pw.print(" userId="); pw.println(ps.userId);
6537 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6538 pw.print(" codePath="); pw.println(ps.codePathString);
6539 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6540 }
6541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006542 pw.println(" ");
6543 pw.println("Shared Users:");
6544 {
6545 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006546 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6547 pw.print(Integer.toHexString(System.identityHashCode(su)));
6548 pw.println("):");
6549 pw.print(" userId="); pw.print(su.userId);
6550 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006551 pw.println(" grantedPermissions:");
6552 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006553 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006554 }
6555 pw.println(" loadedPermissions:");
6556 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006557 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006558 }
6559 }
6560 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006562 pw.println(" ");
6563 pw.println("Settings parse messages:");
6564 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006565
6566 pw.println(" ");
6567 pw.println("Package warning messages:");
6568 File fname = getSettingsProblemFile();
6569 FileInputStream in;
6570 try {
6571 in = new FileInputStream(fname);
6572 int avail = in.available();
6573 byte[] data = new byte[avail];
6574 in.read(data);
6575 pw.println(new String(data));
6576 } catch (FileNotFoundException e) {
6577 } catch (IOException e) {
6578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006580
6581 synchronized (mProviders) {
6582 pw.println(" ");
6583 pw.println("Registered ContentProviders:");
6584 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006585 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006586 pw.println(p.toString());
6587 }
6588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 }
6590
6591 static final class BasePermission {
6592 final static int TYPE_NORMAL = 0;
6593 final static int TYPE_BUILTIN = 1;
6594 final static int TYPE_DYNAMIC = 2;
6595
6596 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006597 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 final int type;
6599 PackageParser.Permission perm;
6600 PermissionInfo pendingInfo;
6601 int uid;
6602 int[] gids;
6603
6604 BasePermission(String _name, String _sourcePackage, int _type) {
6605 name = _name;
6606 sourcePackage = _sourcePackage;
6607 type = _type;
6608 }
6609 }
6610
6611 static class PackageSignatures {
6612 private Signature[] mSignatures;
6613
6614 PackageSignatures(Signature[] sigs) {
6615 assignSignatures(sigs);
6616 }
6617
6618 PackageSignatures() {
6619 }
6620
6621 void writeXml(XmlSerializer serializer, String tagName,
6622 ArrayList<Signature> pastSignatures) throws IOException {
6623 if (mSignatures == null) {
6624 return;
6625 }
6626 serializer.startTag(null, tagName);
6627 serializer.attribute(null, "count",
6628 Integer.toString(mSignatures.length));
6629 for (int i=0; i<mSignatures.length; i++) {
6630 serializer.startTag(null, "cert");
6631 final Signature sig = mSignatures[i];
6632 final int sigHash = sig.hashCode();
6633 final int numPast = pastSignatures.size();
6634 int j;
6635 for (j=0; j<numPast; j++) {
6636 Signature pastSig = pastSignatures.get(j);
6637 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6638 serializer.attribute(null, "index", Integer.toString(j));
6639 break;
6640 }
6641 }
6642 if (j >= numPast) {
6643 pastSignatures.add(sig);
6644 serializer.attribute(null, "index", Integer.toString(numPast));
6645 serializer.attribute(null, "key", sig.toCharsString());
6646 }
6647 serializer.endTag(null, "cert");
6648 }
6649 serializer.endTag(null, tagName);
6650 }
6651
6652 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6653 throws IOException, XmlPullParserException {
6654 String countStr = parser.getAttributeValue(null, "count");
6655 if (countStr == null) {
6656 reportSettingsProblem(Log.WARN,
6657 "Error in package manager settings: <signatures> has"
6658 + " no count at " + parser.getPositionDescription());
6659 XmlUtils.skipCurrentTag(parser);
6660 }
6661 final int count = Integer.parseInt(countStr);
6662 mSignatures = new Signature[count];
6663 int pos = 0;
6664
6665 int outerDepth = parser.getDepth();
6666 int type;
6667 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6668 && (type != XmlPullParser.END_TAG
6669 || parser.getDepth() > outerDepth)) {
6670 if (type == XmlPullParser.END_TAG
6671 || type == XmlPullParser.TEXT) {
6672 continue;
6673 }
6674
6675 String tagName = parser.getName();
6676 if (tagName.equals("cert")) {
6677 if (pos < count) {
6678 String index = parser.getAttributeValue(null, "index");
6679 if (index != null) {
6680 try {
6681 int idx = Integer.parseInt(index);
6682 String key = parser.getAttributeValue(null, "key");
6683 if (key == null) {
6684 if (idx >= 0 && idx < pastSignatures.size()) {
6685 Signature sig = pastSignatures.get(idx);
6686 if (sig != null) {
6687 mSignatures[pos] = pastSignatures.get(idx);
6688 pos++;
6689 } else {
6690 reportSettingsProblem(Log.WARN,
6691 "Error in package manager settings: <cert> "
6692 + "index " + index + " is not defined at "
6693 + parser.getPositionDescription());
6694 }
6695 } else {
6696 reportSettingsProblem(Log.WARN,
6697 "Error in package manager settings: <cert> "
6698 + "index " + index + " is out of bounds at "
6699 + parser.getPositionDescription());
6700 }
6701 } else {
6702 while (pastSignatures.size() <= idx) {
6703 pastSignatures.add(null);
6704 }
6705 Signature sig = new Signature(key);
6706 pastSignatures.set(idx, sig);
6707 mSignatures[pos] = sig;
6708 pos++;
6709 }
6710 } catch (NumberFormatException e) {
6711 reportSettingsProblem(Log.WARN,
6712 "Error in package manager settings: <cert> "
6713 + "index " + index + " is not a number at "
6714 + parser.getPositionDescription());
6715 }
6716 } else {
6717 reportSettingsProblem(Log.WARN,
6718 "Error in package manager settings: <cert> has"
6719 + " no index at " + parser.getPositionDescription());
6720 }
6721 } else {
6722 reportSettingsProblem(Log.WARN,
6723 "Error in package manager settings: too "
6724 + "many <cert> tags, expected " + count
6725 + " at " + parser.getPositionDescription());
6726 }
6727 } else {
6728 reportSettingsProblem(Log.WARN,
6729 "Unknown element under <cert>: "
6730 + parser.getName());
6731 }
6732 XmlUtils.skipCurrentTag(parser);
6733 }
6734
6735 if (pos < count) {
6736 // Should never happen -- there is an error in the written
6737 // settings -- but if it does we don't want to generate
6738 // a bad array.
6739 Signature[] newSigs = new Signature[pos];
6740 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6741 mSignatures = newSigs;
6742 }
6743 }
6744
6745 /**
6746 * If any of the given 'sigs' is contained in the existing signatures,
6747 * then completely replace the current signatures with the ones in
6748 * 'sigs'. This is used for updating an existing package to a newly
6749 * installed version.
6750 */
6751 boolean updateSignatures(Signature[] sigs, boolean update) {
6752 if (mSignatures == null) {
6753 if (update) {
6754 assignSignatures(sigs);
6755 }
6756 return true;
6757 }
6758 if (sigs == null) {
6759 return false;
6760 }
6761
6762 for (int i=0; i<sigs.length; i++) {
6763 Signature sig = sigs[i];
6764 for (int j=0; j<mSignatures.length; j++) {
6765 if (mSignatures[j].equals(sig)) {
6766 if (update) {
6767 assignSignatures(sigs);
6768 }
6769 return true;
6770 }
6771 }
6772 }
6773 return false;
6774 }
6775
6776 /**
6777 * If any of the given 'sigs' is contained in the existing signatures,
6778 * then add in any new signatures found in 'sigs'. This is used for
6779 * including a new package into an existing shared user id.
6780 */
6781 boolean mergeSignatures(Signature[] sigs, boolean update) {
6782 if (mSignatures == null) {
6783 if (update) {
6784 assignSignatures(sigs);
6785 }
6786 return true;
6787 }
6788 if (sigs == null) {
6789 return false;
6790 }
6791
6792 Signature[] added = null;
6793 int addedCount = 0;
6794 boolean haveMatch = false;
6795 for (int i=0; i<sigs.length; i++) {
6796 Signature sig = sigs[i];
6797 boolean found = false;
6798 for (int j=0; j<mSignatures.length; j++) {
6799 if (mSignatures[j].equals(sig)) {
6800 found = true;
6801 haveMatch = true;
6802 break;
6803 }
6804 }
6805
6806 if (!found) {
6807 if (added == null) {
6808 added = new Signature[sigs.length];
6809 }
6810 added[i] = sig;
6811 addedCount++;
6812 }
6813 }
6814
6815 if (!haveMatch) {
6816 // Nothing matched -- reject the new signatures.
6817 return false;
6818 }
6819 if (added == null) {
6820 // Completely matched -- nothing else to do.
6821 return true;
6822 }
6823
6824 // Add additional signatures in.
6825 if (update) {
6826 Signature[] total = new Signature[addedCount+mSignatures.length];
6827 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6828 int j = mSignatures.length;
6829 for (int i=0; i<added.length; i++) {
6830 if (added[i] != null) {
6831 total[j] = added[i];
6832 j++;
6833 }
6834 }
6835 mSignatures = total;
6836 }
6837 return true;
6838 }
6839
6840 private void assignSignatures(Signature[] sigs) {
6841 if (sigs == null) {
6842 mSignatures = null;
6843 return;
6844 }
6845 mSignatures = new Signature[sigs.length];
6846 for (int i=0; i<sigs.length; i++) {
6847 mSignatures[i] = sigs[i];
6848 }
6849 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006851 @Override
6852 public String toString() {
6853 StringBuffer buf = new StringBuffer(128);
6854 buf.append("PackageSignatures{");
6855 buf.append(Integer.toHexString(System.identityHashCode(this)));
6856 buf.append(" [");
6857 if (mSignatures != null) {
6858 for (int i=0; i<mSignatures.length; i++) {
6859 if (i > 0) buf.append(", ");
6860 buf.append(Integer.toHexString(
6861 System.identityHashCode(mSignatures[i])));
6862 }
6863 }
6864 buf.append("]}");
6865 return buf.toString();
6866 }
6867 }
6868
6869 static class PreferredActivity extends IntentFilter {
6870 final int mMatch;
6871 final String[] mSetPackages;
6872 final String[] mSetClasses;
6873 final String[] mSetComponents;
6874 final ComponentName mActivity;
6875 final String mShortActivity;
6876 String mParseError;
6877
6878 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6879 ComponentName activity) {
6880 super(filter);
6881 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6882 mActivity = activity;
6883 mShortActivity = activity.flattenToShortString();
6884 mParseError = null;
6885 if (set != null) {
6886 final int N = set.length;
6887 String[] myPackages = new String[N];
6888 String[] myClasses = new String[N];
6889 String[] myComponents = new String[N];
6890 for (int i=0; i<N; i++) {
6891 ComponentName cn = set[i];
6892 if (cn == null) {
6893 mSetPackages = null;
6894 mSetClasses = null;
6895 mSetComponents = null;
6896 return;
6897 }
6898 myPackages[i] = cn.getPackageName().intern();
6899 myClasses[i] = cn.getClassName().intern();
6900 myComponents[i] = cn.flattenToShortString().intern();
6901 }
6902 mSetPackages = myPackages;
6903 mSetClasses = myClasses;
6904 mSetComponents = myComponents;
6905 } else {
6906 mSetPackages = null;
6907 mSetClasses = null;
6908 mSetComponents = null;
6909 }
6910 }
6911
6912 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6913 IOException {
6914 mShortActivity = parser.getAttributeValue(null, "name");
6915 mActivity = ComponentName.unflattenFromString(mShortActivity);
6916 if (mActivity == null) {
6917 mParseError = "Bad activity name " + mShortActivity;
6918 }
6919 String matchStr = parser.getAttributeValue(null, "match");
6920 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6921 String setCountStr = parser.getAttributeValue(null, "set");
6922 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6923
6924 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6925 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6926 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6927
6928 int setPos = 0;
6929
6930 int outerDepth = parser.getDepth();
6931 int type;
6932 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6933 && (type != XmlPullParser.END_TAG
6934 || parser.getDepth() > outerDepth)) {
6935 if (type == XmlPullParser.END_TAG
6936 || type == XmlPullParser.TEXT) {
6937 continue;
6938 }
6939
6940 String tagName = parser.getName();
6941 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6942 // + parser.getDepth() + " tag=" + tagName);
6943 if (tagName.equals("set")) {
6944 String name = parser.getAttributeValue(null, "name");
6945 if (name == null) {
6946 if (mParseError == null) {
6947 mParseError = "No name in set tag in preferred activity "
6948 + mShortActivity;
6949 }
6950 } else if (setPos >= setCount) {
6951 if (mParseError == null) {
6952 mParseError = "Too many set tags in preferred activity "
6953 + mShortActivity;
6954 }
6955 } else {
6956 ComponentName cn = ComponentName.unflattenFromString(name);
6957 if (cn == null) {
6958 if (mParseError == null) {
6959 mParseError = "Bad set name " + name + " in preferred activity "
6960 + mShortActivity;
6961 }
6962 } else {
6963 myPackages[setPos] = cn.getPackageName();
6964 myClasses[setPos] = cn.getClassName();
6965 myComponents[setPos] = name;
6966 setPos++;
6967 }
6968 }
6969 XmlUtils.skipCurrentTag(parser);
6970 } else if (tagName.equals("filter")) {
6971 //Log.i(TAG, "Starting to parse filter...");
6972 readFromXml(parser);
6973 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6974 // + parser.getDepth() + " tag=" + parser.getName());
6975 } else {
6976 reportSettingsProblem(Log.WARN,
6977 "Unknown element under <preferred-activities>: "
6978 + parser.getName());
6979 XmlUtils.skipCurrentTag(parser);
6980 }
6981 }
6982
6983 if (setPos != setCount) {
6984 if (mParseError == null) {
6985 mParseError = "Not enough set tags (expected " + setCount
6986 + " but found " + setPos + ") in " + mShortActivity;
6987 }
6988 }
6989
6990 mSetPackages = myPackages;
6991 mSetClasses = myClasses;
6992 mSetComponents = myComponents;
6993 }
6994
6995 public void writeToXml(XmlSerializer serializer) throws IOException {
6996 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6997 serializer.attribute(null, "name", mShortActivity);
6998 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6999 serializer.attribute(null, "set", Integer.toString(NS));
7000 for (int s=0; s<NS; s++) {
7001 serializer.startTag(null, "set");
7002 serializer.attribute(null, "name", mSetComponents[s]);
7003 serializer.endTag(null, "set");
7004 }
7005 serializer.startTag(null, "filter");
7006 super.writeToXml(serializer);
7007 serializer.endTag(null, "filter");
7008 }
7009
7010 boolean sameSet(List<ResolveInfo> query, int priority) {
7011 if (mSetPackages == null) return false;
7012 final int NQ = query.size();
7013 final int NS = mSetPackages.length;
7014 int numMatch = 0;
7015 for (int i=0; i<NQ; i++) {
7016 ResolveInfo ri = query.get(i);
7017 if (ri.priority != priority) continue;
7018 ActivityInfo ai = ri.activityInfo;
7019 boolean good = false;
7020 for (int j=0; j<NS; j++) {
7021 if (mSetPackages[j].equals(ai.packageName)
7022 && mSetClasses[j].equals(ai.name)) {
7023 numMatch++;
7024 good = true;
7025 break;
7026 }
7027 }
7028 if (!good) return false;
7029 }
7030 return numMatch == NS;
7031 }
7032 }
7033
7034 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007035 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 HashSet<String> grantedPermissions = new HashSet<String>();
7038 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007042 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007043 setFlags(pkgFlags);
7044 }
7045
7046 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007047 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007048 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
7049 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 }
7051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 /**
7054 * Settings base class for pending and resolved classes.
7055 */
7056 static class PackageSettingBase extends GrantedPermissions {
7057 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007058 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007059 File codePath;
7060 String codePathString;
7061 File resourcePath;
7062 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063 private long timeStamp;
7064 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007065 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007066
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007067 boolean uidError;
7068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007069 PackageSignatures signatures = new PackageSignatures();
7070
7071 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 /* Explicitly disabled components */
7074 HashSet<String> disabledComponents = new HashSet<String>(0);
7075 /* Explicitly enabled components */
7076 HashSet<String> enabledComponents = new HashSet<String>(0);
7077 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7078 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007079
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007080 PackageSettingBase origPackage;
7081
Jacek Surazski65e13172009-04-28 15:26:38 +02007082 /* package name of the app that installed this package */
7083 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007084
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007085 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007086 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 super(pkgFlags);
7088 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007089 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007090 init(codePath, resourcePath, pVersionCode);
7091 }
7092
7093 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 this.codePath = codePath;
7095 this.codePathString = codePath.toString();
7096 this.resourcePath = resourcePath;
7097 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007098 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007099 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007100
Jacek Surazski65e13172009-04-28 15:26:38 +02007101 public void setInstallerPackageName(String packageName) {
7102 installerPackageName = packageName;
7103 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007104
Jacek Surazski65e13172009-04-28 15:26:38 +02007105 String getInstallerPackageName() {
7106 return installerPackageName;
7107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007109 public void setInstallStatus(int newStatus) {
7110 installStatus = newStatus;
7111 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007113 public int getInstallStatus() {
7114 return installStatus;
7115 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 public void setTimeStamp(long newStamp) {
7118 if (newStamp != timeStamp) {
7119 timeStamp = newStamp;
7120 timeStampString = Long.toString(newStamp);
7121 }
7122 }
7123
7124 public void setTimeStamp(long newStamp, String newStampStr) {
7125 timeStamp = newStamp;
7126 timeStampString = newStampStr;
7127 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 public long getTimeStamp() {
7130 return timeStamp;
7131 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007133 public String getTimeStampStr() {
7134 return timeStampString;
7135 }
7136
7137 public void copyFrom(PackageSettingBase base) {
7138 grantedPermissions = base.grantedPermissions;
7139 gids = base.gids;
7140 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 timeStamp = base.timeStamp;
7143 timeStampString = base.timeStampString;
7144 signatures = base.signatures;
7145 permissionsFixed = base.permissionsFixed;
7146 disabledComponents = base.disabledComponents;
7147 enabledComponents = base.enabledComponents;
7148 enabled = base.enabled;
7149 installStatus = base.installStatus;
7150 }
7151
7152 void enableComponentLP(String componentClassName) {
7153 disabledComponents.remove(componentClassName);
7154 enabledComponents.add(componentClassName);
7155 }
7156
7157 void disableComponentLP(String componentClassName) {
7158 enabledComponents.remove(componentClassName);
7159 disabledComponents.add(componentClassName);
7160 }
7161
7162 void restoreComponentLP(String componentClassName) {
7163 enabledComponents.remove(componentClassName);
7164 disabledComponents.remove(componentClassName);
7165 }
7166
7167 int currentEnabledStateLP(String componentName) {
7168 if (enabledComponents.contains(componentName)) {
7169 return COMPONENT_ENABLED_STATE_ENABLED;
7170 } else if (disabledComponents.contains(componentName)) {
7171 return COMPONENT_ENABLED_STATE_DISABLED;
7172 } else {
7173 return COMPONENT_ENABLED_STATE_DEFAULT;
7174 }
7175 }
7176 }
7177
7178 /**
7179 * Settings data for a particular package we know about.
7180 */
7181 static final class PackageSetting extends PackageSettingBase {
7182 int userId;
7183 PackageParser.Package pkg;
7184 SharedUserSetting sharedUser;
7185
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007186 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007187 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007188 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007189 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007191 @Override
7192 public String toString() {
7193 return "PackageSetting{"
7194 + Integer.toHexString(System.identityHashCode(this))
7195 + " " + name + "/" + userId + "}";
7196 }
7197 }
7198
7199 /**
7200 * Settings data for a particular shared user ID we know about.
7201 */
7202 static final class SharedUserSetting extends GrantedPermissions {
7203 final String name;
7204 int userId;
7205 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7206 final PackageSignatures signatures = new PackageSignatures();
7207
7208 SharedUserSetting(String _name, int _pkgFlags) {
7209 super(_pkgFlags);
7210 name = _name;
7211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213 @Override
7214 public String toString() {
7215 return "SharedUserSetting{"
7216 + Integer.toHexString(System.identityHashCode(this))
7217 + " " + name + "/" + userId + "}";
7218 }
7219 }
7220
7221 /**
7222 * Holds information about dynamic settings.
7223 */
7224 private static final class Settings {
7225 private final File mSettingsFilename;
7226 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007227 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 private final HashMap<String, PackageSetting> mPackages =
7229 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007230 // List of replaced system applications
7231 final HashMap<String, PackageSetting> mDisabledSysPackages =
7232 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 // The user's preferred activities associated with particular intent
7235 // filters.
7236 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7237 new IntentResolver<PreferredActivity, PreferredActivity>() {
7238 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007239 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007240 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007241 out.print(prefix); out.print(
7242 Integer.toHexString(System.identityHashCode(filter)));
7243 out.print(' ');
7244 out.print(filter.mActivity.flattenToShortString());
7245 out.print(" match=0x");
7246 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007247 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007248 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007250 out.print(prefix); out.print(" ");
7251 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007252 }
7253 }
7254 }
7255 };
7256 private final HashMap<String, SharedUserSetting> mSharedUsers =
7257 new HashMap<String, SharedUserSetting>();
7258 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7259 private final SparseArray<Object> mOtherUserIds =
7260 new SparseArray<Object>();
7261
7262 // For reading/writing settings file.
7263 private final ArrayList<Signature> mPastSignatures =
7264 new ArrayList<Signature>();
7265
7266 // Mapping from permission names to info about them.
7267 final HashMap<String, BasePermission> mPermissions =
7268 new HashMap<String, BasePermission>();
7269
7270 // Mapping from permission tree names to info about them.
7271 final HashMap<String, BasePermission> mPermissionTrees =
7272 new HashMap<String, BasePermission>();
7273
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007274 // Packages that have been uninstalled and still need their external
7275 // storage data deleted.
7276 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7277
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007278 // Packages that have been renamed since they were first installed.
7279 // Keys are the new names of the packages, values are the original
7280 // names. The packages appear everwhere else under their original
7281 // names.
7282 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 private final StringBuilder mReadMessages = new StringBuilder();
7285
7286 private static final class PendingPackage extends PackageSettingBase {
7287 final int sharedId;
7288
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007289 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007290 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007291 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 this.sharedId = sharedId;
7293 }
7294 }
7295 private final ArrayList<PendingPackage> mPendingPackages
7296 = new ArrayList<PendingPackage>();
7297
7298 Settings() {
7299 File dataDir = Environment.getDataDirectory();
7300 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007301 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7302 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007303 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007304 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007305 FileUtils.setPermissions(systemDir.toString(),
7306 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7307 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7308 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007309 FileUtils.setPermissions(systemSecureDir.toString(),
7310 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7311 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7312 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007313 mSettingsFilename = new File(systemDir, "packages.xml");
7314 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007315 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 }
7317
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007318 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007319 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007320 int pkgFlags, boolean create, boolean add) {
7321 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007322 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007323 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 return p;
7325 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007326
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007327 PackageSetting peekPackageLP(String name) {
7328 return mPackages.get(name);
7329 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 PackageSetting p = mPackages.get(name);
7331 if (p != null && p.codePath.getPath().equals(codePath)) {
7332 return p;
7333 }
7334 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007335 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007338 void setInstallStatus(String pkgName, int status) {
7339 PackageSetting p = mPackages.get(pkgName);
7340 if(p != null) {
7341 if(p.getInstallStatus() != status) {
7342 p.setInstallStatus(status);
7343 }
7344 }
7345 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007346
Jacek Surazski65e13172009-04-28 15:26:38 +02007347 void setInstallerPackageName(String pkgName,
7348 String installerPkgName) {
7349 PackageSetting p = mPackages.get(pkgName);
7350 if(p != null) {
7351 p.setInstallerPackageName(installerPkgName);
7352 }
7353 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007354
Jacek Surazski65e13172009-04-28 15:26:38 +02007355 String getInstallerPackageName(String pkgName) {
7356 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007357 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007358 }
7359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 int getInstallStatus(String pkgName) {
7361 PackageSetting p = mPackages.get(pkgName);
7362 if(p != null) {
7363 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007365 return -1;
7366 }
7367
7368 SharedUserSetting getSharedUserLP(String name,
7369 int pkgFlags, boolean create) {
7370 SharedUserSetting s = mSharedUsers.get(name);
7371 if (s == null) {
7372 if (!create) {
7373 return null;
7374 }
7375 s = new SharedUserSetting(name, pkgFlags);
7376 if (MULTIPLE_APPLICATION_UIDS) {
7377 s.userId = newUserIdLP(s);
7378 } else {
7379 s.userId = FIRST_APPLICATION_UID;
7380 }
7381 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7382 // < 0 means we couldn't assign a userid; fall out and return
7383 // s, which is currently null
7384 if (s.userId >= 0) {
7385 mSharedUsers.put(name, s);
7386 }
7387 }
7388
7389 return s;
7390 }
7391
7392 int disableSystemPackageLP(String name) {
7393 PackageSetting p = mPackages.get(name);
7394 if(p == null) {
7395 Log.w(TAG, "Package:"+name+" is not an installed package");
7396 return -1;
7397 }
7398 PackageSetting dp = mDisabledSysPackages.get(name);
7399 // always make sure the system package code and resource paths dont change
7400 if(dp == null) {
7401 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7402 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7403 }
7404 mDisabledSysPackages.put(name, p);
7405 }
7406 return removePackageLP(name);
7407 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 PackageSetting enableSystemPackageLP(String name) {
7410 PackageSetting p = mDisabledSysPackages.get(name);
7411 if(p == null) {
7412 Log.w(TAG, "Package:"+name+" is not disabled");
7413 return null;
7414 }
7415 // Reset flag in ApplicationInfo object
7416 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7417 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7418 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007419 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007420 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 mDisabledSysPackages.remove(name);
7422 return ret;
7423 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007424
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007425 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007426 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007427 PackageSetting p = mPackages.get(name);
7428 if (p != null) {
7429 if (p.userId == uid) {
7430 return p;
7431 }
7432 reportSettingsProblem(Log.ERROR,
7433 "Adding duplicate package, keeping first: " + name);
7434 return null;
7435 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007436 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007437 p.userId = uid;
7438 if (addUserIdLP(uid, p, name)) {
7439 mPackages.put(name, p);
7440 return p;
7441 }
7442 return null;
7443 }
7444
7445 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7446 SharedUserSetting s = mSharedUsers.get(name);
7447 if (s != null) {
7448 if (s.userId == uid) {
7449 return s;
7450 }
7451 reportSettingsProblem(Log.ERROR,
7452 "Adding duplicate shared user, keeping first: " + name);
7453 return null;
7454 }
7455 s = new SharedUserSetting(name, pkgFlags);
7456 s.userId = uid;
7457 if (addUserIdLP(uid, s, name)) {
7458 mSharedUsers.put(name, s);
7459 return s;
7460 }
7461 return null;
7462 }
7463
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007464 // Transfer ownership of permissions from one package to another.
7465 private void transferPermissions(String origPkg, String newPkg) {
7466 // Transfer ownership of permissions to the new package.
7467 for (int i=0; i<2; i++) {
7468 HashMap<String, BasePermission> permissions =
7469 i == 0 ? mPermissionTrees : mPermissions;
7470 for (BasePermission bp : permissions.values()) {
7471 if (origPkg.equals(bp.sourcePackage)) {
7472 if (DEBUG_UPGRADE) Log.v(TAG,
7473 "Moving permission " + bp.name
7474 + " from pkg " + bp.sourcePackage
7475 + " to " + newPkg);
7476 bp.sourcePackage = newPkg;
7477 bp.perm = null;
7478 if (bp.pendingInfo != null) {
7479 bp.sourcePackage = newPkg;
7480 }
7481 bp.uid = 0;
7482 bp.gids = null;
7483 }
7484 }
7485 }
7486 }
7487
7488 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007489 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007490 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007491 PackageSetting p = mPackages.get(name);
7492 if (p != null) {
7493 if (!p.codePath.equals(codePath)) {
7494 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007495 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007496 // This is an updated system app with versions in both system
7497 // and data partition. Just let the most recent version
7498 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007499 Log.w(TAG, "Trying to update system app code path from " +
7500 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007501 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007502 // Just a change in the code path is not an issue, but
7503 // let's log a message about it.
7504 Log.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007505 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007507 }
7508 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 reportSettingsProblem(Log.WARN,
7510 "Package " + name + " shared user changed from "
7511 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7512 + " to "
7513 + (sharedUser != null ? sharedUser.name : "<nothing>")
7514 + "; replacing with new");
7515 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007516 } else {
7517 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7518 // If what we are scanning is a system package, then
7519 // make it so, regardless of whether it was previously
7520 // installed only in the data partition.
7521 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 }
7524 }
7525 if (p == null) {
7526 // Create a new PackageSettings entry. this can end up here because
7527 // of code path mismatch or user id mismatch of an updated system partition
7528 if (!create) {
7529 return null;
7530 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007531 if (origPackage != null) {
7532 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007533 p = new PackageSetting(origPackage.name, name, codePath,
7534 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007535 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7536 + " is adopting original package " + origPackage.name);
7537 p.copyFrom(origPackage);
7538 p.sharedUser = origPackage.sharedUser;
7539 p.userId = origPackage.userId;
7540 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007541 mRenamedPackages.put(name, origPackage.name);
7542 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007543 // Update new package state.
7544 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007545 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007546 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007547 p.setTimeStamp(codePath.lastModified());
7548 p.sharedUser = sharedUser;
7549 if (sharedUser != null) {
7550 p.userId = sharedUser.userId;
7551 } else if (MULTIPLE_APPLICATION_UIDS) {
7552 // Clone the setting here for disabled system packages
7553 PackageSetting dis = mDisabledSysPackages.get(name);
7554 if (dis != null) {
7555 // For disabled packages a new setting is created
7556 // from the existing user id. This still has to be
7557 // added to list of user id's
7558 // Copy signatures from previous setting
7559 if (dis.signatures.mSignatures != null) {
7560 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7561 }
7562 p.userId = dis.userId;
7563 // Clone permissions
7564 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7565 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7566 // Clone component info
7567 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7568 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7569 // Add new setting to list of user ids
7570 addUserIdLP(p.userId, p, name);
7571 } else {
7572 // Assign new user id
7573 p.userId = newUserIdLP(p);
7574 }
7575 } else {
7576 p.userId = FIRST_APPLICATION_UID;
7577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007578 }
7579 if (p.userId < 0) {
7580 reportSettingsProblem(Log.WARN,
7581 "Package " + name + " could not be assigned a valid uid");
7582 return null;
7583 }
7584 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007585 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007587 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 }
7589 }
7590 return p;
7591 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007592
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007593 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007594 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007595 String codePath = pkg.applicationInfo.sourceDir;
7596 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007597 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007598 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007599 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007600 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007601 p.codePath = new File(codePath);
7602 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007603 }
7604 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007605 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007606 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007607 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007608 p.resourcePath = new File(resourcePath);
7609 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007610 }
7611 // Update version code if needed
7612 if (pkg.mVersionCode != p.versionCode) {
7613 p.versionCode = pkg.mVersionCode;
7614 }
7615 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7616 }
7617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007618 // Utility method that adds a PackageSetting to mPackages and
7619 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007620 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007621 SharedUserSetting sharedUser) {
7622 mPackages.put(name, p);
7623 if (sharedUser != null) {
7624 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7625 reportSettingsProblem(Log.ERROR,
7626 "Package " + p.name + " was user "
7627 + p.sharedUser + " but is now " + sharedUser
7628 + "; I am not changing its files so it will probably fail!");
7629 p.sharedUser.packages.remove(p);
7630 } else if (p.userId != sharedUser.userId) {
7631 reportSettingsProblem(Log.ERROR,
7632 "Package " + p.name + " was user id " + p.userId
7633 + " but is now user " + sharedUser
7634 + " with id " + sharedUser.userId
7635 + "; I am not changing its files so it will probably fail!");
7636 }
7637
7638 sharedUser.packages.add(p);
7639 p.sharedUser = sharedUser;
7640 p.userId = sharedUser.userId;
7641 }
7642 }
7643
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007644 /*
7645 * Update the shared user setting when a package using
7646 * specifying the shared user id is removed. The gids
7647 * associated with each permission of the deleted package
7648 * are removed from the shared user's gid list only if its
7649 * not in use by other permissions of packages in the
7650 * shared user setting.
7651 */
7652 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7654 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7655 return;
7656 }
7657 // No sharedUserId
7658 if (deletedPs.sharedUser == null) {
7659 return;
7660 }
7661 SharedUserSetting sus = deletedPs.sharedUser;
7662 // Update permissions
7663 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7664 boolean used = false;
7665 if (!sus.grantedPermissions.contains (eachPerm)) {
7666 continue;
7667 }
7668 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007669 if (pkg.pkg != null &&
7670 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7671 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007672 used = true;
7673 break;
7674 }
7675 }
7676 if (!used) {
7677 // can safely delete this permission from list
7678 sus.grantedPermissions.remove(eachPerm);
7679 sus.loadedPermissions.remove(eachPerm);
7680 }
7681 }
7682 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007683 int newGids[] = globalGids;
7684 for (String eachPerm : sus.grantedPermissions) {
7685 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007686 if (bp != null) {
7687 newGids = appendInts(newGids, bp.gids);
7688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 }
7690 sus.gids = newGids;
7691 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 private int removePackageLP(String name) {
7694 PackageSetting p = mPackages.get(name);
7695 if (p != null) {
7696 mPackages.remove(name);
7697 if (p.sharedUser != null) {
7698 p.sharedUser.packages.remove(p);
7699 if (p.sharedUser.packages.size() == 0) {
7700 mSharedUsers.remove(p.sharedUser.name);
7701 removeUserIdLP(p.sharedUser.userId);
7702 return p.sharedUser.userId;
7703 }
7704 } else {
7705 removeUserIdLP(p.userId);
7706 return p.userId;
7707 }
7708 }
7709 return -1;
7710 }
7711
7712 private boolean addUserIdLP(int uid, Object obj, Object name) {
7713 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7714 return false;
7715 }
7716
7717 if (uid >= FIRST_APPLICATION_UID) {
7718 int N = mUserIds.size();
7719 final int index = uid - FIRST_APPLICATION_UID;
7720 while (index >= N) {
7721 mUserIds.add(null);
7722 N++;
7723 }
7724 if (mUserIds.get(index) != null) {
7725 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007726 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727 + " name=" + name);
7728 return false;
7729 }
7730 mUserIds.set(index, obj);
7731 } else {
7732 if (mOtherUserIds.get(uid) != null) {
7733 reportSettingsProblem(Log.ERROR,
7734 "Adding duplicate shared id: " + uid
7735 + " name=" + name);
7736 return false;
7737 }
7738 mOtherUserIds.put(uid, obj);
7739 }
7740 return true;
7741 }
7742
7743 public Object getUserIdLP(int uid) {
7744 if (uid >= FIRST_APPLICATION_UID) {
7745 int N = mUserIds.size();
7746 final int index = uid - FIRST_APPLICATION_UID;
7747 return index < N ? mUserIds.get(index) : null;
7748 } else {
7749 return mOtherUserIds.get(uid);
7750 }
7751 }
7752
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007753 private Set<String> findPackagesWithFlag(int flag) {
7754 Set<String> ret = new HashSet<String>();
7755 for (PackageSetting ps : mPackages.values()) {
7756 // Has to match atleast all the flag bits set on flag
7757 if ((ps.pkgFlags & flag) == flag) {
7758 ret.add(ps.name);
7759 }
7760 }
7761 return ret;
7762 }
7763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 private void removeUserIdLP(int uid) {
7765 if (uid >= FIRST_APPLICATION_UID) {
7766 int N = mUserIds.size();
7767 final int index = uid - FIRST_APPLICATION_UID;
7768 if (index < N) mUserIds.set(index, null);
7769 } else {
7770 mOtherUserIds.remove(uid);
7771 }
7772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 void writeLP() {
7775 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7776
7777 // Keep the old settings around until we know the new ones have
7778 // been successfully written.
7779 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007780 // Presence of backup settings file indicates that we failed
7781 // to persist settings earlier. So preserve the older
7782 // backup for future reference since the current settings
7783 // might have been corrupted.
7784 if (!mBackupSettingsFilename.exists()) {
7785 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7786 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7787 return;
7788 }
7789 } else {
7790 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007792 }
7793
7794 mPastSignatures.clear();
7795
7796 try {
7797 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7798
7799 //XmlSerializer serializer = XmlUtils.serializerInstance();
7800 XmlSerializer serializer = new FastXmlSerializer();
7801 serializer.setOutput(str, "utf-8");
7802 serializer.startDocument(null, true);
7803 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7804
7805 serializer.startTag(null, "packages");
7806
7807 serializer.startTag(null, "permission-trees");
7808 for (BasePermission bp : mPermissionTrees.values()) {
7809 writePermission(serializer, bp);
7810 }
7811 serializer.endTag(null, "permission-trees");
7812
7813 serializer.startTag(null, "permissions");
7814 for (BasePermission bp : mPermissions.values()) {
7815 writePermission(serializer, bp);
7816 }
7817 serializer.endTag(null, "permissions");
7818
7819 for (PackageSetting pkg : mPackages.values()) {
7820 writePackage(serializer, pkg);
7821 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7824 writeDisabledSysPackage(serializer, pkg);
7825 }
7826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 serializer.startTag(null, "preferred-activities");
7828 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7829 serializer.startTag(null, "item");
7830 pa.writeToXml(serializer);
7831 serializer.endTag(null, "item");
7832 }
7833 serializer.endTag(null, "preferred-activities");
7834
7835 for (SharedUserSetting usr : mSharedUsers.values()) {
7836 serializer.startTag(null, "shared-user");
7837 serializer.attribute(null, "name", usr.name);
7838 serializer.attribute(null, "userId",
7839 Integer.toString(usr.userId));
7840 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7841 serializer.startTag(null, "perms");
7842 for (String name : usr.grantedPermissions) {
7843 serializer.startTag(null, "item");
7844 serializer.attribute(null, "name", name);
7845 serializer.endTag(null, "item");
7846 }
7847 serializer.endTag(null, "perms");
7848 serializer.endTag(null, "shared-user");
7849 }
7850
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007851 if (mPackagesToBeCleaned.size() > 0) {
7852 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7853 serializer.startTag(null, "cleaning-package");
7854 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7855 serializer.endTag(null, "cleaning-package");
7856 }
7857 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007858
7859 if (mRenamedPackages.size() > 0) {
7860 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
7861 serializer.startTag(null, "renamed-package");
7862 serializer.attribute(null, "new", e.getKey());
7863 serializer.attribute(null, "old", e.getValue());
7864 serializer.endTag(null, "renamed-package");
7865 }
7866 }
7867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007868 serializer.endTag(null, "packages");
7869
7870 serializer.endDocument();
7871
7872 str.flush();
7873 str.close();
7874
7875 // New settings successfully written, old ones are no longer
7876 // needed.
7877 mBackupSettingsFilename.delete();
7878 FileUtils.setPermissions(mSettingsFilename.toString(),
7879 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7880 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7881 |FileUtils.S_IROTH,
7882 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007883
7884 // Write package list file now, use a JournaledFile.
7885 //
7886 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
7887 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
7888
7889 str = new FileOutputStream(journal.chooseForWrite());
7890 try {
7891 StringBuilder sb = new StringBuilder();
7892 for (PackageSetting pkg : mPackages.values()) {
7893 ApplicationInfo ai = pkg.pkg.applicationInfo;
7894 String dataPath = ai.dataDir;
7895 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7896
7897 // Avoid any application that has a space in its path
7898 // or that is handled by the system.
7899 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
7900 continue;
7901
7902 // we store on each line the following information for now:
7903 //
7904 // pkgName - package name
7905 // userId - application-specific user id
7906 // debugFlag - 0 or 1 if the package is debuggable.
7907 // dataPath - path to package's data path
7908 //
7909 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
7910 //
7911 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
7912 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
7913 // system/core/run-as/run-as.c
7914 //
7915 sb.setLength(0);
7916 sb.append(ai.packageName);
7917 sb.append(" ");
7918 sb.append((int)ai.uid);
7919 sb.append(isDebug ? " 1 " : " 0 ");
7920 sb.append(dataPath);
7921 sb.append("\n");
7922 str.write(sb.toString().getBytes());
7923 }
7924 str.flush();
7925 str.close();
7926 journal.commit();
7927 }
7928 catch (Exception e) {
7929 journal.rollback();
7930 }
7931
7932 FileUtils.setPermissions(mPackageListFilename.toString(),
7933 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7934 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7935 |FileUtils.S_IROTH,
7936 -1, -1);
7937
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007938 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007939
7940 } catch(XmlPullParserException e) {
7941 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 -08007942 } catch(java.io.IOException e) {
7943 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 -08007944 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007945 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007946 if (mSettingsFilename.exists()) {
7947 if (!mSettingsFilename.delete()) {
7948 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7949 }
7950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007951 //Debug.stopMethodTracing();
7952 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007953
7954 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007955 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007956 serializer.startTag(null, "updated-package");
7957 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007958 if (pkg.realName != null) {
7959 serializer.attribute(null, "realName", pkg.realName);
7960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 serializer.attribute(null, "codePath", pkg.codePathString);
7962 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007963 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007964 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7965 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7966 }
7967 if (pkg.sharedUser == null) {
7968 serializer.attribute(null, "userId",
7969 Integer.toString(pkg.userId));
7970 } else {
7971 serializer.attribute(null, "sharedUserId",
7972 Integer.toString(pkg.userId));
7973 }
7974 serializer.startTag(null, "perms");
7975 if (pkg.sharedUser == null) {
7976 // If this is a shared user, the permissions will
7977 // be written there. We still need to write an
7978 // empty permissions list so permissionsFixed will
7979 // be set.
7980 for (final String name : pkg.grantedPermissions) {
7981 BasePermission bp = mPermissions.get(name);
7982 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7983 // We only need to write signature or system permissions but this wont
7984 // match the semantics of grantedPermissions. So write all permissions.
7985 serializer.startTag(null, "item");
7986 serializer.attribute(null, "name", name);
7987 serializer.endTag(null, "item");
7988 }
7989 }
7990 }
7991 serializer.endTag(null, "perms");
7992 serializer.endTag(null, "updated-package");
7993 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007994
7995 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007996 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 serializer.startTag(null, "package");
7998 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007999 if (pkg.realName != null) {
8000 serializer.attribute(null, "realName", pkg.realName);
8001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008002 serializer.attribute(null, "codePath", pkg.codePathString);
8003 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8004 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8005 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008006 serializer.attribute(null, "flags",
8007 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008008 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008009 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008010 if (pkg.sharedUser == null) {
8011 serializer.attribute(null, "userId",
8012 Integer.toString(pkg.userId));
8013 } else {
8014 serializer.attribute(null, "sharedUserId",
8015 Integer.toString(pkg.userId));
8016 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008017 if (pkg.uidError) {
8018 serializer.attribute(null, "uidError", "true");
8019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008020 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8021 serializer.attribute(null, "enabled",
8022 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8023 ? "true" : "false");
8024 }
8025 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8026 serializer.attribute(null, "installStatus", "false");
8027 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008028 if (pkg.installerPackageName != null) {
8029 serializer.attribute(null, "installer", pkg.installerPackageName);
8030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8032 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8033 serializer.startTag(null, "perms");
8034 if (pkg.sharedUser == null) {
8035 // If this is a shared user, the permissions will
8036 // be written there. We still need to write an
8037 // empty permissions list so permissionsFixed will
8038 // be set.
8039 for (final String name : pkg.grantedPermissions) {
8040 serializer.startTag(null, "item");
8041 serializer.attribute(null, "name", name);
8042 serializer.endTag(null, "item");
8043 }
8044 }
8045 serializer.endTag(null, "perms");
8046 }
8047 if (pkg.disabledComponents.size() > 0) {
8048 serializer.startTag(null, "disabled-components");
8049 for (final String name : pkg.disabledComponents) {
8050 serializer.startTag(null, "item");
8051 serializer.attribute(null, "name", name);
8052 serializer.endTag(null, "item");
8053 }
8054 serializer.endTag(null, "disabled-components");
8055 }
8056 if (pkg.enabledComponents.size() > 0) {
8057 serializer.startTag(null, "enabled-components");
8058 for (final String name : pkg.enabledComponents) {
8059 serializer.startTag(null, "item");
8060 serializer.attribute(null, "name", name);
8061 serializer.endTag(null, "item");
8062 }
8063 serializer.endTag(null, "enabled-components");
8064 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008066 serializer.endTag(null, "package");
8067 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008069 void writePermission(XmlSerializer serializer, BasePermission bp)
8070 throws XmlPullParserException, java.io.IOException {
8071 if (bp.type != BasePermission.TYPE_BUILTIN
8072 && bp.sourcePackage != null) {
8073 serializer.startTag(null, "item");
8074 serializer.attribute(null, "name", bp.name);
8075 serializer.attribute(null, "package", bp.sourcePackage);
8076 if (DEBUG_SETTINGS) Log.v(TAG,
8077 "Writing perm: name=" + bp.name + " type=" + bp.type);
8078 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8079 PermissionInfo pi = bp.perm != null ? bp.perm.info
8080 : bp.pendingInfo;
8081 if (pi != null) {
8082 serializer.attribute(null, "type", "dynamic");
8083 if (pi.icon != 0) {
8084 serializer.attribute(null, "icon",
8085 Integer.toString(pi.icon));
8086 }
8087 if (pi.nonLocalizedLabel != null) {
8088 serializer.attribute(null, "label",
8089 pi.nonLocalizedLabel.toString());
8090 }
8091 if (pi.protectionLevel !=
8092 PermissionInfo.PROTECTION_NORMAL) {
8093 serializer.attribute(null, "protection",
8094 Integer.toString(pi.protectionLevel));
8095 }
8096 }
8097 }
8098 serializer.endTag(null, "item");
8099 }
8100 }
8101
8102 String getReadMessagesLP() {
8103 return mReadMessages.toString();
8104 }
8105
Oscar Montemayora8529f62009-11-18 10:14:20 -08008106 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008107 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8108 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008109 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 while(its.hasNext()) {
8111 String key = its.next();
8112 PackageSetting ps = mPackages.get(key);
8113 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008114 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008115 }
8116 }
8117 return ret;
8118 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008120 boolean readLP() {
8121 FileInputStream str = null;
8122 if (mBackupSettingsFilename.exists()) {
8123 try {
8124 str = new FileInputStream(mBackupSettingsFilename);
8125 mReadMessages.append("Reading from backup settings file\n");
8126 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008127 if (mSettingsFilename.exists()) {
8128 // If both the backup and settings file exist, we
8129 // ignore the settings since it might have been
8130 // corrupted.
8131 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
8132 mSettingsFilename.delete();
8133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008134 } catch (java.io.IOException e) {
8135 // We'll try for the normal settings file.
8136 }
8137 }
8138
8139 mPastSignatures.clear();
8140
8141 try {
8142 if (str == null) {
8143 if (!mSettingsFilename.exists()) {
8144 mReadMessages.append("No settings file found\n");
8145 Log.i(TAG, "No current settings file!");
8146 return false;
8147 }
8148 str = new FileInputStream(mSettingsFilename);
8149 }
8150 XmlPullParser parser = Xml.newPullParser();
8151 parser.setInput(str, null);
8152
8153 int type;
8154 while ((type=parser.next()) != XmlPullParser.START_TAG
8155 && type != XmlPullParser.END_DOCUMENT) {
8156 ;
8157 }
8158
8159 if (type != XmlPullParser.START_TAG) {
8160 mReadMessages.append("No start tag found in settings file\n");
8161 Log.e(TAG, "No start tag found in package manager settings");
8162 return false;
8163 }
8164
8165 int outerDepth = parser.getDepth();
8166 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8167 && (type != XmlPullParser.END_TAG
8168 || parser.getDepth() > outerDepth)) {
8169 if (type == XmlPullParser.END_TAG
8170 || type == XmlPullParser.TEXT) {
8171 continue;
8172 }
8173
8174 String tagName = parser.getName();
8175 if (tagName.equals("package")) {
8176 readPackageLP(parser);
8177 } else if (tagName.equals("permissions")) {
8178 readPermissionsLP(mPermissions, parser);
8179 } else if (tagName.equals("permission-trees")) {
8180 readPermissionsLP(mPermissionTrees, parser);
8181 } else if (tagName.equals("shared-user")) {
8182 readSharedUserLP(parser);
8183 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008184 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 } else if (tagName.equals("preferred-activities")) {
8186 readPreferredActivitiesLP(parser);
8187 } else if(tagName.equals("updated-package")) {
8188 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008189 } else if (tagName.equals("cleaning-package")) {
8190 String name = parser.getAttributeValue(null, "name");
8191 if (name != null) {
8192 mPackagesToBeCleaned.add(name);
8193 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008194 } else if (tagName.equals("renamed-package")) {
8195 String nname = parser.getAttributeValue(null, "new");
8196 String oname = parser.getAttributeValue(null, "old");
8197 if (nname != null && oname != null) {
8198 mRenamedPackages.put(nname, oname);
8199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 } else {
8201 Log.w(TAG, "Unknown element under <packages>: "
8202 + parser.getName());
8203 XmlUtils.skipCurrentTag(parser);
8204 }
8205 }
8206
8207 str.close();
8208
8209 } catch(XmlPullParserException e) {
8210 mReadMessages.append("Error reading: " + e.toString());
8211 Log.e(TAG, "Error reading package manager settings", e);
8212
8213 } catch(java.io.IOException e) {
8214 mReadMessages.append("Error reading: " + e.toString());
8215 Log.e(TAG, "Error reading package manager settings", e);
8216
8217 }
8218
8219 int N = mPendingPackages.size();
8220 for (int i=0; i<N; i++) {
8221 final PendingPackage pp = mPendingPackages.get(i);
8222 Object idObj = getUserIdLP(pp.sharedId);
8223 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008224 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008226 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008227 if (p == null) {
8228 Log.w(TAG, "Unable to create application package for "
8229 + pp.name);
8230 continue;
8231 }
8232 p.copyFrom(pp);
8233 } else if (idObj != null) {
8234 String msg = "Bad package setting: package " + pp.name
8235 + " has shared uid " + pp.sharedId
8236 + " that is not a shared uid\n";
8237 mReadMessages.append(msg);
8238 Log.e(TAG, msg);
8239 } else {
8240 String msg = "Bad package setting: package " + pp.name
8241 + " has shared uid " + pp.sharedId
8242 + " that is not defined\n";
8243 mReadMessages.append(msg);
8244 Log.e(TAG, msg);
8245 }
8246 }
8247 mPendingPackages.clear();
8248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008249 mReadMessages.append("Read completed successfully: "
8250 + mPackages.size() + " packages, "
8251 + mSharedUsers.size() + " shared uids\n");
8252
8253 return true;
8254 }
8255
8256 private int readInt(XmlPullParser parser, String ns, String name,
8257 int defValue) {
8258 String v = parser.getAttributeValue(ns, name);
8259 try {
8260 if (v == null) {
8261 return defValue;
8262 }
8263 return Integer.parseInt(v);
8264 } catch (NumberFormatException e) {
8265 reportSettingsProblem(Log.WARN,
8266 "Error in package manager settings: attribute " +
8267 name + " has bad integer value " + v + " at "
8268 + parser.getPositionDescription());
8269 }
8270 return defValue;
8271 }
8272
8273 private void readPermissionsLP(HashMap<String, BasePermission> out,
8274 XmlPullParser parser)
8275 throws IOException, XmlPullParserException {
8276 int outerDepth = parser.getDepth();
8277 int type;
8278 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8279 && (type != XmlPullParser.END_TAG
8280 || parser.getDepth() > outerDepth)) {
8281 if (type == XmlPullParser.END_TAG
8282 || type == XmlPullParser.TEXT) {
8283 continue;
8284 }
8285
8286 String tagName = parser.getName();
8287 if (tagName.equals("item")) {
8288 String name = parser.getAttributeValue(null, "name");
8289 String sourcePackage = parser.getAttributeValue(null, "package");
8290 String ptype = parser.getAttributeValue(null, "type");
8291 if (name != null && sourcePackage != null) {
8292 boolean dynamic = "dynamic".equals(ptype);
8293 BasePermission bp = new BasePermission(name, sourcePackage,
8294 dynamic
8295 ? BasePermission.TYPE_DYNAMIC
8296 : BasePermission.TYPE_NORMAL);
8297 if (dynamic) {
8298 PermissionInfo pi = new PermissionInfo();
8299 pi.packageName = sourcePackage.intern();
8300 pi.name = name.intern();
8301 pi.icon = readInt(parser, null, "icon", 0);
8302 pi.nonLocalizedLabel = parser.getAttributeValue(
8303 null, "label");
8304 pi.protectionLevel = readInt(parser, null, "protection",
8305 PermissionInfo.PROTECTION_NORMAL);
8306 bp.pendingInfo = pi;
8307 }
8308 out.put(bp.name, bp);
8309 } else {
8310 reportSettingsProblem(Log.WARN,
8311 "Error in package manager settings: permissions has"
8312 + " no name at " + parser.getPositionDescription());
8313 }
8314 } else {
8315 reportSettingsProblem(Log.WARN,
8316 "Unknown element reading permissions: "
8317 + parser.getName() + " at "
8318 + parser.getPositionDescription());
8319 }
8320 XmlUtils.skipCurrentTag(parser);
8321 }
8322 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008324 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008325 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008326 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008327 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008328 String codePathStr = parser.getAttributeValue(null, "codePath");
8329 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008330 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 resourcePathStr = codePathStr;
8332 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008333 String version = parser.getAttributeValue(null, "version");
8334 int versionCode = 0;
8335 if (version != null) {
8336 try {
8337 versionCode = Integer.parseInt(version);
8338 } catch (NumberFormatException e) {
8339 }
8340 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008342 int pkgFlags = 0;
8343 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008344 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008345 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008346 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008347 String timeStampStr = parser.getAttributeValue(null, "ts");
8348 if (timeStampStr != null) {
8349 try {
8350 long timeStamp = Long.parseLong(timeStampStr);
8351 ps.setTimeStamp(timeStamp, timeStampStr);
8352 } catch (NumberFormatException e) {
8353 }
8354 }
8355 String idStr = parser.getAttributeValue(null, "userId");
8356 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8357 if(ps.userId <= 0) {
8358 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8359 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8360 }
8361 int outerDepth = parser.getDepth();
8362 int type;
8363 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8364 && (type != XmlPullParser.END_TAG
8365 || parser.getDepth() > outerDepth)) {
8366 if (type == XmlPullParser.END_TAG
8367 || type == XmlPullParser.TEXT) {
8368 continue;
8369 }
8370
8371 String tagName = parser.getName();
8372 if (tagName.equals("perms")) {
8373 readGrantedPermissionsLP(parser,
8374 ps.grantedPermissions);
8375 } else {
8376 reportSettingsProblem(Log.WARN,
8377 "Unknown element under <updated-package>: "
8378 + parser.getName());
8379 XmlUtils.skipCurrentTag(parser);
8380 }
8381 }
8382 mDisabledSysPackages.put(name, ps);
8383 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008385 private void readPackageLP(XmlPullParser parser)
8386 throws XmlPullParserException, IOException {
8387 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008388 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008389 String idStr = null;
8390 String sharedIdStr = null;
8391 String codePathStr = null;
8392 String resourcePathStr = null;
8393 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008394 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008395 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008396 int pkgFlags = 0;
8397 String timeStampStr;
8398 long timeStamp = 0;
8399 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008400 String version = null;
8401 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008402 try {
8403 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008404 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008405 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008406 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008407 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8408 codePathStr = parser.getAttributeValue(null, "codePath");
8409 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008410 version = parser.getAttributeValue(null, "version");
8411 if (version != null) {
8412 try {
8413 versionCode = Integer.parseInt(version);
8414 } catch (NumberFormatException e) {
8415 }
8416 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008417 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008418
8419 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008420 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008421 try {
8422 pkgFlags = Integer.parseInt(systemStr);
8423 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008424 }
8425 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008426 // For backward compatibility
8427 systemStr = parser.getAttributeValue(null, "system");
8428 if (systemStr != null) {
8429 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8430 } else {
8431 // Old settings that don't specify system... just treat
8432 // them as system, good enough.
8433 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008435 }
8436 timeStampStr = parser.getAttributeValue(null, "ts");
8437 if (timeStampStr != null) {
8438 try {
8439 timeStamp = Long.parseLong(timeStampStr);
8440 } catch (NumberFormatException e) {
8441 }
8442 }
8443 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8444 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8445 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8446 if (resourcePathStr == null) {
8447 resourcePathStr = codePathStr;
8448 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008449 if (realName != null) {
8450 realName = realName.intern();
8451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008452 if (name == null) {
8453 reportSettingsProblem(Log.WARN,
8454 "Error in package manager settings: <package> has no name at "
8455 + parser.getPositionDescription());
8456 } else if (codePathStr == null) {
8457 reportSettingsProblem(Log.WARN,
8458 "Error in package manager settings: <package> has no codePath at "
8459 + parser.getPositionDescription());
8460 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008461 packageSetting = addPackageLP(name.intern(), realName,
8462 new File(codePathStr), new File(resourcePathStr),
8463 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8465 + ": userId=" + userId + " pkg=" + packageSetting);
8466 if (packageSetting == null) {
8467 reportSettingsProblem(Log.ERROR,
8468 "Failure adding uid " + userId
8469 + " while parsing settings at "
8470 + parser.getPositionDescription());
8471 } else {
8472 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8473 }
8474 } else if (sharedIdStr != null) {
8475 userId = sharedIdStr != null
8476 ? Integer.parseInt(sharedIdStr) : 0;
8477 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008478 packageSetting = new PendingPackage(name.intern(), realName,
8479 new File(codePathStr), new File(resourcePathStr),
8480 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8482 mPendingPackages.add((PendingPackage) packageSetting);
8483 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8484 + ": sharedUserId=" + userId + " pkg="
8485 + packageSetting);
8486 } else {
8487 reportSettingsProblem(Log.WARN,
8488 "Error in package manager settings: package "
8489 + name + " has bad sharedId " + sharedIdStr
8490 + " at " + parser.getPositionDescription());
8491 }
8492 } else {
8493 reportSettingsProblem(Log.WARN,
8494 "Error in package manager settings: package "
8495 + name + " has bad userId " + idStr + " at "
8496 + parser.getPositionDescription());
8497 }
8498 } catch (NumberFormatException e) {
8499 reportSettingsProblem(Log.WARN,
8500 "Error in package manager settings: package "
8501 + name + " has bad userId " + idStr + " at "
8502 + parser.getPositionDescription());
8503 }
8504 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008505 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008506 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008507 final String enabledStr = parser.getAttributeValue(null, "enabled");
8508 if (enabledStr != null) {
8509 if (enabledStr.equalsIgnoreCase("true")) {
8510 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8511 } else if (enabledStr.equalsIgnoreCase("false")) {
8512 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8513 } else if (enabledStr.equalsIgnoreCase("default")) {
8514 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8515 } else {
8516 reportSettingsProblem(Log.WARN,
8517 "Error in package manager settings: package "
8518 + name + " has bad enabled value: " + idStr
8519 + " at " + parser.getPositionDescription());
8520 }
8521 } else {
8522 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8523 }
8524 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8525 if (installStatusStr != null) {
8526 if (installStatusStr.equalsIgnoreCase("false")) {
8527 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8528 } else {
8529 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8530 }
8531 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 int outerDepth = parser.getDepth();
8534 int type;
8535 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8536 && (type != XmlPullParser.END_TAG
8537 || parser.getDepth() > outerDepth)) {
8538 if (type == XmlPullParser.END_TAG
8539 || type == XmlPullParser.TEXT) {
8540 continue;
8541 }
8542
8543 String tagName = parser.getName();
8544 if (tagName.equals("disabled-components")) {
8545 readDisabledComponentsLP(packageSetting, parser);
8546 } else if (tagName.equals("enabled-components")) {
8547 readEnabledComponentsLP(packageSetting, parser);
8548 } else if (tagName.equals("sigs")) {
8549 packageSetting.signatures.readXml(parser, mPastSignatures);
8550 } else if (tagName.equals("perms")) {
8551 readGrantedPermissionsLP(parser,
8552 packageSetting.loadedPermissions);
8553 packageSetting.permissionsFixed = true;
8554 } else {
8555 reportSettingsProblem(Log.WARN,
8556 "Unknown element under <package>: "
8557 + parser.getName());
8558 XmlUtils.skipCurrentTag(parser);
8559 }
8560 }
8561 } else {
8562 XmlUtils.skipCurrentTag(parser);
8563 }
8564 }
8565
8566 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8567 XmlPullParser parser)
8568 throws IOException, XmlPullParserException {
8569 int outerDepth = parser.getDepth();
8570 int type;
8571 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8572 && (type != XmlPullParser.END_TAG
8573 || parser.getDepth() > outerDepth)) {
8574 if (type == XmlPullParser.END_TAG
8575 || type == XmlPullParser.TEXT) {
8576 continue;
8577 }
8578
8579 String tagName = parser.getName();
8580 if (tagName.equals("item")) {
8581 String name = parser.getAttributeValue(null, "name");
8582 if (name != null) {
8583 packageSetting.disabledComponents.add(name.intern());
8584 } else {
8585 reportSettingsProblem(Log.WARN,
8586 "Error in package manager settings: <disabled-components> has"
8587 + " no name at " + parser.getPositionDescription());
8588 }
8589 } else {
8590 reportSettingsProblem(Log.WARN,
8591 "Unknown element under <disabled-components>: "
8592 + parser.getName());
8593 }
8594 XmlUtils.skipCurrentTag(parser);
8595 }
8596 }
8597
8598 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8599 XmlPullParser parser)
8600 throws IOException, XmlPullParserException {
8601 int outerDepth = parser.getDepth();
8602 int type;
8603 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8604 && (type != XmlPullParser.END_TAG
8605 || parser.getDepth() > outerDepth)) {
8606 if (type == XmlPullParser.END_TAG
8607 || type == XmlPullParser.TEXT) {
8608 continue;
8609 }
8610
8611 String tagName = parser.getName();
8612 if (tagName.equals("item")) {
8613 String name = parser.getAttributeValue(null, "name");
8614 if (name != null) {
8615 packageSetting.enabledComponents.add(name.intern());
8616 } else {
8617 reportSettingsProblem(Log.WARN,
8618 "Error in package manager settings: <enabled-components> has"
8619 + " no name at " + parser.getPositionDescription());
8620 }
8621 } else {
8622 reportSettingsProblem(Log.WARN,
8623 "Unknown element under <enabled-components>: "
8624 + parser.getName());
8625 }
8626 XmlUtils.skipCurrentTag(parser);
8627 }
8628 }
8629
8630 private void readSharedUserLP(XmlPullParser parser)
8631 throws XmlPullParserException, IOException {
8632 String name = null;
8633 String idStr = null;
8634 int pkgFlags = 0;
8635 SharedUserSetting su = null;
8636 try {
8637 name = parser.getAttributeValue(null, "name");
8638 idStr = parser.getAttributeValue(null, "userId");
8639 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8640 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8641 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8642 }
8643 if (name == null) {
8644 reportSettingsProblem(Log.WARN,
8645 "Error in package manager settings: <shared-user> has no name at "
8646 + parser.getPositionDescription());
8647 } else if (userId == 0) {
8648 reportSettingsProblem(Log.WARN,
8649 "Error in package manager settings: shared-user "
8650 + name + " has bad userId " + idStr + " at "
8651 + parser.getPositionDescription());
8652 } else {
8653 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8654 reportSettingsProblem(Log.ERROR,
8655 "Occurred while parsing settings at "
8656 + parser.getPositionDescription());
8657 }
8658 }
8659 } catch (NumberFormatException e) {
8660 reportSettingsProblem(Log.WARN,
8661 "Error in package manager settings: package "
8662 + name + " has bad userId " + idStr + " at "
8663 + parser.getPositionDescription());
8664 };
8665
8666 if (su != null) {
8667 int outerDepth = parser.getDepth();
8668 int type;
8669 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8670 && (type != XmlPullParser.END_TAG
8671 || parser.getDepth() > outerDepth)) {
8672 if (type == XmlPullParser.END_TAG
8673 || type == XmlPullParser.TEXT) {
8674 continue;
8675 }
8676
8677 String tagName = parser.getName();
8678 if (tagName.equals("sigs")) {
8679 su.signatures.readXml(parser, mPastSignatures);
8680 } else if (tagName.equals("perms")) {
8681 readGrantedPermissionsLP(parser, su.loadedPermissions);
8682 } else {
8683 reportSettingsProblem(Log.WARN,
8684 "Unknown element under <shared-user>: "
8685 + parser.getName());
8686 XmlUtils.skipCurrentTag(parser);
8687 }
8688 }
8689
8690 } else {
8691 XmlUtils.skipCurrentTag(parser);
8692 }
8693 }
8694
8695 private void readGrantedPermissionsLP(XmlPullParser parser,
8696 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8697 int outerDepth = parser.getDepth();
8698 int type;
8699 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8700 && (type != XmlPullParser.END_TAG
8701 || parser.getDepth() > outerDepth)) {
8702 if (type == XmlPullParser.END_TAG
8703 || type == XmlPullParser.TEXT) {
8704 continue;
8705 }
8706
8707 String tagName = parser.getName();
8708 if (tagName.equals("item")) {
8709 String name = parser.getAttributeValue(null, "name");
8710 if (name != null) {
8711 outPerms.add(name.intern());
8712 } else {
8713 reportSettingsProblem(Log.WARN,
8714 "Error in package manager settings: <perms> has"
8715 + " no name at " + parser.getPositionDescription());
8716 }
8717 } else {
8718 reportSettingsProblem(Log.WARN,
8719 "Unknown element under <perms>: "
8720 + parser.getName());
8721 }
8722 XmlUtils.skipCurrentTag(parser);
8723 }
8724 }
8725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008726 private void readPreferredActivitiesLP(XmlPullParser parser)
8727 throws XmlPullParserException, IOException {
8728 int outerDepth = parser.getDepth();
8729 int type;
8730 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8731 && (type != XmlPullParser.END_TAG
8732 || parser.getDepth() > outerDepth)) {
8733 if (type == XmlPullParser.END_TAG
8734 || type == XmlPullParser.TEXT) {
8735 continue;
8736 }
8737
8738 String tagName = parser.getName();
8739 if (tagName.equals("item")) {
8740 PreferredActivity pa = new PreferredActivity(parser);
8741 if (pa.mParseError == null) {
8742 mPreferredActivities.addFilter(pa);
8743 } else {
8744 reportSettingsProblem(Log.WARN,
8745 "Error in package manager settings: <preferred-activity> "
8746 + pa.mParseError + " at "
8747 + parser.getPositionDescription());
8748 }
8749 } else {
8750 reportSettingsProblem(Log.WARN,
8751 "Unknown element under <preferred-activities>: "
8752 + parser.getName());
8753 XmlUtils.skipCurrentTag(parser);
8754 }
8755 }
8756 }
8757
8758 // Returns -1 if we could not find an available UserId to assign
8759 private int newUserIdLP(Object obj) {
8760 // Let's be stupidly inefficient for now...
8761 final int N = mUserIds.size();
8762 for (int i=0; i<N; i++) {
8763 if (mUserIds.get(i) == null) {
8764 mUserIds.set(i, obj);
8765 return FIRST_APPLICATION_UID + i;
8766 }
8767 }
8768
8769 // None left?
8770 if (N >= MAX_APPLICATION_UIDS) {
8771 return -1;
8772 }
8773
8774 mUserIds.add(obj);
8775 return FIRST_APPLICATION_UID + N;
8776 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778 public PackageSetting getDisabledSystemPkg(String name) {
8779 synchronized(mPackages) {
8780 PackageSetting ps = mDisabledSysPackages.get(name);
8781 return ps;
8782 }
8783 }
8784
8785 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8786 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8787 if (Config.LOGV) {
8788 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8789 + " componentName = " + componentInfo.name);
8790 Log.v(TAG, "enabledComponents: "
8791 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8792 Log.v(TAG, "disabledComponents: "
8793 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8794 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008795 if (packageSettings == null) {
8796 if (false) {
8797 Log.w(TAG, "WAITING FOR DEBUGGER");
8798 Debug.waitForDebugger();
8799 Log.i(TAG, "We will crash!");
8800 }
8801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008802 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8803 || ((componentInfo.enabled
8804 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8805 || (componentInfo.applicationInfo.enabled
8806 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8807 && !packageSettings.disabledComponents.contains(componentInfo.name))
8808 || packageSettings.enabledComponents.contains(componentInfo.name));
8809 }
8810 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008811
8812 // ------- apps on sdcard specific code -------
8813 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008814 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008815 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008816 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008817 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008818
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008819 private String getEncryptKey() {
8820 try {
8821 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8822 if (sdEncKey == null) {
8823 sdEncKey = SystemKeyStore.getInstance().
8824 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8825 if (sdEncKey == null) {
8826 Log.e(TAG, "Failed to create encryption keys");
8827 return null;
8828 }
8829 }
8830 return sdEncKey;
8831 } catch (NoSuchAlgorithmException nsae) {
8832 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8833 return null;
8834 }
8835 }
8836
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008837 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008838 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008839 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008840 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008841 if (list != null) {
8842 int idx = 0;
8843 int idList[] = new int[MAX_CONTAINERS];
8844 boolean neverFound = true;
8845 for (String name : list) {
8846 // Ignore null entries
8847 if (name == null) {
8848 continue;
8849 }
8850 int sidx = name.indexOf(prefix);
8851 if (sidx == -1) {
8852 // Not a temp file. just ignore
8853 continue;
8854 }
8855 String subStr = name.substring(sidx + prefix.length());
8856 idList[idx] = -1;
8857 if (subStr != null) {
8858 try {
8859 int cid = Integer.parseInt(subStr);
8860 idList[idx++] = cid;
8861 neverFound = false;
8862 } catch (NumberFormatException e) {
8863 }
8864 }
8865 }
8866 if (!neverFound) {
8867 // Sort idList
8868 Arrays.sort(idList);
8869 for (int j = 1; j <= idList.length; j++) {
8870 if (idList[j-1] != j) {
8871 tmpIdx = j;
8872 break;
8873 }
8874 }
8875 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008876 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008877 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008878 }
8879
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08008880 /*
8881 * Return true if PackageManager does have packages to be updated.
8882 */
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008883 public boolean updateExternalMediaStatus(final boolean mediaStatus) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008884 synchronized (mPackages) {
8885 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8886 mediaStatus+", mMediaMounted=" + mMediaMounted);
8887 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008888 return false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008889 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008890 mMediaMounted = mediaStatus;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08008891 boolean ret = false;
8892 synchronized (mPackages) {
8893 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8894 ret = appList != null && appList.size() > 0;
8895 }
8896 if (!ret) {
8897 // No packages will be effected by the sdcard update. Just return.
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008898 return false;
8899 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008900 // Queue up an async operation since the package installation may take a little while.
8901 mHandler.post(new Runnable() {
8902 public void run() {
8903 mHandler.removeCallbacks(this);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08008904 // If we are up here that means there are packages to be
8905 // enabled or disabled.
8906 final HashMap<SdInstallArgs, String> processCids =
8907 new HashMap<SdInstallArgs, String>();
8908 final int[] uidArr = getExternalMediaPackages(mediaStatus, processCids);
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008909 if (mediaStatus) {
8910 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
8911 loadMediaPackages(processCids, uidArr);
8912 startCleaningPackages();
8913 } else {
8914 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
8915 unloadMediaPackages(processCids, uidArr);
8916 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008917 }
8918 });
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008919 return true;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008920 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008921 }
8922
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008923 private int[] getExternalMediaPackages(boolean mediaStatus,
8924 Map<SdInstallArgs, String> processCids) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008925 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008926 if (list == null || list.length == 0) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008927 return null;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008928 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008929
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008930 int uidList[] = new int[list.length];
8931 int num = 0;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008932 synchronized (mPackages) {
8933 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8934 for (String cid : list) {
8935 SdInstallArgs args = new SdInstallArgs(cid);
8936 String removeEntry = null;
8937 for (String app : appList) {
8938 if (args.matchContainer(app)) {
8939 removeEntry = app;
8940 break;
8941 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008942 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008943 if (removeEntry == null) {
8944 // No matching app on device. Skip entry or may be cleanup?
8945 // Ignore default package
8946 continue;
8947 }
8948 appList.remove(removeEntry);
8949 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8950 processCids.put(args, ps.codePathString);
8951 int uid = ps.userId;
8952 if (uid != -1) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008953 uidList[num++] = uid;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008954 }
8955 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008956 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008957 int uidArr[] = null;
8958 if (num > 0) {
8959 // Sort uid list
8960 Arrays.sort(uidList, 0, num);
8961 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008962 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008963 uidArr[0] = uidList[0];
8964 int di = 0;
8965 for (int i = 1; i < num; i++) {
8966 if (uidList[i-1] != uidList[i]) {
8967 uidArr[di++] = uidList[i];
8968 }
8969 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008970 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008971 return uidArr;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008972 }
8973
8974 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8975 ArrayList<String> pkgList, int uidArr[]) {
8976 int size = pkgList.size();
8977 if (size > 0) {
8978 // Send broadcasts here
8979 Bundle extras = new Bundle();
8980 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8981 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008982 if (uidArr != null) {
8983 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8984 }
8985 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8986 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008987 sendPackageBroadcast(action, null, extras);
8988 }
8989 }
8990
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008991 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008992 ArrayList<String> pkgList = new ArrayList<String>();
8993 Set<SdInstallArgs> keys = processCids.keySet();
8994 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008995 String codePath = processCids.get(args);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008996 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install pkg : "
8997 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008998 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008999 Log.e(TAG, "Failed to install package: " + codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009000 continue;
9001 }
9002 // Parse package
9003 int parseFlags = PackageParser.PARSE_CHATTY |
9004 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9005 PackageParser pp = new PackageParser(codePath);
9006 pp.setSeparateProcesses(mSeparateProcesses);
9007 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9008 codePath, mMetrics, parseFlags);
9009 if (pkg == null) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009010 Log.e(TAG, "Trying to install pkg : "
9011 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009012 continue;
9013 }
9014 setApplicationInfoPaths(pkg, codePath, codePath);
9015 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9016 synchronized (mInstallLock) {
9017 // Scan the package
9018 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9019 synchronized (mPackages) {
9020 // Grant permissions
9021 grantPermissionsLP(pkg, false);
9022 // Persist settings
9023 mSettings.writeLP();
9024 retCode = PackageManager.INSTALL_SUCCEEDED;
9025 pkgList.add(pkg.packageName);
9026 }
9027 } else {
9028 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
9029 }
9030 }
9031 args.doPostInstall(retCode);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009032 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009033 // Send a broadcast to let everyone know we are done processing
9034 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009035 if (pkgList.size() > 0) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009036 Runtime.getRuntime().gc();
9037 // If something failed do we clean up here or next install?
9038 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009039 }
9040
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009041 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009042 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009043 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009044 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009045 Set<SdInstallArgs> keys = processCids.keySet();
9046 for (SdInstallArgs args : keys) {
9047 String cid = args.cid;
9048 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009049 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009050 // Delete package internally
9051 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9052 synchronized (mInstallLock) {
9053 boolean res = deletePackageLI(pkgName, false,
9054 PackageManager.DONT_DELETE_DATA, outInfo);
9055 if (res) {
9056 pkgList.add(pkgName);
9057 } else {
9058 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009059 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009060 }
9061 }
9062 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009063 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009064 // Send broadcasts
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009065 if (pkgList.size() > 0) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009066 Runtime.getRuntime().gc();
9067 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009068 // Do clean up. Just unmount
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009069 for (SdInstallArgs args : failedList) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009070 synchronized (mInstallLock) {
9071 args.doPostDeleteLI(false);
9072 }
9073 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009074 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009075
9076 public void movePackage(final String packageName,
9077 final IPackageMoveObserver observer, final int flags) {
9078 if (packageName == null) {
9079 return;
9080 }
9081 mContext.enforceCallingOrSelfPermission(
9082 android.Manifest.permission.MOVE_PACKAGE, null);
9083 int returnCode = PackageManager.MOVE_SUCCEEDED;
9084 int currFlags = 0;
9085 int newFlags = 0;
9086 synchronized (mPackages) {
9087 PackageParser.Package pkg = mPackages.get(packageName);
9088 if (pkg == null) {
9089 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9090 }
9091 // Disable moving fwd locked apps and system packages
9092 if (pkg.applicationInfo != null &&
9093 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9094 Log.w(TAG, "Cannot move system application");
9095 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9096 } else if (pkg.applicationInfo != null &&
9097 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9098 Log.w(TAG, "Cannot move forward locked app.");
9099 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9100 } else {
9101 // Find install location first
9102 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9103 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9104 Log.w(TAG, "Ambigous flags specified for move location.");
9105 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9106 } else {
9107 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9108 PackageManager.INSTALL_EXTERNAL : 0;
9109 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0 ?
9110 PackageManager.INSTALL_EXTERNAL : 0;
9111 if (newFlags == currFlags) {
9112 Log.w(TAG, "No move required. Trying to move to same location");
9113 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9114 }
9115 }
9116 }
9117 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9118 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9119 } else {
9120 Message msg = mHandler.obtainMessage(INIT_COPY);
9121 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9122 pkg.applicationInfo.publicSourceDir);
9123 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9124 packageName);
9125 msg.obj = mp;
9126 mHandler.sendMessage(msg);
9127 }
9128 }
9129 }
9130
9131 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9132 // Queue up an async operation since the package deletion may take a little while.
9133 mHandler.post(new Runnable() {
9134 public void run() {
9135 mHandler.removeCallbacks(this);
9136 int returnCode = currentStatus;
9137 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9138 if (moveSucceeded) {
9139 int uid = -1;
9140 synchronized (mPackages) {
9141 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9142 }
9143 ArrayList<String> pkgList = new ArrayList<String>();
9144 pkgList.add(mp.packageName);
9145 int uidArr[] = new int[] { uid };
9146 // Send resources unavailable broadcast
9147 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9148
9149 // Update package code and resource paths
9150 synchronized (mPackages) {
9151 PackageParser.Package pkg = mPackages.get(mp.packageName);
9152 if (pkg != null) {
9153 String oldCodePath = pkg.mPath;
9154 String newCodePath = mp.targetArgs.getCodePath();
9155 String newResPath = mp.targetArgs.getResourcePath();
9156 pkg.mPath = newCodePath;
9157 // Move dex files around
9158 if (moveDexFiles(pkg)
9159 != PackageManager.INSTALL_SUCCEEDED) {
9160 // Moving of dex files failed. Set
9161 // error code and abort move.
9162 pkg.mPath = pkg.mScanPath;
9163 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9164 moveSucceeded = false;
9165 } else {
9166 pkg.mScanPath = newCodePath;
9167 pkg.applicationInfo.sourceDir = newCodePath;
9168 pkg.applicationInfo.publicSourceDir = newResPath;
9169 PackageSetting ps = (PackageSetting) pkg.mExtras;
9170 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9171 ps.codePathString = ps.codePath.getPath();
9172 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9173 ps.resourcePathString = ps.resourcePath.getPath();
9174 // Set the application info flag correctly.
9175 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9176 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_ON_SDCARD;
9177 } else {
9178 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_ON_SDCARD;
9179 }
9180 ps.setFlags(pkg.applicationInfo.flags);
9181 mAppDirs.remove(oldCodePath);
9182 mAppDirs.put(newCodePath, pkg);
9183 // Persist settings
9184 mSettings.writeLP();
9185 }
9186 }
9187 }
9188 if (moveSucceeded) {
9189 // Delete older code
9190 synchronized (mInstallLock) {
9191 mp.srcArgs.cleanUpResourcesLI();
9192 }
9193 // Send resources available broadcast
9194 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9195 Runtime.getRuntime().gc();
9196 }
9197 }
9198 if (!moveSucceeded){
9199 // Clean up failed installation
9200 if (mp.targetArgs != null) {
9201 mp.targetArgs.doPostInstall(
9202 PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
9203 }
9204 }
9205 IPackageMoveObserver observer = mp.observer;
9206 if (observer != null) {
9207 try {
9208 observer.packageMoved(mp.packageName, returnCode);
9209 } catch (RemoteException e) {
9210 Log.i(TAG, "Observer no longer exists.");
9211 }
9212 }
9213 }
9214 });
9215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009216}