blob: 9e11546d5f7d18188888f8f03af0e8716158ff02 [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;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.DevicePolicyManager;
33import android.app.admin.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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.pm.PackageParser;
60import android.content.pm.PermissionInfo;
61import android.content.pm.PermissionGroupInfo;
62import android.content.pm.ProviderInfo;
63import android.content.pm.ResolveInfo;
64import android.content.pm.ServiceInfo;
65import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.Uri;
67import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070068import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080070import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080072import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070073import android.os.Looper;
74import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Parcel;
76import android.os.RemoteException;
77import android.os.Environment;
78import android.os.FileObserver;
79import android.os.FileUtils;
80import android.os.Handler;
San Mehatb1043402010-02-05 08:26:50 -080081import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.ParcelFileDescriptor;
83import android.os.Process;
84import android.os.ServiceManager;
85import android.os.SystemClock;
86import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080087import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.util.*;
89import android.view.Display;
90import android.view.WindowManager;
91
92import java.io.File;
93import java.io.FileDescriptor;
94import java.io.FileInputStream;
95import java.io.FileNotFoundException;
96import java.io.FileOutputStream;
97import java.io.FileReader;
98import java.io.FilenameFilter;
99import java.io.IOException;
100import java.io.InputStream;
101import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800102import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800103import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import java.util.ArrayList;
105import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700106import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.Collections;
108import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800109import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Enumeration;
111import java.util.HashMap;
112import java.util.HashSet;
113import java.util.Iterator;
114import java.util.List;
115import java.util.Map;
116import java.util.Set;
117import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800118import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import java.util.zip.ZipFile;
120import java.util.zip.ZipOutputStream;
121
122class PackageManagerService extends IPackageManager.Stub {
123 private static final String TAG = "PackageManager";
124 private static final boolean DEBUG_SETTINGS = false;
125 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800126 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800127 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
129 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
130 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400131 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private static final int FIRST_APPLICATION_UID =
133 Process.FIRST_APPLICATION_UID;
134 private static final int MAX_APPLICATION_UIDS = 1000;
135
136 private static final boolean SHOW_INFO = false;
137
138 private static final boolean GET_CERTIFICATES = true;
139
Oscar Montemayora8529f62009-11-18 10:14:20 -0800140 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private static final int REMOVE_EVENTS =
143 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
144 private static final int ADD_EVENTS =
145 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
146
147 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800148 // Suffix used during package installation when copying/moving
149 // package apks to install directory.
150 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800152 /**
153 * Indicates the state of installation. Used by PackageManager to
154 * figure out incomplete installations. Say a package is being installed
155 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
156 * the package installation is successful or unsuccesful lin which case
157 * the PackageManager will no longer maintain state information associated
158 * with the package. If some exception(like device freeze or battery being
159 * pulled out) occurs during installation of a package, the PackageManager
160 * needs this information to clean up the previously failed installation.
161 */
162 private static final int PKG_INSTALL_INCOMPLETE = 0;
163 private static final int PKG_INSTALL_COMPLETE = 1;
164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final int SCAN_MONITOR = 1<<0;
166 static final int SCAN_NO_DEX = 1<<1;
167 static final int SCAN_FORCE_DEX = 1<<2;
168 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800169 static final int SCAN_NEW_INSTALL = 1<<4;
170 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800172 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
173 "com.android.defcontainer",
174 "com.android.defcontainer.DefaultContainerService");
175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
177 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700178 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Dianne Hackborn851a5412009-05-08 12:06:44 -0700180 final int mSdkVersion = Build.VERSION.SDK_INT;
181 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
182 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 final Context mContext;
185 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700186 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 final DisplayMetrics mMetrics;
188 final int mDefParseFlags;
189 final String[] mSeparateProcesses;
190
191 // This is where all application persistent data goes.
192 final File mAppDataDir;
193
Oscar Montemayora8529f62009-11-18 10:14:20 -0800194 // If Encrypted File System feature is enabled, all application persistent data
195 // should go here instead.
196 final File mSecureAppDataDir;
197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 // This is the object monitoring the framework dir.
199 final FileObserver mFrameworkInstallObserver;
200
201 // This is the object monitoring the system app dir.
202 final FileObserver mSystemInstallObserver;
203
204 // This is the object monitoring mAppInstallDir.
205 final FileObserver mAppInstallObserver;
206
207 // This is the object monitoring mDrmAppPrivateInstallDir.
208 final FileObserver mDrmAppInstallObserver;
209
210 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
211 // LOCK HELD. Can be called with mInstallLock held.
212 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 final File mFrameworkDir;
215 final File mSystemAppDir;
216 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700217 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
219 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
220 // apps.
221 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 // Lock for state used when installing and doing other long running
226 // operations. Methods that must be called with this lock held have
227 // the prefix "LI".
228 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 // These are the directories in the 3rd party applications installed dir
231 // that we have currently loaded packages from. Keys are the application's
232 // installed zip file (absolute codePath), and values are Package.
233 final HashMap<String, PackageParser.Package> mAppDirs =
234 new HashMap<String, PackageParser.Package>();
235
236 // Information for the parser to write more useful error messages.
237 File mScanningPath;
238 int mLastScanError;
239
240 final int[] mOutPermissions = new int[3];
241
242 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // Keys are String (package name), values are Package. This also serves
245 // as the lock for the global state. Methods that must be called with
246 // this lock held have the prefix "LP".
247 final HashMap<String, PackageParser.Package> mPackages =
248 new HashMap<String, PackageParser.Package>();
249
250 final Settings mSettings;
251 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
253 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
254 int[] mGlobalGids;
255
256 // These are the built-in uid -> permission mappings that were read from the
257 // etc/permissions.xml file.
258 final SparseArray<HashSet<String>> mSystemPermissions =
259 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 // These are the built-in shared libraries that were read from the
262 // etc/permissions.xml file.
263 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800264
Dianne Hackborn49237342009-08-27 20:08:01 -0700265 // Temporary for building the final shared libraries for an .apk.
266 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800267
Dianne Hackborn49237342009-08-27 20:08:01 -0700268 // These are the features this devices supports that were read from the
269 // etc/permissions.xml file.
270 final HashMap<String, FeatureInfo> mAvailableFeatures =
271 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 // All available activities, for your resolving pleasure.
274 final ActivityIntentResolver mActivities =
275 new ActivityIntentResolver();
276
277 // All available receivers, for your resolving pleasure.
278 final ActivityIntentResolver mReceivers =
279 new ActivityIntentResolver();
280
281 // All available services, for your resolving pleasure.
282 final ServiceIntentResolver mServices = new ServiceIntentResolver();
283
284 // Keys are String (provider class name), values are Provider.
285 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
286 new HashMap<ComponentName, PackageParser.Provider>();
287
288 // Mapping from provider base names (first directory in content URI codePath)
289 // to the provider information.
290 final HashMap<String, PackageParser.Provider> mProviders =
291 new HashMap<String, PackageParser.Provider>();
292
293 // Mapping from instrumentation class names to info about them.
294 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
295 new HashMap<ComponentName, PackageParser.Instrumentation>();
296
297 // Mapping from permission names to info about them.
298 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
299 new HashMap<String, PackageParser.PermissionGroup>();
300
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800301 // Packages whose data we have transfered into another package, thus
302 // should no longer exist.
303 final HashSet<String> mTransferedPackages = new HashSet<String>();
304
Dianne Hackborn854060af2009-07-09 18:14:31 -0700305 // Broadcast actions that are only available to the system.
306 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 boolean mSystemReady;
309 boolean mSafeMode;
310 boolean mHasSystemUidErrors;
311
312 ApplicationInfo mAndroidApplication;
313 final ActivityInfo mResolveActivity = new ActivityInfo();
314 final ResolveInfo mResolveInfo = new ResolveInfo();
315 ComponentName mResolveComponentName;
316 PackageParser.Package mPlatformPackage;
317
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700318 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800319 final HashMap<String, ArrayList<String>> mPendingBroadcasts
320 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800321 // Service Connection to remote media container service to copy
322 // package uri's from external media onto secure containers
323 // or internal storage.
324 private IMediaContainerService mContainerService = null;
325
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700326 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800327 static final int MCS_BOUND = 3;
328 static final int END_COPY = 4;
329 static final int INIT_COPY = 5;
330 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800331 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800332 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800333 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800334 static final int MCS_RECONNECT = 10;
335 static final int MCS_GIVE_UP = 11;
336
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700337 // Delay time in millisecs
338 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800339 final private DefaultContainerConnection mDefContainerConn =
340 new DefaultContainerConnection();
341 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800342 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800343 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800344 IMediaContainerService imcs =
345 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800346 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800347 }
348
349 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800350 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800351 }
352 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700353
Christopher Tate1bb69062010-02-19 17:02:12 -0800354 // Recordkeeping of restore-after-install operations that are currently in flight
355 // between the Package Manager and the Backup Manager
356 class PostInstallData {
357 public InstallArgs args;
358 public PackageInstalledInfo res;
359
360 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
361 args = _a;
362 res = _r;
363 }
364 };
365 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
366 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
367
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700368 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800369 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800370 final ArrayList<HandlerParams> mPendingInstalls =
371 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800372
373 private boolean connectToService() {
374 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
375 " DefaultContainerService");
376 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
377 if (mContext.bindService(service, mDefContainerConn,
378 Context.BIND_AUTO_CREATE)) {
379 mBound = true;
380 return true;
381 }
382 return false;
383 }
384
385 private void disconnectService() {
386 mContainerService = null;
387 mBound = false;
388 mContext.unbindService(mDefContainerConn);
389 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800390
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700391 PackageHandler(Looper looper) {
392 super(looper);
393 }
394 public void handleMessage(Message msg) {
395 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800396 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800397 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800398 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800399 int idx = mPendingInstalls.size();
400 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
401 // If a bind was already initiated we dont really
402 // need to do anything. The pending install
403 // will be processed later on.
404 if (!mBound) {
405 // If this is the only one pending we might
406 // have to bind to the service again.
407 if (!connectToService()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800408 Log.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800409 params.serviceError();
410 return;
411 } else {
412 // Once we bind to the service, the first
413 // pending request will be processed.
414 mPendingInstalls.add(idx, params);
415 }
416 } else {
417 mPendingInstalls.add(idx, params);
418 // Already bound to the service. Just make
419 // sure we trigger off processing the first request.
420 if (idx == 0) {
421 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800422 }
423 }
424 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800425 }
426 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800427 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800428 if (msg.obj != null) {
429 mContainerService = (IMediaContainerService) msg.obj;
430 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800431 if (mContainerService == null) {
432 // Something seriously wrong. Bail out
433 Log.e(TAG, "Cannot bind to media container service");
434 for (HandlerParams params : mPendingInstalls) {
435 mPendingInstalls.remove(0);
436 // Indicate service bind error
437 params.serviceError();
438 }
439 mPendingInstalls.clear();
440 } else if (mPendingInstalls.size() > 0) {
441 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800442 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800443 params.startCopy();
444 }
445 } else {
446 // Should never happen ideally.
447 Log.w(TAG, "Empty queue");
448 }
449 break;
450 }
451 case MCS_RECONNECT : {
452 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
453 if (mPendingInstalls.size() > 0) {
454 if (mBound) {
455 disconnectService();
456 }
457 if (!connectToService()) {
458 Log.e(TAG, "Failed to bind to media container service");
459 for (HandlerParams params : mPendingInstalls) {
460 mPendingInstalls.remove(0);
461 // Indicate service bind error
462 params.serviceError();
463 }
464 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800465 }
466 }
467 break;
468 }
469 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
471 // Delete pending install
472 if (mPendingInstalls.size() > 0) {
473 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800474 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800475 if (mPendingInstalls.size() == 0) {
476 if (mBound) {
477 disconnectService();
478 }
479 } else {
480 // There are more pending requests in queue.
481 // Just post MCS_BOUND message to trigger processing
482 // of next pending install.
483 mHandler.sendEmptyMessage(MCS_BOUND);
484 }
485 break;
486 }
487 case MCS_GIVE_UP: {
488 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
489 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800490 break;
491 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700492 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800493 String packages[];
494 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700495 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700496 int uids[];
497 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800498 if (mPendingBroadcasts == null) {
499 return;
500 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700501 size = mPendingBroadcasts.size();
502 if (size <= 0) {
503 // Nothing to be done. Just return
504 return;
505 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800506 packages = new String[size];
507 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700508 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800509 Iterator<HashMap.Entry<String, ArrayList<String>>>
510 it = mPendingBroadcasts.entrySet().iterator();
511 int i = 0;
512 while (it.hasNext() && i < size) {
513 HashMap.Entry<String, ArrayList<String>> ent = it.next();
514 packages[i] = ent.getKey();
515 components[i] = ent.getValue();
516 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700517 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800518 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700519 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800520 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700521 mPendingBroadcasts.clear();
522 }
523 // Send broadcasts
524 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800525 sendPackageChangedBroadcast(packages[i], true,
526 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700527 }
528 break;
529 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800530 case START_CLEANING_PACKAGE: {
531 String packageName = (String)msg.obj;
532 synchronized (mPackages) {
533 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
534 mSettings.mPackagesToBeCleaned.add(packageName);
535 }
536 }
537 startCleaningPackages();
538 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800539 case POST_INSTALL: {
540 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
541 PostInstallData data = mRunningInstalls.get(msg.arg1);
542 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800543 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800544
545 if (data != null) {
546 InstallArgs args = data.args;
547 PackageInstalledInfo res = data.res;
548
549 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
550 res.removedInfo.sendBroadcast(false, true);
551 Bundle extras = new Bundle(1);
552 extras.putInt(Intent.EXTRA_UID, res.uid);
553 final boolean update = res.removedInfo.removedPackage != null;
554 if (update) {
555 extras.putBoolean(Intent.EXTRA_REPLACING, true);
556 }
557 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
558 res.pkg.applicationInfo.packageName,
559 extras);
560 if (update) {
561 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
562 res.pkg.applicationInfo.packageName,
563 extras);
564 }
565 if (res.removedInfo.args != null) {
566 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800567 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800568 }
569 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800570 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800571 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800572 // We delete after a gc for applications on sdcard.
573 if (deleteOld) {
574 synchronized (mInstallLock) {
575 res.removedInfo.args.doPostDeleteLI(true);
576 }
577 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800578 if (args.observer != null) {
579 try {
580 args.observer.packageInstalled(res.name, res.returnCode);
581 } catch (RemoteException e) {
582 Log.i(TAG, "Observer no longer exists.");
583 }
584 }
585 } else {
586 Log.e(TAG, "Bogus post-install token " + msg.arg1);
587 }
588 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700589 }
590 }
591 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800592
593 static boolean installOnSd(int flags) {
594 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800595 ((flags & PackageManager.INSTALL_EXTERNAL) == 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800596 return false;
597 }
598 return true;
599 }
600
601 static boolean isFwdLocked(int flags) {
602 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
603 return true;
604 }
605 return false;
606 }
607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 public static final IPackageManager main(Context context, boolean factoryTest) {
609 PackageManagerService m = new PackageManagerService(context, factoryTest);
610 ServiceManager.addService("package", m);
611 return m;
612 }
613
614 static String[] splitString(String str, char sep) {
615 int count = 1;
616 int i = 0;
617 while ((i=str.indexOf(sep, i)) >= 0) {
618 count++;
619 i++;
620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 String[] res = new String[count];
623 i=0;
624 count = 0;
625 int lastI=0;
626 while ((i=str.indexOf(sep, i)) >= 0) {
627 res[count] = str.substring(lastI, i);
628 count++;
629 i++;
630 lastI = i;
631 }
632 res[count] = str.substring(lastI, str.length());
633 return res;
634 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800637 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 if (mSdkVersion <= 0) {
641 Log.w(TAG, "**** ro.build.version.sdk not set!");
642 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 mContext = context;
645 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700646 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 mMetrics = new DisplayMetrics();
648 mSettings = new Settings();
649 mSettings.addSharedUserLP("android.uid.system",
650 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
651 mSettings.addSharedUserLP("android.uid.phone",
652 MULTIPLE_APPLICATION_UIDS
653 ? RADIO_UID : FIRST_APPLICATION_UID,
654 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400655 mSettings.addSharedUserLP("android.uid.log",
656 MULTIPLE_APPLICATION_UIDS
657 ? LOG_UID : FIRST_APPLICATION_UID,
658 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659
660 String separateProcesses = SystemProperties.get("debug.separate_processes");
661 if (separateProcesses != null && separateProcesses.length() > 0) {
662 if ("*".equals(separateProcesses)) {
663 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
664 mSeparateProcesses = null;
665 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
666 } else {
667 mDefParseFlags = 0;
668 mSeparateProcesses = separateProcesses.split(",");
669 Log.w(TAG, "Running with debug.separate_processes: "
670 + separateProcesses);
671 }
672 } else {
673 mDefParseFlags = 0;
674 mSeparateProcesses = null;
675 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 Installer installer = new Installer();
678 // Little hacky thing to check if installd is here, to determine
679 // whether we are running on the simulator and thus need to take
680 // care of building the /data file structure ourself.
681 // (apparently the sim now has a working installer)
682 if (installer.ping() && Process.supportsProcesses()) {
683 mInstaller = installer;
684 } else {
685 mInstaller = null;
686 }
687
688 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
689 Display d = wm.getDefaultDisplay();
690 d.getMetrics(mMetrics);
691
692 synchronized (mInstallLock) {
693 synchronized (mPackages) {
694 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700695 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 File dataDir = Environment.getDataDirectory();
698 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800699 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
701
702 if (mInstaller == null) {
703 // Make sure these dirs exist, when we are running in
704 // the simulator.
705 // Make a wide-open directory for random misc stuff.
706 File miscDir = new File(dataDir, "misc");
707 miscDir.mkdirs();
708 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800709 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 mDrmAppPrivateInstallDir.mkdirs();
711 }
712
713 readPermissions();
714
715 mRestoredSettings = mSettings.readLP();
716 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800717
718 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800721 // Set flag to monitor and not change apk file paths when
722 // scanning install directories.
723 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700724 if (mNoDexOpt) {
725 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800726 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700732 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700735 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 /**
738 * Out of paranoia, ensure that everything in the boot class
739 * path has been dexed.
740 */
741 String bootClassPath = System.getProperty("java.boot.class.path");
742 if (bootClassPath != null) {
743 String[] paths = splitString(bootClassPath, ':');
744 for (int i=0; i<paths.length; i++) {
745 try {
746 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
747 libFiles.add(paths[i]);
748 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700749 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 }
751 } catch (FileNotFoundException e) {
752 Log.w(TAG, "Boot class path not found: " + paths[i]);
753 } catch (IOException e) {
754 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
755 }
756 }
757 } else {
758 Log.w(TAG, "No BOOTCLASSPATH found!");
759 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 /**
762 * Also ensure all external libraries have had dexopt run on them.
763 */
764 if (mSharedLibraries.size() > 0) {
765 Iterator<String> libs = mSharedLibraries.values().iterator();
766 while (libs.hasNext()) {
767 String lib = libs.next();
768 try {
769 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
770 libFiles.add(lib);
771 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700772 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 }
774 } catch (FileNotFoundException e) {
775 Log.w(TAG, "Library not found: " + lib);
776 } catch (IOException e) {
777 Log.w(TAG, "Exception reading library: " + lib, e);
778 }
779 }
780 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 // Gross hack for now: we know this file doesn't contain any
783 // code, so don't dexopt it to avoid the resulting log spew.
784 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 /**
787 * And there are a number of commands implemented in Java, which
788 * we currently need to do the dexopt on so that they can be
789 * run from a non-root shell.
790 */
791 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700792 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 for (int i=0; i<frameworkFiles.length; i++) {
794 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
795 String path = libPath.getPath();
796 // Skip the file if we alrady did it.
797 if (libFiles.contains(path)) {
798 continue;
799 }
800 // Skip the file if it is not a type we want to dexopt.
801 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
802 continue;
803 }
804 try {
805 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
806 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700807 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 }
809 } catch (FileNotFoundException e) {
810 Log.w(TAG, "Jar not found: " + path);
811 } catch (IOException e) {
812 Log.w(TAG, "Exception reading jar: " + path, e);
813 }
814 }
815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800816
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700817 if (didDexOpt) {
818 // If we had to do a dexopt of one of the previous
819 // things, then something on the system has changed.
820 // Consider this significant, and wipe away all other
821 // existing dexopt files to ensure we don't leave any
822 // dangling around.
823 String[] files = mDalvikCacheDir.list();
824 if (files != null) {
825 for (int i=0; i<files.length; i++) {
826 String fn = files[i];
827 if (fn.startsWith("data@app@")
828 || fn.startsWith("data@app-private@")) {
829 Log.i(TAG, "Pruning dalvik file: " + fn);
830 (new File(mDalvikCacheDir, fn)).delete();
831 }
832 }
833 }
834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800836
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800837 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 mFrameworkInstallObserver = new AppDirObserver(
839 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
840 mFrameworkInstallObserver.startWatching();
841 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800842 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800843
844 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
846 mSystemInstallObserver = new AppDirObserver(
847 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
848 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800849 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800850
851 if (mInstaller != null) {
852 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
853 mInstaller.moveFiles();
854 }
855
856 // Prune any system packages that no longer exist.
857 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
858 while (psit.hasNext()) {
859 PackageSetting ps = psit.next();
860 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800861 && !mPackages.containsKey(ps.name)
862 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800863 psit.remove();
864 String msg = "System package " + ps.name
865 + " no longer exists; wiping its data";
866 reportSettingsProblem(Log.WARN, msg);
867 if (mInstaller != null) {
868 // XXX how to set useEncryptedFSDir for packages that
869 // are not encrypted?
870 mInstaller.remove(ps.name, true);
871 }
872 }
873 }
874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 mAppInstallDir = new File(dataDir, "app");
876 if (mInstaller == null) {
877 // Make sure these dirs exist, when we are running in
878 // the simulator.
879 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
880 }
881 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800882 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 //clean up list
884 for(int i = 0; i < deletePkgsList.size(); i++) {
885 //clean up here
886 cleanupInstallFailedPackage(deletePkgsList.get(i));
887 }
888 //delete tmp files
889 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800890
891 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 SystemClock.uptimeMillis());
893 mAppInstallObserver = new AppDirObserver(
894 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
895 mAppInstallObserver.startWatching();
896 scanDirLI(mAppInstallDir, 0, scanMode);
897
898 mDrmAppInstallObserver = new AppDirObserver(
899 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
900 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800901 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800903 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 SystemClock.uptimeMillis());
905 Log.i(TAG, "Time to scan packages: "
906 + ((SystemClock.uptimeMillis()-startTime)/1000f)
907 + " seconds");
908
909 updatePermissionsLP();
910
911 mSettings.writeLP();
912
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800913 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 // Now after opening every single application zip, make sure they
917 // are all flushed. Not really needed, but keeps things nice and
918 // tidy.
919 Runtime.getRuntime().gc();
920 } // synchronized (mPackages)
921 } // synchronized (mInstallLock)
922 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 @Override
925 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
926 throws RemoteException {
927 try {
928 return super.onTransact(code, data, reply, flags);
929 } catch (RuntimeException e) {
930 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
931 Log.e(TAG, "Package Manager Crash", e);
932 }
933 throw e;
934 }
935 }
936
Dianne Hackborne6620b22010-01-22 14:46:21 -0800937 void cleanupInstallFailedPackage(PackageSetting ps) {
938 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800940 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
941 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 if (retCode < 0) {
943 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800944 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 }
946 } else {
947 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800948 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 File dataDir = new File(pkg.applicationInfo.dataDir);
950 dataDir.delete();
951 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800952 if (ps.codePath != null) {
953 if (!ps.codePath.delete()) {
954 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
955 }
956 }
957 if (ps.resourcePath != null) {
958 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
959 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
960 }
961 }
962 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 }
964
965 void readPermissions() {
966 // Read permissions from .../etc/permission directory.
967 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
968 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
969 Log.w(TAG, "No directory " + libraryDir + ", skipping");
970 return;
971 }
972 if (!libraryDir.canRead()) {
973 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
974 return;
975 }
976
977 // Iterate over the files in the directory and scan .xml files
978 for (File f : libraryDir.listFiles()) {
979 // We'll read platform.xml last
980 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
981 continue;
982 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 if (!f.getPath().endsWith(".xml")) {
985 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
986 continue;
987 }
988 if (!f.canRead()) {
989 Log.w(TAG, "Permissions library file " + f + " cannot be read");
990 continue;
991 }
992
993 readPermissionsFromXml(f);
994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
997 final File permFile = new File(Environment.getRootDirectory(),
998 "etc/permissions/platform.xml");
999 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001000
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001001 StringBuilder sb = new StringBuilder(128);
1002 sb.append("Libs:");
1003 Iterator<String> it = mSharedLibraries.keySet().iterator();
1004 while (it.hasNext()) {
1005 sb.append(' ');
1006 String name = it.next();
1007 sb.append(name);
1008 sb.append(':');
1009 sb.append(mSharedLibraries.get(name));
1010 }
1011 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001012
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001013 sb.setLength(0);
1014 sb.append("Features:");
1015 it = mAvailableFeatures.keySet().iterator();
1016 while (it.hasNext()) {
1017 sb.append(' ');
1018 sb.append(it.next());
1019 }
1020 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001022
1023 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 FileReader permReader = null;
1025 try {
1026 permReader = new FileReader(permFile);
1027 } catch (FileNotFoundException e) {
1028 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
1029 return;
1030 }
1031
1032 try {
1033 XmlPullParser parser = Xml.newPullParser();
1034 parser.setInput(permReader);
1035
1036 XmlUtils.beginDocument(parser, "permissions");
1037
1038 while (true) {
1039 XmlUtils.nextElement(parser);
1040 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1041 break;
1042 }
1043
1044 String name = parser.getName();
1045 if ("group".equals(name)) {
1046 String gidStr = parser.getAttributeValue(null, "gid");
1047 if (gidStr != null) {
1048 int gid = Integer.parseInt(gidStr);
1049 mGlobalGids = appendInt(mGlobalGids, gid);
1050 } else {
1051 Log.w(TAG, "<group> without gid at "
1052 + parser.getPositionDescription());
1053 }
1054
1055 XmlUtils.skipCurrentTag(parser);
1056 continue;
1057 } else if ("permission".equals(name)) {
1058 String perm = parser.getAttributeValue(null, "name");
1059 if (perm == null) {
1060 Log.w(TAG, "<permission> without name at "
1061 + parser.getPositionDescription());
1062 XmlUtils.skipCurrentTag(parser);
1063 continue;
1064 }
1065 perm = perm.intern();
1066 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 } else if ("assign-permission".equals(name)) {
1069 String perm = parser.getAttributeValue(null, "name");
1070 if (perm == null) {
1071 Log.w(TAG, "<assign-permission> without name at "
1072 + parser.getPositionDescription());
1073 XmlUtils.skipCurrentTag(parser);
1074 continue;
1075 }
1076 String uidStr = parser.getAttributeValue(null, "uid");
1077 if (uidStr == null) {
1078 Log.w(TAG, "<assign-permission> without uid at "
1079 + parser.getPositionDescription());
1080 XmlUtils.skipCurrentTag(parser);
1081 continue;
1082 }
1083 int uid = Process.getUidForName(uidStr);
1084 if (uid < 0) {
1085 Log.w(TAG, "<assign-permission> with unknown uid \""
1086 + uidStr + "\" at "
1087 + parser.getPositionDescription());
1088 XmlUtils.skipCurrentTag(parser);
1089 continue;
1090 }
1091 perm = perm.intern();
1092 HashSet<String> perms = mSystemPermissions.get(uid);
1093 if (perms == null) {
1094 perms = new HashSet<String>();
1095 mSystemPermissions.put(uid, perms);
1096 }
1097 perms.add(perm);
1098 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 } else if ("library".equals(name)) {
1101 String lname = parser.getAttributeValue(null, "name");
1102 String lfile = parser.getAttributeValue(null, "file");
1103 if (lname == null) {
1104 Log.w(TAG, "<library> without name at "
1105 + parser.getPositionDescription());
1106 } else if (lfile == null) {
1107 Log.w(TAG, "<library> without file at "
1108 + parser.getPositionDescription());
1109 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001110 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001111 mSharedLibraries.put(lname, lfile);
1112 }
1113 XmlUtils.skipCurrentTag(parser);
1114 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001115
Dianne Hackborn49237342009-08-27 20:08:01 -07001116 } else if ("feature".equals(name)) {
1117 String fname = parser.getAttributeValue(null, "name");
1118 if (fname == null) {
1119 Log.w(TAG, "<feature> without name at "
1120 + parser.getPositionDescription());
1121 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001122 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001123 FeatureInfo fi = new FeatureInfo();
1124 fi.name = fname;
1125 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
1127 XmlUtils.skipCurrentTag(parser);
1128 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 } else {
1131 XmlUtils.skipCurrentTag(parser);
1132 continue;
1133 }
1134
1135 }
1136 } catch (XmlPullParserException e) {
1137 Log.w(TAG, "Got execption parsing permissions.", e);
1138 } catch (IOException e) {
1139 Log.w(TAG, "Got execption parsing permissions.", e);
1140 }
1141 }
1142
1143 void readPermission(XmlPullParser parser, String name)
1144 throws IOException, XmlPullParserException {
1145
1146 name = name.intern();
1147
1148 BasePermission bp = mSettings.mPermissions.get(name);
1149 if (bp == null) {
1150 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1151 mSettings.mPermissions.put(name, bp);
1152 }
1153 int outerDepth = parser.getDepth();
1154 int type;
1155 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1156 && (type != XmlPullParser.END_TAG
1157 || parser.getDepth() > outerDepth)) {
1158 if (type == XmlPullParser.END_TAG
1159 || type == XmlPullParser.TEXT) {
1160 continue;
1161 }
1162
1163 String tagName = parser.getName();
1164 if ("group".equals(tagName)) {
1165 String gidStr = parser.getAttributeValue(null, "gid");
1166 if (gidStr != null) {
1167 int gid = Process.getGidForName(gidStr);
1168 bp.gids = appendInt(bp.gids, gid);
1169 } else {
1170 Log.w(TAG, "<group> without gid at "
1171 + parser.getPositionDescription());
1172 }
1173 }
1174 XmlUtils.skipCurrentTag(parser);
1175 }
1176 }
1177
1178 static int[] appendInt(int[] cur, int val) {
1179 if (cur == null) {
1180 return new int[] { val };
1181 }
1182 final int N = cur.length;
1183 for (int i=0; i<N; i++) {
1184 if (cur[i] == val) {
1185 return cur;
1186 }
1187 }
1188 int[] ret = new int[N+1];
1189 System.arraycopy(cur, 0, ret, 0, N);
1190 ret[N] = val;
1191 return ret;
1192 }
1193
1194 static int[] appendInts(int[] cur, int[] add) {
1195 if (add == null) return cur;
1196 if (cur == null) return add;
1197 final int N = add.length;
1198 for (int i=0; i<N; i++) {
1199 cur = appendInt(cur, add[i]);
1200 }
1201 return cur;
1202 }
1203
1204 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001205 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1206 // The package has been uninstalled but has retained data and resources.
1207 return PackageParser.generatePackageInfo(p, null, flags);
1208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 final PackageSetting ps = (PackageSetting)p.mExtras;
1210 if (ps == null) {
1211 return null;
1212 }
1213 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1214 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1215 }
1216
1217 public PackageInfo getPackageInfo(String packageName, int flags) {
1218 synchronized (mPackages) {
1219 PackageParser.Package p = mPackages.get(packageName);
1220 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001221 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 + ": " + p);
1223 if (p != null) {
1224 return generatePackageInfo(p, flags);
1225 }
1226 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1227 return generatePackageInfoFromSettingsLP(packageName, flags);
1228 }
1229 }
1230 return null;
1231 }
1232
Dianne Hackborn47096932010-02-11 15:57:09 -08001233 public String[] currentToCanonicalPackageNames(String[] names) {
1234 String[] out = new String[names.length];
1235 synchronized (mPackages) {
1236 for (int i=names.length-1; i>=0; i--) {
1237 PackageSetting ps = mSettings.mPackages.get(names[i]);
1238 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1239 }
1240 }
1241 return out;
1242 }
1243
1244 public String[] canonicalToCurrentPackageNames(String[] names) {
1245 String[] out = new String[names.length];
1246 synchronized (mPackages) {
1247 for (int i=names.length-1; i>=0; i--) {
1248 String cur = mSettings.mRenamedPackages.get(names[i]);
1249 out[i] = cur != null ? cur : names[i];
1250 }
1251 }
1252 return out;
1253 }
1254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 public int getPackageUid(String packageName) {
1256 synchronized (mPackages) {
1257 PackageParser.Package p = mPackages.get(packageName);
1258 if(p != null) {
1259 return p.applicationInfo.uid;
1260 }
1261 PackageSetting ps = mSettings.mPackages.get(packageName);
1262 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1263 return -1;
1264 }
1265 p = ps.pkg;
1266 return p != null ? p.applicationInfo.uid : -1;
1267 }
1268 }
1269
1270 public int[] getPackageGids(String packageName) {
1271 synchronized (mPackages) {
1272 PackageParser.Package p = mPackages.get(packageName);
1273 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001274 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 + ": " + p);
1276 if (p != null) {
1277 final PackageSetting ps = (PackageSetting)p.mExtras;
1278 final SharedUserSetting suid = ps.sharedUser;
1279 return suid != null ? suid.gids : ps.gids;
1280 }
1281 }
1282 // stupid thing to indicate an error.
1283 return new int[0];
1284 }
1285
1286 public PermissionInfo getPermissionInfo(String name, int flags) {
1287 synchronized (mPackages) {
1288 final BasePermission p = mSettings.mPermissions.get(name);
1289 if (p != null && p.perm != null) {
1290 return PackageParser.generatePermissionInfo(p.perm, flags);
1291 }
1292 return null;
1293 }
1294 }
1295
1296 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1297 synchronized (mPackages) {
1298 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1299 for (BasePermission p : mSettings.mPermissions.values()) {
1300 if (group == null) {
1301 if (p.perm.info.group == null) {
1302 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1303 }
1304 } else {
1305 if (group.equals(p.perm.info.group)) {
1306 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1307 }
1308 }
1309 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 if (out.size() > 0) {
1312 return out;
1313 }
1314 return mPermissionGroups.containsKey(group) ? out : null;
1315 }
1316 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1319 synchronized (mPackages) {
1320 return PackageParser.generatePermissionGroupInfo(
1321 mPermissionGroups.get(name), flags);
1322 }
1323 }
1324
1325 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1326 synchronized (mPackages) {
1327 final int N = mPermissionGroups.size();
1328 ArrayList<PermissionGroupInfo> out
1329 = new ArrayList<PermissionGroupInfo>(N);
1330 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1331 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1332 }
1333 return out;
1334 }
1335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1338 PackageSetting ps = mSettings.mPackages.get(packageName);
1339 if(ps != null) {
1340 if(ps.pkg == null) {
1341 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1342 if(pInfo != null) {
1343 return pInfo.applicationInfo;
1344 }
1345 return null;
1346 }
1347 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1348 }
1349 return null;
1350 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1353 PackageSetting ps = mSettings.mPackages.get(packageName);
1354 if(ps != null) {
1355 if(ps.pkg == null) {
1356 ps.pkg = new PackageParser.Package(packageName);
1357 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001358 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1359 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1360 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1361 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
1363 return generatePackageInfo(ps.pkg, flags);
1364 }
1365 return null;
1366 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1369 synchronized (mPackages) {
1370 PackageParser.Package p = mPackages.get(packageName);
1371 if (Config.LOGV) Log.v(
1372 TAG, "getApplicationInfo " + packageName
1373 + ": " + p);
1374 if (p != null) {
1375 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001376 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 }
1378 if ("android".equals(packageName)||"system".equals(packageName)) {
1379 return mAndroidApplication;
1380 }
1381 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1382 return generateApplicationInfoFromSettingsLP(packageName, flags);
1383 }
1384 }
1385 return null;
1386 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001387
1388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1390 mContext.enforceCallingOrSelfPermission(
1391 android.Manifest.permission.CLEAR_APP_CACHE, null);
1392 // Queue up an async operation since clearing cache may take a little while.
1393 mHandler.post(new Runnable() {
1394 public void run() {
1395 mHandler.removeCallbacks(this);
1396 int retCode = -1;
1397 if (mInstaller != null) {
1398 retCode = mInstaller.freeCache(freeStorageSize);
1399 if (retCode < 0) {
1400 Log.w(TAG, "Couldn't clear application caches");
1401 }
1402 } //end if mInstaller
1403 if (observer != null) {
1404 try {
1405 observer.onRemoveCompleted(null, (retCode >= 0));
1406 } catch (RemoteException e) {
1407 Log.w(TAG, "RemoveException when invoking call back");
1408 }
1409 }
1410 }
1411 });
1412 }
1413
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001414 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001415 mContext.enforceCallingOrSelfPermission(
1416 android.Manifest.permission.CLEAR_APP_CACHE, null);
1417 // Queue up an async operation since clearing cache may take a little while.
1418 mHandler.post(new Runnable() {
1419 public void run() {
1420 mHandler.removeCallbacks(this);
1421 int retCode = -1;
1422 if (mInstaller != null) {
1423 retCode = mInstaller.freeCache(freeStorageSize);
1424 if (retCode < 0) {
1425 Log.w(TAG, "Couldn't clear application caches");
1426 }
1427 }
1428 if(pi != null) {
1429 try {
1430 // Callback via pending intent
1431 int code = (retCode >= 0) ? 1 : 0;
1432 pi.sendIntent(null, code, null,
1433 null, null);
1434 } catch (SendIntentException e1) {
1435 Log.i(TAG, "Failed to send pending intent");
1436 }
1437 }
1438 }
1439 });
1440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1443 synchronized (mPackages) {
1444 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001445
1446 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001448 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 }
1450 if (mResolveComponentName.equals(component)) {
1451 return mResolveActivity;
1452 }
1453 }
1454 return null;
1455 }
1456
1457 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1458 synchronized (mPackages) {
1459 PackageParser.Activity a = mReceivers.mActivities.get(component);
1460 if (Config.LOGV) Log.v(
1461 TAG, "getReceiverInfo " + component + ": " + a);
1462 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1463 return PackageParser.generateActivityInfo(a, flags);
1464 }
1465 }
1466 return null;
1467 }
1468
1469 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1470 synchronized (mPackages) {
1471 PackageParser.Service s = mServices.mServices.get(component);
1472 if (Config.LOGV) Log.v(
1473 TAG, "getServiceInfo " + component + ": " + s);
1474 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1475 return PackageParser.generateServiceInfo(s, flags);
1476 }
1477 }
1478 return null;
1479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 public String[] getSystemSharedLibraryNames() {
1482 Set<String> libSet;
1483 synchronized (mPackages) {
1484 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001485 int size = libSet.size();
1486 if (size > 0) {
1487 String[] libs = new String[size];
1488 libSet.toArray(libs);
1489 return libs;
1490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001492 return null;
1493 }
1494
1495 public FeatureInfo[] getSystemAvailableFeatures() {
1496 Collection<FeatureInfo> featSet;
1497 synchronized (mPackages) {
1498 featSet = mAvailableFeatures.values();
1499 int size = featSet.size();
1500 if (size > 0) {
1501 FeatureInfo[] features = new FeatureInfo[size+1];
1502 featSet.toArray(features);
1503 FeatureInfo fi = new FeatureInfo();
1504 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1505 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1506 features[size] = fi;
1507 return features;
1508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 }
1510 return null;
1511 }
1512
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001513 public boolean hasSystemFeature(String name) {
1514 synchronized (mPackages) {
1515 return mAvailableFeatures.containsKey(name);
1516 }
1517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 public int checkPermission(String permName, String pkgName) {
1520 synchronized (mPackages) {
1521 PackageParser.Package p = mPackages.get(pkgName);
1522 if (p != null && p.mExtras != null) {
1523 PackageSetting ps = (PackageSetting)p.mExtras;
1524 if (ps.sharedUser != null) {
1525 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1526 return PackageManager.PERMISSION_GRANTED;
1527 }
1528 } else if (ps.grantedPermissions.contains(permName)) {
1529 return PackageManager.PERMISSION_GRANTED;
1530 }
1531 }
1532 }
1533 return PackageManager.PERMISSION_DENIED;
1534 }
1535
1536 public int checkUidPermission(String permName, int uid) {
1537 synchronized (mPackages) {
1538 Object obj = mSettings.getUserIdLP(uid);
1539 if (obj != null) {
1540 if (obj instanceof SharedUserSetting) {
1541 SharedUserSetting sus = (SharedUserSetting)obj;
1542 if (sus.grantedPermissions.contains(permName)) {
1543 return PackageManager.PERMISSION_GRANTED;
1544 }
1545 } else if (obj instanceof PackageSetting) {
1546 PackageSetting ps = (PackageSetting)obj;
1547 if (ps.grantedPermissions.contains(permName)) {
1548 return PackageManager.PERMISSION_GRANTED;
1549 }
1550 }
1551 } else {
1552 HashSet<String> perms = mSystemPermissions.get(uid);
1553 if (perms != null && perms.contains(permName)) {
1554 return PackageManager.PERMISSION_GRANTED;
1555 }
1556 }
1557 }
1558 return PackageManager.PERMISSION_DENIED;
1559 }
1560
1561 private BasePermission findPermissionTreeLP(String permName) {
1562 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1563 if (permName.startsWith(bp.name) &&
1564 permName.length() > bp.name.length() &&
1565 permName.charAt(bp.name.length()) == '.') {
1566 return bp;
1567 }
1568 }
1569 return null;
1570 }
1571
1572 private BasePermission checkPermissionTreeLP(String permName) {
1573 if (permName != null) {
1574 BasePermission bp = findPermissionTreeLP(permName);
1575 if (bp != null) {
1576 if (bp.uid == Binder.getCallingUid()) {
1577 return bp;
1578 }
1579 throw new SecurityException("Calling uid "
1580 + Binder.getCallingUid()
1581 + " is not allowed to add to permission tree "
1582 + bp.name + " owned by uid " + bp.uid);
1583 }
1584 }
1585 throw new SecurityException("No permission tree found for " + permName);
1586 }
1587
1588 public boolean addPermission(PermissionInfo info) {
1589 synchronized (mPackages) {
1590 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1591 throw new SecurityException("Label must be specified in permission");
1592 }
1593 BasePermission tree = checkPermissionTreeLP(info.name);
1594 BasePermission bp = mSettings.mPermissions.get(info.name);
1595 boolean added = bp == null;
1596 if (added) {
1597 bp = new BasePermission(info.name, tree.sourcePackage,
1598 BasePermission.TYPE_DYNAMIC);
1599 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1600 throw new SecurityException(
1601 "Not allowed to modify non-dynamic permission "
1602 + info.name);
1603 }
1604 bp.perm = new PackageParser.Permission(tree.perm.owner,
1605 new PermissionInfo(info));
1606 bp.perm.info.packageName = tree.perm.info.packageName;
1607 bp.uid = tree.uid;
1608 if (added) {
1609 mSettings.mPermissions.put(info.name, bp);
1610 }
1611 mSettings.writeLP();
1612 return added;
1613 }
1614 }
1615
1616 public void removePermission(String name) {
1617 synchronized (mPackages) {
1618 checkPermissionTreeLP(name);
1619 BasePermission bp = mSettings.mPermissions.get(name);
1620 if (bp != null) {
1621 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1622 throw new SecurityException(
1623 "Not allowed to modify non-dynamic permission "
1624 + name);
1625 }
1626 mSettings.mPermissions.remove(name);
1627 mSettings.writeLP();
1628 }
1629 }
1630 }
1631
Dianne Hackborn854060af2009-07-09 18:14:31 -07001632 public boolean isProtectedBroadcast(String actionName) {
1633 synchronized (mPackages) {
1634 return mProtectedBroadcasts.contains(actionName);
1635 }
1636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 public int checkSignatures(String pkg1, String pkg2) {
1639 synchronized (mPackages) {
1640 PackageParser.Package p1 = mPackages.get(pkg1);
1641 PackageParser.Package p2 = mPackages.get(pkg2);
1642 if (p1 == null || p1.mExtras == null
1643 || p2 == null || p2.mExtras == null) {
1644 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1645 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001646 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
1648 }
1649
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001650 public int checkUidSignatures(int uid1, int uid2) {
1651 synchronized (mPackages) {
1652 Signature[] s1;
1653 Signature[] s2;
1654 Object obj = mSettings.getUserIdLP(uid1);
1655 if (obj != null) {
1656 if (obj instanceof SharedUserSetting) {
1657 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1658 } else if (obj instanceof PackageSetting) {
1659 s1 = ((PackageSetting)obj).signatures.mSignatures;
1660 } else {
1661 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1662 }
1663 } else {
1664 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1665 }
1666 obj = mSettings.getUserIdLP(uid2);
1667 if (obj != null) {
1668 if (obj instanceof SharedUserSetting) {
1669 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1670 } else if (obj instanceof PackageSetting) {
1671 s2 = ((PackageSetting)obj).signatures.mSignatures;
1672 } else {
1673 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1674 }
1675 } else {
1676 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1677 }
1678 return checkSignaturesLP(s1, s2);
1679 }
1680 }
1681
1682 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1683 if (s1 == null) {
1684 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1686 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1687 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001688 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1690 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001691 final int N1 = s1.length;
1692 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 for (int i=0; i<N1; i++) {
1694 boolean match = false;
1695 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001696 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 match = true;
1698 break;
1699 }
1700 }
1701 if (!match) {
1702 return PackageManager.SIGNATURE_NO_MATCH;
1703 }
1704 }
1705 return PackageManager.SIGNATURE_MATCH;
1706 }
1707
1708 public String[] getPackagesForUid(int uid) {
1709 synchronized (mPackages) {
1710 Object obj = mSettings.getUserIdLP(uid);
1711 if (obj instanceof SharedUserSetting) {
1712 SharedUserSetting sus = (SharedUserSetting)obj;
1713 final int N = sus.packages.size();
1714 String[] res = new String[N];
1715 Iterator<PackageSetting> it = sus.packages.iterator();
1716 int i=0;
1717 while (it.hasNext()) {
1718 res[i++] = it.next().name;
1719 }
1720 return res;
1721 } else if (obj instanceof PackageSetting) {
1722 PackageSetting ps = (PackageSetting)obj;
1723 return new String[] { ps.name };
1724 }
1725 }
1726 return null;
1727 }
1728
1729 public String getNameForUid(int uid) {
1730 synchronized (mPackages) {
1731 Object obj = mSettings.getUserIdLP(uid);
1732 if (obj instanceof SharedUserSetting) {
1733 SharedUserSetting sus = (SharedUserSetting)obj;
1734 return sus.name + ":" + sus.userId;
1735 } else if (obj instanceof PackageSetting) {
1736 PackageSetting ps = (PackageSetting)obj;
1737 return ps.name;
1738 }
1739 }
1740 return null;
1741 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 public int getUidForSharedUser(String sharedUserName) {
1744 if(sharedUserName == null) {
1745 return -1;
1746 }
1747 synchronized (mPackages) {
1748 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1749 if(suid == null) {
1750 return -1;
1751 }
1752 return suid.userId;
1753 }
1754 }
1755
1756 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1757 int flags) {
1758 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001759 return chooseBestActivity(intent, resolvedType, flags, query);
1760 }
1761
Mihai Predaeae850c2009-05-13 10:13:48 +02001762 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1763 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 if (query != null) {
1765 final int N = query.size();
1766 if (N == 1) {
1767 return query.get(0);
1768 } else if (N > 1) {
1769 // If there is more than one activity with the same priority,
1770 // then let the user decide between them.
1771 ResolveInfo r0 = query.get(0);
1772 ResolveInfo r1 = query.get(1);
1773 if (false) {
1774 System.out.println(r0.activityInfo.name +
1775 "=" + r0.priority + " vs " +
1776 r1.activityInfo.name +
1777 "=" + r1.priority);
1778 }
1779 // If the first activity has a higher priority, or a different
1780 // default, then it is always desireable to pick it.
1781 if (r0.priority != r1.priority
1782 || r0.preferredOrder != r1.preferredOrder
1783 || r0.isDefault != r1.isDefault) {
1784 return query.get(0);
1785 }
1786 // If we have saved a preference for a preferred activity for
1787 // this Intent, use that.
1788 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1789 flags, query, r0.priority);
1790 if (ri != null) {
1791 return ri;
1792 }
1793 return mResolveInfo;
1794 }
1795 }
1796 return null;
1797 }
1798
1799 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1800 int flags, List<ResolveInfo> query, int priority) {
1801 synchronized (mPackages) {
1802 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1803 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001804 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1806 if (prefs != null && prefs.size() > 0) {
1807 // First figure out how good the original match set is.
1808 // We will only allow preferred activities that came
1809 // from the same match quality.
1810 int match = 0;
1811 final int N = query.size();
1812 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1813 for (int j=0; j<N; j++) {
1814 ResolveInfo ri = query.get(j);
1815 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1816 + ": 0x" + Integer.toHexString(match));
1817 if (ri.match > match) match = ri.match;
1818 }
1819 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1820 + Integer.toHexString(match));
1821 match &= IntentFilter.MATCH_CATEGORY_MASK;
1822 final int M = prefs.size();
1823 for (int i=0; i<M; i++) {
1824 PreferredActivity pa = prefs.get(i);
1825 if (pa.mMatch != match) {
1826 continue;
1827 }
1828 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1829 if (DEBUG_PREFERRED) {
1830 Log.v(TAG, "Got preferred activity:");
1831 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1832 }
1833 if (ai != null) {
1834 for (int j=0; j<N; j++) {
1835 ResolveInfo ri = query.get(j);
1836 if (!ri.activityInfo.applicationInfo.packageName
1837 .equals(ai.applicationInfo.packageName)) {
1838 continue;
1839 }
1840 if (!ri.activityInfo.name.equals(ai.name)) {
1841 continue;
1842 }
1843
1844 // Okay we found a previously set preferred app.
1845 // If the result set is different from when this
1846 // was created, we need to clear it and re-ask the
1847 // user their preference.
1848 if (!pa.sameSet(query, priority)) {
1849 Log.i(TAG, "Result set changed, dropping preferred activity for "
1850 + intent + " type " + resolvedType);
1851 mSettings.mPreferredActivities.removeFilter(pa);
1852 return null;
1853 }
1854
1855 // Yay!
1856 return ri;
1857 }
1858 }
1859 }
1860 }
1861 }
1862 return null;
1863 }
1864
1865 public List<ResolveInfo> queryIntentActivities(Intent intent,
1866 String resolvedType, int flags) {
1867 ComponentName comp = intent.getComponent();
1868 if (comp != null) {
1869 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1870 ActivityInfo ai = getActivityInfo(comp, flags);
1871 if (ai != null) {
1872 ResolveInfo ri = new ResolveInfo();
1873 ri.activityInfo = ai;
1874 list.add(ri);
1875 }
1876 return list;
1877 }
1878
1879 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001880 String pkgName = intent.getPackage();
1881 if (pkgName == null) {
1882 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1883 resolvedType, flags);
1884 }
1885 PackageParser.Package pkg = mPackages.get(pkgName);
1886 if (pkg != null) {
1887 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1888 resolvedType, flags, pkg.activities);
1889 }
1890 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
1892 }
1893
1894 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1895 Intent[] specifics, String[] specificTypes, Intent intent,
1896 String resolvedType, int flags) {
1897 final String resultsAction = intent.getAction();
1898
1899 List<ResolveInfo> results = queryIntentActivities(
1900 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1901 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1902
1903 int specificsPos = 0;
1904 int N;
1905
1906 // todo: note that the algorithm used here is O(N^2). This
1907 // isn't a problem in our current environment, but if we start running
1908 // into situations where we have more than 5 or 10 matches then this
1909 // should probably be changed to something smarter...
1910
1911 // First we go through and resolve each of the specific items
1912 // that were supplied, taking care of removing any corresponding
1913 // duplicate items in the generic resolve list.
1914 if (specifics != null) {
1915 for (int i=0; i<specifics.length; i++) {
1916 final Intent sintent = specifics[i];
1917 if (sintent == null) {
1918 continue;
1919 }
1920
1921 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1922 String action = sintent.getAction();
1923 if (resultsAction != null && resultsAction.equals(action)) {
1924 // If this action was explicitly requested, then don't
1925 // remove things that have it.
1926 action = null;
1927 }
1928 ComponentName comp = sintent.getComponent();
1929 ResolveInfo ri = null;
1930 ActivityInfo ai = null;
1931 if (comp == null) {
1932 ri = resolveIntent(
1933 sintent,
1934 specificTypes != null ? specificTypes[i] : null,
1935 flags);
1936 if (ri == null) {
1937 continue;
1938 }
1939 if (ri == mResolveInfo) {
1940 // ACK! Must do something better with this.
1941 }
1942 ai = ri.activityInfo;
1943 comp = new ComponentName(ai.applicationInfo.packageName,
1944 ai.name);
1945 } else {
1946 ai = getActivityInfo(comp, flags);
1947 if (ai == null) {
1948 continue;
1949 }
1950 }
1951
1952 // Look for any generic query activities that are duplicates
1953 // of this specific one, and remove them from the results.
1954 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1955 N = results.size();
1956 int j;
1957 for (j=specificsPos; j<N; j++) {
1958 ResolveInfo sri = results.get(j);
1959 if ((sri.activityInfo.name.equals(comp.getClassName())
1960 && sri.activityInfo.applicationInfo.packageName.equals(
1961 comp.getPackageName()))
1962 || (action != null && sri.filter.matchAction(action))) {
1963 results.remove(j);
1964 if (Config.LOGV) Log.v(
1965 TAG, "Removing duplicate item from " + j
1966 + " due to specific " + specificsPos);
1967 if (ri == null) {
1968 ri = sri;
1969 }
1970 j--;
1971 N--;
1972 }
1973 }
1974
1975 // Add this specific item to its proper place.
1976 if (ri == null) {
1977 ri = new ResolveInfo();
1978 ri.activityInfo = ai;
1979 }
1980 results.add(specificsPos, ri);
1981 ri.specificIndex = i;
1982 specificsPos++;
1983 }
1984 }
1985
1986 // Now we go through the remaining generic results and remove any
1987 // duplicate actions that are found here.
1988 N = results.size();
1989 for (int i=specificsPos; i<N-1; i++) {
1990 final ResolveInfo rii = results.get(i);
1991 if (rii.filter == null) {
1992 continue;
1993 }
1994
1995 // Iterate over all of the actions of this result's intent
1996 // filter... typically this should be just one.
1997 final Iterator<String> it = rii.filter.actionsIterator();
1998 if (it == null) {
1999 continue;
2000 }
2001 while (it.hasNext()) {
2002 final String action = it.next();
2003 if (resultsAction != null && resultsAction.equals(action)) {
2004 // If this action was explicitly requested, then don't
2005 // remove things that have it.
2006 continue;
2007 }
2008 for (int j=i+1; j<N; j++) {
2009 final ResolveInfo rij = results.get(j);
2010 if (rij.filter != null && rij.filter.hasAction(action)) {
2011 results.remove(j);
2012 if (Config.LOGV) Log.v(
2013 TAG, "Removing duplicate item from " + j
2014 + " due to action " + action + " at " + i);
2015 j--;
2016 N--;
2017 }
2018 }
2019 }
2020
2021 // If the caller didn't request filter information, drop it now
2022 // so we don't have to marshall/unmarshall it.
2023 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2024 rii.filter = null;
2025 }
2026 }
2027
2028 // Filter out the caller activity if so requested.
2029 if (caller != null) {
2030 N = results.size();
2031 for (int i=0; i<N; i++) {
2032 ActivityInfo ainfo = results.get(i).activityInfo;
2033 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2034 && caller.getClassName().equals(ainfo.name)) {
2035 results.remove(i);
2036 break;
2037 }
2038 }
2039 }
2040
2041 // If the caller didn't request filter information,
2042 // drop them now so we don't have to
2043 // marshall/unmarshall it.
2044 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2045 N = results.size();
2046 for (int i=0; i<N; i++) {
2047 results.get(i).filter = null;
2048 }
2049 }
2050
2051 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2052 return results;
2053 }
2054
2055 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2056 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002057 ComponentName comp = intent.getComponent();
2058 if (comp != null) {
2059 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2060 ActivityInfo ai = getReceiverInfo(comp, flags);
2061 if (ai != null) {
2062 ResolveInfo ri = new ResolveInfo();
2063 ri.activityInfo = ai;
2064 list.add(ri);
2065 }
2066 return list;
2067 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002070 String pkgName = intent.getPackage();
2071 if (pkgName == null) {
2072 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2073 resolvedType, flags);
2074 }
2075 PackageParser.Package pkg = mPackages.get(pkgName);
2076 if (pkg != null) {
2077 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2078 resolvedType, flags, pkg.receivers);
2079 }
2080 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 }
2082 }
2083
2084 public ResolveInfo resolveService(Intent intent, String resolvedType,
2085 int flags) {
2086 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2087 flags);
2088 if (query != null) {
2089 if (query.size() >= 1) {
2090 // If there is more than one service with the same priority,
2091 // just arbitrarily pick the first one.
2092 return query.get(0);
2093 }
2094 }
2095 return null;
2096 }
2097
2098 public List<ResolveInfo> queryIntentServices(Intent intent,
2099 String resolvedType, int flags) {
2100 ComponentName comp = intent.getComponent();
2101 if (comp != null) {
2102 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2103 ServiceInfo si = getServiceInfo(comp, flags);
2104 if (si != null) {
2105 ResolveInfo ri = new ResolveInfo();
2106 ri.serviceInfo = si;
2107 list.add(ri);
2108 }
2109 return list;
2110 }
2111
2112 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002113 String pkgName = intent.getPackage();
2114 if (pkgName == null) {
2115 return (List<ResolveInfo>)mServices.queryIntent(intent,
2116 resolvedType, flags);
2117 }
2118 PackageParser.Package pkg = mPackages.get(pkgName);
2119 if (pkg != null) {
2120 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2121 resolvedType, flags, pkg.services);
2122 }
2123 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 }
2125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 public List<PackageInfo> getInstalledPackages(int flags) {
2128 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2129
2130 synchronized (mPackages) {
2131 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2132 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2133 while (i.hasNext()) {
2134 final PackageSetting ps = i.next();
2135 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2136 if(psPkg != null) {
2137 finalList.add(psPkg);
2138 }
2139 }
2140 }
2141 else {
2142 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2143 while (i.hasNext()) {
2144 final PackageParser.Package p = i.next();
2145 if (p.applicationInfo != null) {
2146 PackageInfo pi = generatePackageInfo(p, flags);
2147 if(pi != null) {
2148 finalList.add(pi);
2149 }
2150 }
2151 }
2152 }
2153 }
2154 return finalList;
2155 }
2156
2157 public List<ApplicationInfo> getInstalledApplications(int flags) {
2158 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2159 synchronized(mPackages) {
2160 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2161 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2162 while (i.hasNext()) {
2163 final PackageSetting ps = i.next();
2164 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2165 if(ai != null) {
2166 finalList.add(ai);
2167 }
2168 }
2169 }
2170 else {
2171 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2172 while (i.hasNext()) {
2173 final PackageParser.Package p = i.next();
2174 if (p.applicationInfo != null) {
2175 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2176 if(ai != null) {
2177 finalList.add(ai);
2178 }
2179 }
2180 }
2181 }
2182 }
2183 return finalList;
2184 }
2185
2186 public List<ApplicationInfo> getPersistentApplications(int flags) {
2187 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2188
2189 synchronized (mPackages) {
2190 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2191 while (i.hasNext()) {
2192 PackageParser.Package p = i.next();
2193 if (p.applicationInfo != null
2194 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2195 && (!mSafeMode || (p.applicationInfo.flags
2196 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2197 finalList.add(p.applicationInfo);
2198 }
2199 }
2200 }
2201
2202 return finalList;
2203 }
2204
2205 public ProviderInfo resolveContentProvider(String name, int flags) {
2206 synchronized (mPackages) {
2207 final PackageParser.Provider provider = mProviders.get(name);
2208 return provider != null
2209 && mSettings.isEnabledLP(provider.info, flags)
2210 && (!mSafeMode || (provider.info.applicationInfo.flags
2211 &ApplicationInfo.FLAG_SYSTEM) != 0)
2212 ? PackageParser.generateProviderInfo(provider, flags)
2213 : null;
2214 }
2215 }
2216
Fred Quintana718d8a22009-04-29 17:53:20 -07002217 /**
2218 * @deprecated
2219 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 public void querySyncProviders(List outNames, List outInfo) {
2221 synchronized (mPackages) {
2222 Iterator<Map.Entry<String, PackageParser.Provider>> i
2223 = mProviders.entrySet().iterator();
2224
2225 while (i.hasNext()) {
2226 Map.Entry<String, PackageParser.Provider> entry = i.next();
2227 PackageParser.Provider p = entry.getValue();
2228
2229 if (p.syncable
2230 && (!mSafeMode || (p.info.applicationInfo.flags
2231 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2232 outNames.add(entry.getKey());
2233 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2234 }
2235 }
2236 }
2237 }
2238
2239 public List<ProviderInfo> queryContentProviders(String processName,
2240 int uid, int flags) {
2241 ArrayList<ProviderInfo> finalList = null;
2242
2243 synchronized (mPackages) {
2244 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2245 while (i.hasNext()) {
2246 PackageParser.Provider p = i.next();
2247 if (p.info.authority != null
2248 && (processName == null ||
2249 (p.info.processName.equals(processName)
2250 && p.info.applicationInfo.uid == uid))
2251 && mSettings.isEnabledLP(p.info, flags)
2252 && (!mSafeMode || (p.info.applicationInfo.flags
2253 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2254 if (finalList == null) {
2255 finalList = new ArrayList<ProviderInfo>(3);
2256 }
2257 finalList.add(PackageParser.generateProviderInfo(p,
2258 flags));
2259 }
2260 }
2261 }
2262
2263 if (finalList != null) {
2264 Collections.sort(finalList, mProviderInitOrderSorter);
2265 }
2266
2267 return finalList;
2268 }
2269
2270 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2271 int flags) {
2272 synchronized (mPackages) {
2273 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2274 return PackageParser.generateInstrumentationInfo(i, flags);
2275 }
2276 }
2277
2278 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2279 int flags) {
2280 ArrayList<InstrumentationInfo> finalList =
2281 new ArrayList<InstrumentationInfo>();
2282
2283 synchronized (mPackages) {
2284 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2285 while (i.hasNext()) {
2286 PackageParser.Instrumentation p = i.next();
2287 if (targetPackage == null
2288 || targetPackage.equals(p.info.targetPackage)) {
2289 finalList.add(PackageParser.generateInstrumentationInfo(p,
2290 flags));
2291 }
2292 }
2293 }
2294
2295 return finalList;
2296 }
2297
2298 private void scanDirLI(File dir, int flags, int scanMode) {
2299 Log.d(TAG, "Scanning app dir " + dir);
2300
2301 String[] files = dir.list();
2302
2303 int i;
2304 for (i=0; i<files.length; i++) {
2305 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002306 if (!isPackageFilename(files[i])) {
2307 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002308 continue;
2309 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002310 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002312 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002313 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2314 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002315 // Delete the apk
2316 Log.w(TAG, "Cleaning up failed install of " + file);
2317 file.delete();
2318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 }
2320 }
2321
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002322 private static File getSettingsProblemFile() {
2323 File dataDir = Environment.getDataDirectory();
2324 File systemDir = new File(dataDir, "system");
2325 File fname = new File(systemDir, "uiderrors.txt");
2326 return fname;
2327 }
2328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002329 private static void reportSettingsProblem(int priority, String msg) {
2330 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002331 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 FileOutputStream out = new FileOutputStream(fname, true);
2333 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002334 SimpleDateFormat formatter = new SimpleDateFormat();
2335 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2336 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 pw.close();
2338 FileUtils.setPermissions(
2339 fname.toString(),
2340 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2341 -1, -1);
2342 } catch (java.io.IOException e) {
2343 }
2344 Log.println(priority, TAG, msg);
2345 }
2346
2347 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2348 PackageParser.Package pkg, File srcFile, int parseFlags) {
2349 if (GET_CERTIFICATES) {
2350 if (ps == null || !ps.codePath.equals(srcFile)
2351 || ps.getTimeStamp() != srcFile.lastModified()) {
2352 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2353 if (!pp.collectCertificates(pkg, parseFlags)) {
2354 mLastScanError = pp.getParseError();
2355 return false;
2356 }
2357 }
2358 }
2359 return true;
2360 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 /*
2363 * Scan a package and return the newly parsed package.
2364 * Returns null in case of errors and the error code is stored in mLastScanError
2365 */
2366 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002367 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002369 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002371 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002374 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 if (pkg == null) {
2376 mLastScanError = pp.getParseError();
2377 return null;
2378 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002379 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 PackageSetting updatedPkg;
2381 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002382 // Look to see if we already know about this package.
2383 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002384 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002385 // This package has been renamed to its original name. Let's
2386 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002387 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002388 }
2389 // If there was no original package, see one for the real package name.
2390 if (ps == null) {
2391 ps = mSettings.peekPackageLP(pkg.packageName);
2392 }
2393 // Check to see if this package could be hiding/updating a system
2394 // package. Must look for it either under the original or real
2395 // package name depending on our state.
2396 updatedPkg = mSettings.mDisabledSysPackages.get(
2397 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002399 // First check if this is a system package that may involve an update
2400 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2401 if (!ps.codePath.equals(scanFile)) {
2402 // The path has changed from what was last scanned... check the
2403 // version of the new path against what we have stored to determine
2404 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002405 if (pkg.mVersionCode < ps.versionCode) {
2406 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002407 // Ignore entry. Skip it.
2408 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2409 + "ignored: updated version " + ps.versionCode
2410 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002411 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2412 return null;
2413 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002414 // The current app on the system partion is better than
2415 // what we have updated to on the data partition; switch
2416 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002417 // At this point, its safely assumed that package installation for
2418 // apps in system partition will go through. If not there won't be a working
2419 // version of the app
2420 synchronized (mPackages) {
2421 // Just remove the loaded entries from package lists.
2422 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002423 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002424 Log.w(TAG, "Package " + ps.name + " at " + scanFile
2425 + "reverting from " + ps.codePathString
2426 + ": new version " + pkg.mVersionCode
2427 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002428 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2429 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002430 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 }
2433 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002434 if (updatedPkg != null) {
2435 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2436 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2437 }
2438 // Verify certificates against what was last scanned
2439 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2440 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2441 return null;
2442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 // The apk is forward locked (not public) if its code and resources
2444 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002445 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002447 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002448 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002449
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002450 String codePath = null;
2451 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002452 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2453 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002454 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002455 } else {
2456 // Should not happen at all. Just log an error.
2457 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2458 }
2459 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002460 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002461 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002462 codePath = pkg.mScanPath;
2463 // Set application objects path explicitly.
2464 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002466 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 }
2468
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002469 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2470 String destCodePath, String destResPath) {
2471 pkg.mPath = pkg.mScanPath = destCodePath;
2472 pkg.applicationInfo.sourceDir = destCodePath;
2473 pkg.applicationInfo.publicSourceDir = destResPath;
2474 }
2475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 private static String fixProcessName(String defProcessName,
2477 String processName, int uid) {
2478 if (processName == null) {
2479 return defProcessName;
2480 }
2481 return processName;
2482 }
2483
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002484 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2486 if (pkg.mSignatures != null) {
2487 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2488 updateSignature)) {
2489 Log.e(TAG, "Package " + pkg.packageName
2490 + " signatures do not match the previously installed version; ignoring!");
2491 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2492 return false;
2493 }
2494
2495 if (pkgSetting.sharedUser != null) {
2496 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2497 pkg.mSignatures, updateSignature)) {
2498 Log.e(TAG, "Package " + pkg.packageName
2499 + " has no signatures that match those in shared user "
2500 + pkgSetting.sharedUser.name + "; ignoring!");
2501 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2502 return false;
2503 }
2504 }
2505 } else {
2506 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2507 }
2508 return true;
2509 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002510
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002511 public boolean performDexOpt(String packageName) {
2512 if (!mNoDexOpt) {
2513 return false;
2514 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002515
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002516 PackageParser.Package p;
2517 synchronized (mPackages) {
2518 p = mPackages.get(packageName);
2519 if (p == null || p.mDidDexOpt) {
2520 return false;
2521 }
2522 }
2523 synchronized (mInstallLock) {
2524 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2525 }
2526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002527
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002528 static final int DEX_OPT_SKIPPED = 0;
2529 static final int DEX_OPT_PERFORMED = 1;
2530 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002531
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002532 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2533 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002534 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002535 String path = pkg.mScanPath;
2536 int ret = 0;
2537 try {
2538 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002539 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002540 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002541 pkg.mDidDexOpt = true;
2542 performed = true;
2543 }
2544 } catch (FileNotFoundException e) {
2545 Log.w(TAG, "Apk not found for dexopt: " + path);
2546 ret = -1;
2547 } catch (IOException e) {
2548 Log.w(TAG, "Exception reading apk: " + path, e);
2549 ret = -1;
2550 }
2551 if (ret < 0) {
2552 //error from installer
2553 return DEX_OPT_FAILED;
2554 }
2555 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002556
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002557 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2558 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002559
2560 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2561 return Environment.isEncryptedFilesystemEnabled() &&
2562 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2563 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002564
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002565 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2566 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2567 Log.w(TAG, "Unable to update from " + oldPkg.name
2568 + " to " + newPkg.packageName
2569 + ": old package not in system partition");
2570 return false;
2571 } else if (mPackages.get(oldPkg.name) != null) {
2572 Log.w(TAG, "Unable to update from " + oldPkg.name
2573 + " to " + newPkg.packageName
2574 + ": old package still exists");
2575 return false;
2576 }
2577 return true;
2578 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002579
2580 private File getDataPathForPackage(PackageParser.Package pkg) {
2581 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2582 File dataPath;
2583 if (useEncryptedFSDir) {
2584 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2585 } else {
2586 dataPath = new File(mAppDataDir, pkg.packageName);
2587 }
2588 return dataPath;
2589 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002590
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2592 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002593 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002594 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2595 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002596 // Bail out. The resource and code paths haven't been set.
2597 Log.w(TAG, " Code and resource paths haven't been set correctly");
2598 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2599 return null;
2600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 mScanningPath = scanFile;
2602 if (pkg == null) {
2603 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2604 return null;
2605 }
2606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2608 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2609 }
2610
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002611 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 synchronized (mPackages) {
2613 if (mAndroidApplication != null) {
2614 Log.w(TAG, "*************************************************");
2615 Log.w(TAG, "Core android package being redefined. Skipping.");
2616 Log.w(TAG, " file=" + mScanningPath);
2617 Log.w(TAG, "*************************************************");
2618 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2619 return null;
2620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 // Set up information for our fall-back user intent resolution
2623 // activity.
2624 mPlatformPackage = pkg;
2625 pkg.mVersionCode = mSdkVersion;
2626 mAndroidApplication = pkg.applicationInfo;
2627 mResolveActivity.applicationInfo = mAndroidApplication;
2628 mResolveActivity.name = ResolverActivity.class.getName();
2629 mResolveActivity.packageName = mAndroidApplication.packageName;
2630 mResolveActivity.processName = mAndroidApplication.processName;
2631 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2632 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2633 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2634 mResolveActivity.exported = true;
2635 mResolveActivity.enabled = true;
2636 mResolveInfo.activityInfo = mResolveActivity;
2637 mResolveInfo.priority = 0;
2638 mResolveInfo.preferredOrder = 0;
2639 mResolveInfo.match = 0;
2640 mResolveComponentName = new ComponentName(
2641 mAndroidApplication.packageName, mResolveActivity.name);
2642 }
2643 }
2644
2645 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002646 TAG, "Scanning package " + pkg.packageName);
2647 if (mPackages.containsKey(pkg.packageName)
2648 || mSharedLibraries.containsKey(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 Log.w(TAG, "*************************************************");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002650 Log.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 + " already installed. Skipping duplicate.");
2652 Log.w(TAG, "*************************************************");
2653 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2654 return null;
2655 }
2656
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002657 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002658 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2659 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 SharedUserSetting suid = null;
2662 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002665
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002666 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2667 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002668 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002669 pkg.mRealPackage = null;
2670 pkg.mAdoptPermissions = null;
2671 }
2672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 synchronized (mPackages) {
2674 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002675 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2676 if (mTmpSharedLibraries == null ||
2677 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2678 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2679 }
2680 int num = 0;
2681 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2682 for (int i=0; i<N; i++) {
2683 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 if (file == null) {
2685 Log.e(TAG, "Package " + pkg.packageName
2686 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002687 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2689 return null;
2690 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002691 mTmpSharedLibraries[num] = file;
2692 num++;
2693 }
2694 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2695 for (int i=0; i<N; i++) {
2696 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2697 if (file == null) {
2698 Log.w(TAG, "Package " + pkg.packageName
2699 + " desires unavailable shared library "
2700 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2701 } else {
2702 mTmpSharedLibraries[num] = file;
2703 num++;
2704 }
2705 }
2706 if (num > 0) {
2707 pkg.usesLibraryFiles = new String[num];
2708 System.arraycopy(mTmpSharedLibraries, 0,
2709 pkg.usesLibraryFiles, 0, num);
2710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002711
Dianne Hackborn49237342009-08-27 20:08:01 -07002712 if (pkg.reqFeatures != null) {
2713 N = pkg.reqFeatures.size();
2714 for (int i=0; i<N; i++) {
2715 FeatureInfo fi = pkg.reqFeatures.get(i);
2716 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2717 // Don't care.
2718 continue;
2719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002720
Dianne Hackborn49237342009-08-27 20:08:01 -07002721 if (fi.name != null) {
2722 if (mAvailableFeatures.get(fi.name) == null) {
2723 Log.e(TAG, "Package " + pkg.packageName
2724 + " requires unavailable feature "
2725 + fi.name + "; failing!");
2726 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2727 return null;
2728 }
2729 }
2730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 }
2732 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 if (pkg.mSharedUserId != null) {
2735 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2736 pkg.applicationInfo.flags, true);
2737 if (suid == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002738 Log.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 + " for shared user failed");
2740 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2741 return null;
2742 }
2743 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2744 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2745 + suid.userId + "): packages=" + suid.packages);
2746 }
2747 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002748
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002749 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002750 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002751 Log.w(TAG, "WAITING FOR DEBUGGER");
2752 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002753 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2754 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002755 }
2756 }
2757
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002758 // Check if we are renaming from an original package name.
2759 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002760 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002761 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002762 // This package may need to be renamed to a previously
2763 // installed name. Let's check on that...
2764 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002765 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002766 // This package had originally been installed as the
2767 // original name, and we have already taken care of
2768 // transitioning to the new one. Just update the new
2769 // one to continue using the old name.
2770 realName = pkg.mRealPackage;
2771 if (!pkg.packageName.equals(renamed)) {
2772 // Callers into this function may have already taken
2773 // care of renaming the package; only do it here if
2774 // it is not already done.
2775 pkg.setPackageName(renamed);
2776 }
2777
Dianne Hackbornc1552392010-03-03 16:19:01 -08002778 } else {
2779 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2780 if ((origPackage=mSettings.peekPackageLP(
2781 pkg.mOriginalPackages.get(i))) != null) {
2782 // We do have the package already installed under its
2783 // original name... should we use it?
2784 if (!verifyPackageUpdate(origPackage, pkg)) {
2785 // New package is not compatible with original.
2786 origPackage = null;
2787 continue;
2788 } else if (origPackage.sharedUser != null) {
2789 // Make sure uid is compatible between packages.
2790 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2791 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2792 + " to " + pkg.packageName + ": old uid "
2793 + origPackage.sharedUser.name
2794 + " differs from " + pkg.mSharedUserId);
2795 origPackage = null;
2796 continue;
2797 }
2798 } else {
2799 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2800 + pkg.packageName + " to old name " + origPackage.name);
2801 }
2802 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002803 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002804 }
2805 }
2806 }
2807
2808 if (mTransferedPackages.contains(pkg.packageName)) {
2809 Log.w(TAG, "Package " + pkg.packageName
2810 + " was transferred to another, but its .apk remains");
2811 }
2812
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002813 // Just create the setting, don't add it yet. For already existing packages
2814 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002815 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 destResourceFile, pkg.applicationInfo.flags, true, false);
2817 if (pkgSetting == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002818 Log.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2820 return null;
2821 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002822
2823 if (pkgSetting.origPackage != null) {
2824 // If we are first transitioning from an original package,
2825 // fix up the new package's name now. We need to do this after
2826 // looking up the package under its new name, so getPackageLP
2827 // can take care of fiddling things correctly.
2828 pkg.setPackageName(origPackage.name);
2829
2830 // File a report about this.
2831 String msg = "New package " + pkgSetting.realName
2832 + " renamed to replace old package " + pkgSetting.name;
2833 reportSettingsProblem(Log.WARN, msg);
2834
2835 // Make a note of it.
2836 mTransferedPackages.add(origPackage.name);
2837
2838 // No longer need to retain this.
2839 pkgSetting.origPackage = null;
2840 }
2841
2842 if (realName != null) {
2843 // Make a note of it.
2844 mTransferedPackages.add(pkg.packageName);
2845 }
2846
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002847 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2849 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 pkg.applicationInfo.uid = pkgSetting.userId;
2852 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002853
2854 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2856 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2857 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2858 return null;
2859 }
2860 // The signature has changed, but this package is in the system
2861 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002862 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 // However... if this package is part of a shared user, but it
2864 // doesn't match the signature of the shared user, let's fail.
2865 // What this means is that you can't change the signatures
2866 // associated with an overall shared user, which doesn't seem all
2867 // that unreasonable.
2868 if (pkgSetting.sharedUser != null) {
2869 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2870 pkg.mSignatures, false)) {
2871 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2872 return null;
2873 }
2874 }
2875 removeExisting = true;
2876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002877
The Android Open Source Project10592532009-03-18 17:39:46 -07002878 // Verify that this new package doesn't have any content providers
2879 // that conflict with existing packages. Only do this if the
2880 // package isn't already installed, since we don't want to break
2881 // things that are installed.
2882 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2883 int N = pkg.providers.size();
2884 int i;
2885 for (i=0; i<N; i++) {
2886 PackageParser.Provider p = pkg.providers.get(i);
2887 String names[] = p.info.authority.split(";");
2888 for (int j = 0; j < names.length; j++) {
2889 if (mProviders.containsKey(names[j])) {
2890 PackageParser.Provider other = mProviders.get(names[j]);
2891 Log.w(TAG, "Can't install because provider name " + names[j] +
2892 " (in package " + pkg.applicationInfo.packageName +
2893 ") is already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002894 + ((other != null && other.getComponentName() != null)
2895 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project10592532009-03-18 17:39:46 -07002896 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2897 return null;
2898 }
2899 }
2900 }
2901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 }
2903
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002904 final String pkgName = pkg.packageName;
2905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002907 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002909 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 if (ret != 0) {
2911 String msg = "System package " + pkg.packageName
2912 + " could not have data directory erased after signature change.";
2913 reportSettingsProblem(Log.WARN, msg);
2914 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2915 return null;
2916 }
2917 }
2918 Log.w(TAG, "System package " + pkg.packageName
2919 + " signature changed: existing data removed.");
2920 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002922
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002923 if (pkg.mAdoptPermissions != null) {
2924 // This package wants to adopt ownership of permissions from
2925 // another package.
2926 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2927 String origName = pkg.mAdoptPermissions.get(i);
2928 PackageSetting orig = mSettings.peekPackageLP(origName);
2929 if (orig != null) {
2930 if (verifyPackageUpdate(orig, pkg)) {
2931 Log.i(TAG, "Adopting permissions from "
2932 + origName + " to " + pkg.packageName);
2933 mSettings.transferPermissions(origName, pkg.packageName);
2934 }
2935 }
2936 }
2937 }
2938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 long scanFileTime = scanFile.lastModified();
2940 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2941 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2942 pkg.applicationInfo.processName = fixProcessName(
2943 pkg.applicationInfo.packageName,
2944 pkg.applicationInfo.processName,
2945 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946
2947 File dataPath;
2948 if (mPlatformPackage == pkg) {
2949 // The system package is special.
2950 dataPath = new File (Environment.getDataDirectory(), "system");
2951 pkg.applicationInfo.dataDir = dataPath.getPath();
2952 } else {
2953 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002954 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002955 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002956
2957 boolean uidError = false;
2958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 if (dataPath.exists()) {
2960 mOutPermissions[1] = 0;
2961 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2962 if (mOutPermissions[1] == pkg.applicationInfo.uid
2963 || !Process.supportsProcesses()) {
2964 pkg.applicationInfo.dataDir = dataPath.getPath();
2965 } else {
2966 boolean recovered = false;
2967 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2968 // If this is a system app, we can at least delete its
2969 // current data so the application will still work.
2970 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002971 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002972 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 // Old data gone!
2974 String msg = "System package " + pkg.packageName
2975 + " has changed from uid: "
2976 + mOutPermissions[1] + " to "
2977 + pkg.applicationInfo.uid + "; old data erased";
2978 reportSettingsProblem(Log.WARN, msg);
2979 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002982 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 pkg.applicationInfo.uid);
2984 if (ret == -1) {
2985 // Ack should not happen!
2986 msg = "System package " + pkg.packageName
2987 + " could not have data directory re-created after delete.";
2988 reportSettingsProblem(Log.WARN, msg);
2989 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2990 return null;
2991 }
2992 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 if (!recovered) {
2995 mHasSystemUidErrors = true;
2996 }
2997 }
2998 if (!recovered) {
2999 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3000 + pkg.applicationInfo.uid + "/fs_"
3001 + mOutPermissions[1];
3002 String msg = "Package " + pkg.packageName
3003 + " has mismatched uid: "
3004 + mOutPermissions[1] + " on disk, "
3005 + pkg.applicationInfo.uid + " in settings";
3006 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003007 mSettings.mReadMessages.append(msg);
3008 mSettings.mReadMessages.append('\n');
3009 uidError = true;
3010 if (!pkgSetting.uidError) {
3011 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 }
3014 }
3015 }
3016 pkg.applicationInfo.dataDir = dataPath.getPath();
3017 } else {
3018 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3019 Log.v(TAG, "Want this data dir: " + dataPath);
3020 //invoke installer to do the actual installation
3021 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003022 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 pkg.applicationInfo.uid);
3024 if(ret < 0) {
3025 // Error from installer
3026 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3027 return null;
3028 }
3029 } else {
3030 dataPath.mkdirs();
3031 if (dataPath.exists()) {
3032 FileUtils.setPermissions(
3033 dataPath.toString(),
3034 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3035 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3036 }
3037 }
3038 if (dataPath.exists()) {
3039 pkg.applicationInfo.dataDir = dataPath.getPath();
3040 } else {
3041 Log.w(TAG, "Unable to create data directory: " + dataPath);
3042 pkg.applicationInfo.dataDir = null;
3043 }
3044 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003045
3046 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 }
3048
3049 // Perform shared library installation and dex validation and
3050 // optimization, if this is not a system app.
3051 if (mInstaller != null) {
3052 String path = scanFile.getPath();
3053 if (scanFileNewer) {
3054 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003055 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3056 if (err != PackageManager.INSTALL_SUCCEEDED) {
3057 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 return null;
3059 }
3060 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003061 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003062
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003063 if ((scanMode&SCAN_NO_DEX) == 0) {
3064 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3066 return null;
3067 }
3068 }
3069 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 if (mFactoryTest && pkg.requestedPermissions.contains(
3072 android.Manifest.permission.FACTORY_TEST)) {
3073 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3074 }
3075
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003076 // Request the ActivityManager to kill the process(only for existing packages)
3077 // so that we do not end up in a confused state while the user is still using the older
3078 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003079 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003080 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003081 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003082 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003085 // We don't expect installation to fail beyond this point,
3086 if ((scanMode&SCAN_MONITOR) != 0) {
3087 mAppDirs.put(pkg.mPath, pkg);
3088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003090 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003092 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003093 // Make sure we don't accidentally delete its data.
3094 mSettings.mPackagesToBeCleaned.remove(pkgName);
3095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 int N = pkg.providers.size();
3097 StringBuilder r = null;
3098 int i;
3099 for (i=0; i<N; i++) {
3100 PackageParser.Provider p = pkg.providers.get(i);
3101 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3102 p.info.processName, pkg.applicationInfo.uid);
3103 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3104 p.info.name), p);
3105 p.syncable = p.info.isSyncable;
3106 String names[] = p.info.authority.split(";");
3107 p.info.authority = null;
3108 for (int j = 0; j < names.length; j++) {
3109 if (j == 1 && p.syncable) {
3110 // We only want the first authority for a provider to possibly be
3111 // syncable, so if we already added this provider using a different
3112 // authority clear the syncable flag. We copy the provider before
3113 // changing it because the mProviders object contains a reference
3114 // to a provider that we don't want to change.
3115 // Only do this for the second authority since the resulting provider
3116 // object can be the same for all future authorities for this provider.
3117 p = new PackageParser.Provider(p);
3118 p.syncable = false;
3119 }
3120 if (!mProviders.containsKey(names[j])) {
3121 mProviders.put(names[j], p);
3122 if (p.info.authority == null) {
3123 p.info.authority = names[j];
3124 } else {
3125 p.info.authority = p.info.authority + ";" + names[j];
3126 }
3127 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3128 Log.d(TAG, "Registered content provider: " + names[j] +
3129 ", className = " + p.info.name +
3130 ", isSyncable = " + p.info.isSyncable);
3131 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07003132 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 Log.w(TAG, "Skipping provider name " + names[j] +
3134 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07003135 "): name already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003136 + ((other != null && other.getComponentName() != null)
3137 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 }
3139 }
3140 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3141 if (r == null) {
3142 r = new StringBuilder(256);
3143 } else {
3144 r.append(' ');
3145 }
3146 r.append(p.info.name);
3147 }
3148 }
3149 if (r != null) {
3150 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3151 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 N = pkg.services.size();
3154 r = null;
3155 for (i=0; i<N; i++) {
3156 PackageParser.Service s = pkg.services.get(i);
3157 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3158 s.info.processName, pkg.applicationInfo.uid);
3159 mServices.addService(s);
3160 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3161 if (r == null) {
3162 r = new StringBuilder(256);
3163 } else {
3164 r.append(' ');
3165 }
3166 r.append(s.info.name);
3167 }
3168 }
3169 if (r != null) {
3170 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3171 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 N = pkg.receivers.size();
3174 r = null;
3175 for (i=0; i<N; i++) {
3176 PackageParser.Activity a = pkg.receivers.get(i);
3177 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3178 a.info.processName, pkg.applicationInfo.uid);
3179 mReceivers.addActivity(a, "receiver");
3180 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3181 if (r == null) {
3182 r = new StringBuilder(256);
3183 } else {
3184 r.append(' ');
3185 }
3186 r.append(a.info.name);
3187 }
3188 }
3189 if (r != null) {
3190 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3191 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 N = pkg.activities.size();
3194 r = null;
3195 for (i=0; i<N; i++) {
3196 PackageParser.Activity a = pkg.activities.get(i);
3197 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3198 a.info.processName, pkg.applicationInfo.uid);
3199 mActivities.addActivity(a, "activity");
3200 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3201 if (r == null) {
3202 r = new StringBuilder(256);
3203 } else {
3204 r.append(' ');
3205 }
3206 r.append(a.info.name);
3207 }
3208 }
3209 if (r != null) {
3210 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 N = pkg.permissionGroups.size();
3214 r = null;
3215 for (i=0; i<N; i++) {
3216 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3217 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3218 if (cur == null) {
3219 mPermissionGroups.put(pg.info.name, pg);
3220 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3221 if (r == null) {
3222 r = new StringBuilder(256);
3223 } else {
3224 r.append(' ');
3225 }
3226 r.append(pg.info.name);
3227 }
3228 } else {
3229 Log.w(TAG, "Permission group " + pg.info.name + " from package "
3230 + pg.info.packageName + " ignored: original from "
3231 + cur.info.packageName);
3232 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3233 if (r == null) {
3234 r = new StringBuilder(256);
3235 } else {
3236 r.append(' ');
3237 }
3238 r.append("DUP:");
3239 r.append(pg.info.name);
3240 }
3241 }
3242 }
3243 if (r != null) {
3244 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3245 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 N = pkg.permissions.size();
3248 r = null;
3249 for (i=0; i<N; i++) {
3250 PackageParser.Permission p = pkg.permissions.get(i);
3251 HashMap<String, BasePermission> permissionMap =
3252 p.tree ? mSettings.mPermissionTrees
3253 : mSettings.mPermissions;
3254 p.group = mPermissionGroups.get(p.info.group);
3255 if (p.info.group == null || p.group != null) {
3256 BasePermission bp = permissionMap.get(p.info.name);
3257 if (bp == null) {
3258 bp = new BasePermission(p.info.name, p.info.packageName,
3259 BasePermission.TYPE_NORMAL);
3260 permissionMap.put(p.info.name, bp);
3261 }
3262 if (bp.perm == null) {
3263 if (bp.sourcePackage == null
3264 || bp.sourcePackage.equals(p.info.packageName)) {
3265 BasePermission tree = findPermissionTreeLP(p.info.name);
3266 if (tree == null
3267 || tree.sourcePackage.equals(p.info.packageName)) {
3268 bp.perm = p;
3269 bp.uid = pkg.applicationInfo.uid;
3270 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3271 if (r == null) {
3272 r = new StringBuilder(256);
3273 } else {
3274 r.append(' ');
3275 }
3276 r.append(p.info.name);
3277 }
3278 } else {
3279 Log.w(TAG, "Permission " + p.info.name + " from package "
3280 + p.info.packageName + " ignored: base tree "
3281 + tree.name + " is from package "
3282 + tree.sourcePackage);
3283 }
3284 } else {
3285 Log.w(TAG, "Permission " + p.info.name + " from package "
3286 + p.info.packageName + " ignored: original from "
3287 + bp.sourcePackage);
3288 }
3289 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3290 if (r == null) {
3291 r = new StringBuilder(256);
3292 } else {
3293 r.append(' ');
3294 }
3295 r.append("DUP:");
3296 r.append(p.info.name);
3297 }
3298 } else {
3299 Log.w(TAG, "Permission " + p.info.name + " from package "
3300 + p.info.packageName + " ignored: no group "
3301 + p.group);
3302 }
3303 }
3304 if (r != null) {
3305 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3306 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 N = pkg.instrumentation.size();
3309 r = null;
3310 for (i=0; i<N; i++) {
3311 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3312 a.info.packageName = pkg.applicationInfo.packageName;
3313 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3314 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3315 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003316 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3318 if (r == null) {
3319 r = new StringBuilder(256);
3320 } else {
3321 r.append(' ');
3322 }
3323 r.append(a.info.name);
3324 }
3325 }
3326 if (r != null) {
3327 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003329
Dianne Hackborn854060af2009-07-09 18:14:31 -07003330 if (pkg.protectedBroadcasts != null) {
3331 N = pkg.protectedBroadcasts.size();
3332 for (i=0; i<N; i++) {
3333 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3334 }
3335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 pkgSetting.setTimeStamp(scanFileTime);
3338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 return pkg;
3341 }
3342
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003343 private void killApplication(String pkgName, int uid) {
3344 // Request the ActivityManager to kill the process(only for existing packages)
3345 // so that we do not end up in a confused state while the user is still using the older
3346 // version of the application while the new one gets installed.
3347 IActivityManager am = ActivityManagerNative.getDefault();
3348 if (am != null) {
3349 try {
3350 am.killApplicationWithUid(pkgName, uid);
3351 } catch (RemoteException e) {
3352 }
3353 }
3354 }
3355
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003356 // The following constants are returned by cachePackageSharedLibsForAbiLI
3357 // to indicate if native shared libraries were found in the package.
3358 // Values are:
3359 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3360 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3361 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3362 // in package (and not installed)
3363 //
3364 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3365 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3366 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003368 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3369 // and automatically copy them to /data/data/<appname>/lib if present.
3370 //
3371 // NOTE: this method may throw an IOException if the library cannot
3372 // be copied to its final destination, e.g. if there isn't enough
3373 // room left on the data partition, or a ZipException if the package
3374 // file is malformed.
3375 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003376 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3377 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003378 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3379 final String apkLib = "lib/";
3380 final int apkLibLen = apkLib.length();
3381 final int cpuAbiLen = cpuAbi.length();
3382 final String libPrefix = "lib";
3383 final int libPrefixLen = libPrefix.length();
3384 final String libSuffix = ".so";
3385 final int libSuffixLen = libSuffix.length();
3386 boolean hasNativeLibraries = false;
3387 boolean installedNativeLibraries = false;
3388
3389 // the minimum length of a valid native shared library of the form
3390 // lib/<something>/lib<name>.so.
3391 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3392
3393 ZipFile zipFile = new ZipFile(scanFile);
3394 Enumeration<ZipEntry> entries =
3395 (Enumeration<ZipEntry>) zipFile.entries();
3396
3397 while (entries.hasMoreElements()) {
3398 ZipEntry entry = entries.nextElement();
3399 // skip directories
3400 if (entry.isDirectory()) {
3401 continue;
3402 }
3403 String entryName = entry.getName();
3404
3405 // check that the entry looks like lib/<something>/lib<name>.so
3406 // here, but don't check the ABI just yet.
3407 //
3408 // - must be sufficiently long
3409 // - must end with libSuffix, i.e. ".so"
3410 // - must start with apkLib, i.e. "lib/"
3411 if (entryName.length() < minEntryLen ||
3412 !entryName.endsWith(libSuffix) ||
3413 !entryName.startsWith(apkLib) ) {
3414 continue;
3415 }
3416
3417 // file name must start with libPrefix, i.e. "lib"
3418 int lastSlash = entryName.lastIndexOf('/');
3419
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003420 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003421 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3422 continue;
3423 }
3424
3425 hasNativeLibraries = true;
3426
3427 // check the cpuAbi now, between lib/ and /lib<name>.so
3428 //
3429 if (lastSlash != apkLibLen + cpuAbiLen ||
3430 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3431 continue;
3432
3433 // extract the library file name, ensure it doesn't contain
3434 // weird characters. we're guaranteed here that it doesn't contain
3435 // a directory separator though.
3436 String libFileName = entryName.substring(lastSlash+1);
3437 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3438 continue;
3439 }
3440
3441 installedNativeLibraries = true;
3442
3443 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3444 File.separator + libFileName;
3445 File sharedLibraryFile = new File(sharedLibraryFilePath);
3446 if (! sharedLibraryFile.exists() ||
3447 sharedLibraryFile.length() != entry.getSize() ||
3448 sharedLibraryFile.lastModified() != entry.getTime()) {
3449 if (Config.LOGD) {
3450 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003452 if (mInstaller == null) {
3453 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003454 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003455 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003456 sharedLibraryFile);
3457 }
3458 }
3459 if (!hasNativeLibraries)
3460 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3461
3462 if (!installedNativeLibraries)
3463 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3464
3465 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3466 }
3467
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003468 // Find the gdbserver executable program in a package at
3469 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3470 //
3471 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3472 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3473 //
3474 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3475 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3476 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3477 final String GDBSERVER = "gdbserver";
3478 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3479
3480 ZipFile zipFile = new ZipFile(scanFile);
3481 Enumeration<ZipEntry> entries =
3482 (Enumeration<ZipEntry>) zipFile.entries();
3483
3484 while (entries.hasMoreElements()) {
3485 ZipEntry entry = entries.nextElement();
3486 // skip directories
3487 if (entry.isDirectory()) {
3488 continue;
3489 }
3490 String entryName = entry.getName();
3491
3492 if (!entryName.equals(apkGdbServerPath)) {
3493 continue;
3494 }
3495
3496 String installGdbServerPath = installGdbServerDir.getPath() +
3497 "/" + GDBSERVER;
3498 File installGdbServerFile = new File(installGdbServerPath);
3499 if (! installGdbServerFile.exists() ||
3500 installGdbServerFile.length() != entry.getSize() ||
3501 installGdbServerFile.lastModified() != entry.getTime()) {
3502 if (Config.LOGD) {
3503 Log.d(TAG, "Caching gdbserver " + entry.getName());
3504 }
3505 if (mInstaller == null) {
3506 installGdbServerDir.mkdir();
3507 }
3508 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3509 installGdbServerFile);
3510 }
3511 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3512 }
3513 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3514 }
3515
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003516 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3517 // and copy them to /data/data/<appname>/lib.
3518 //
3519 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3520 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3521 // one if ro.product.cpu.abi2 is defined.
3522 //
3523 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3524 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003525 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003526 try {
3527 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3528
3529 // some architectures are capable of supporting several CPU ABIs
3530 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3531 // this is indicated by the definition of the ro.product.cpu.abi2
3532 // system property.
3533 //
3534 // only scan the package twice in case of ABI mismatch
3535 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003536 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003537 if (cpuAbi2 != null) {
3538 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003540
3541 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3542 Log.w(TAG,"Native ABI mismatch from package file");
3543 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003545
3546 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3547 cpuAbi = cpuAbi2;
3548 }
3549 }
3550
3551 // for debuggable packages, also extract gdbserver from lib/<abi>
3552 // into /data/data/<appname>/lib too.
3553 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3554 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3555 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3556 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3557 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003560 } catch (ZipException e) {
3561 Log.w(TAG, "Failed to extract data from package file", e);
3562 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003564 Log.w(TAG, "Failed to cache package shared libs", e);
3565 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003567 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 }
3569
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003570 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003572 File binaryDir,
3573 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 InputStream inputStream = zipFile.getInputStream(entry);
3575 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003576 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003578 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 // now need to be left as world readable and owned by the system.
3580 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3581 ! tempFile.setLastModified(entry.getTime()) ||
3582 FileUtils.setPermissions(tempFilePath,
3583 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003584 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003586 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 // Failed to properly write file.
3588 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003589 throw new IOException("Couldn't create cached binary "
3590 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 }
3592 } finally {
3593 inputStream.close();
3594 }
3595 }
3596
3597 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3598 if (chatty && Config.LOGD) Log.d(
3599 TAG, "Removing package " + pkg.applicationInfo.packageName );
3600
3601 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 mPackages.remove(pkg.applicationInfo.packageName);
3605 if (pkg.mPath != null) {
3606 mAppDirs.remove(pkg.mPath);
3607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 PackageSetting ps = (PackageSetting)pkg.mExtras;
3610 if (ps != null && ps.sharedUser != null) {
3611 // XXX don't do this until the data is removed.
3612 if (false) {
3613 ps.sharedUser.packages.remove(ps);
3614 if (ps.sharedUser.packages.size() == 0) {
3615 // Remove.
3616 }
3617 }
3618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 int N = pkg.providers.size();
3621 StringBuilder r = null;
3622 int i;
3623 for (i=0; i<N; i++) {
3624 PackageParser.Provider p = pkg.providers.get(i);
3625 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3626 p.info.name));
3627 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 /* The is another ContentProvider with this authority when
3630 * this app was installed so this authority is null,
3631 * Ignore it as we don't have to unregister the provider.
3632 */
3633 continue;
3634 }
3635 String names[] = p.info.authority.split(";");
3636 for (int j = 0; j < names.length; j++) {
3637 if (mProviders.get(names[j]) == p) {
3638 mProviders.remove(names[j]);
3639 if (chatty && Config.LOGD) Log.d(
3640 TAG, "Unregistered content provider: " + names[j] +
3641 ", className = " + p.info.name +
3642 ", isSyncable = " + p.info.isSyncable);
3643 }
3644 }
3645 if (chatty) {
3646 if (r == null) {
3647 r = new StringBuilder(256);
3648 } else {
3649 r.append(' ');
3650 }
3651 r.append(p.info.name);
3652 }
3653 }
3654 if (r != null) {
3655 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 N = pkg.services.size();
3659 r = null;
3660 for (i=0; i<N; i++) {
3661 PackageParser.Service s = pkg.services.get(i);
3662 mServices.removeService(s);
3663 if (chatty) {
3664 if (r == null) {
3665 r = new StringBuilder(256);
3666 } else {
3667 r.append(' ');
3668 }
3669 r.append(s.info.name);
3670 }
3671 }
3672 if (r != null) {
3673 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3674 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 N = pkg.receivers.size();
3677 r = null;
3678 for (i=0; i<N; i++) {
3679 PackageParser.Activity a = pkg.receivers.get(i);
3680 mReceivers.removeActivity(a, "receiver");
3681 if (chatty) {
3682 if (r == null) {
3683 r = new StringBuilder(256);
3684 } else {
3685 r.append(' ');
3686 }
3687 r.append(a.info.name);
3688 }
3689 }
3690 if (r != null) {
3691 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 N = pkg.activities.size();
3695 r = null;
3696 for (i=0; i<N; i++) {
3697 PackageParser.Activity a = pkg.activities.get(i);
3698 mActivities.removeActivity(a, "activity");
3699 if (chatty) {
3700 if (r == null) {
3701 r = new StringBuilder(256);
3702 } else {
3703 r.append(' ');
3704 }
3705 r.append(a.info.name);
3706 }
3707 }
3708 if (r != null) {
3709 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 N = pkg.permissions.size();
3713 r = null;
3714 for (i=0; i<N; i++) {
3715 PackageParser.Permission p = pkg.permissions.get(i);
3716 boolean tree = false;
3717 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3718 if (bp == null) {
3719 tree = true;
3720 bp = mSettings.mPermissionTrees.get(p.info.name);
3721 }
3722 if (bp != null && bp.perm == p) {
3723 if (bp.type != BasePermission.TYPE_BUILTIN) {
3724 if (tree) {
3725 mSettings.mPermissionTrees.remove(p.info.name);
3726 } else {
3727 mSettings.mPermissions.remove(p.info.name);
3728 }
3729 } else {
3730 bp.perm = null;
3731 }
3732 if (chatty) {
3733 if (r == null) {
3734 r = new StringBuilder(256);
3735 } else {
3736 r.append(' ');
3737 }
3738 r.append(p.info.name);
3739 }
3740 }
3741 }
3742 if (r != null) {
3743 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 N = pkg.instrumentation.size();
3747 r = null;
3748 for (i=0; i<N; i++) {
3749 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003750 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 if (chatty) {
3752 if (r == null) {
3753 r = new StringBuilder(256);
3754 } else {
3755 r.append(' ');
3756 }
3757 r.append(a.info.name);
3758 }
3759 }
3760 if (r != null) {
3761 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3762 }
3763 }
3764 }
3765
3766 private static final boolean isPackageFilename(String name) {
3767 return name != null && name.endsWith(".apk");
3768 }
3769
3770 private void updatePermissionsLP() {
3771 // Make sure there are no dangling permission trees.
3772 Iterator<BasePermission> it = mSettings.mPermissionTrees
3773 .values().iterator();
3774 while (it.hasNext()) {
3775 BasePermission bp = it.next();
3776 if (bp.perm == null) {
3777 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3778 + " from package " + bp.sourcePackage);
3779 it.remove();
3780 }
3781 }
3782
3783 // Make sure all dynamic permissions have been assigned to a package,
3784 // and make sure there are no dangling permissions.
3785 it = mSettings.mPermissions.values().iterator();
3786 while (it.hasNext()) {
3787 BasePermission bp = it.next();
3788 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3789 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3790 + bp.name + " pkg=" + bp.sourcePackage
3791 + " info=" + bp.pendingInfo);
3792 if (bp.perm == null && bp.pendingInfo != null) {
3793 BasePermission tree = findPermissionTreeLP(bp.name);
3794 if (tree != null) {
3795 bp.perm = new PackageParser.Permission(tree.perm.owner,
3796 new PermissionInfo(bp.pendingInfo));
3797 bp.perm.info.packageName = tree.perm.info.packageName;
3798 bp.perm.info.name = bp.name;
3799 bp.uid = tree.uid;
3800 }
3801 }
3802 }
3803 if (bp.perm == null) {
3804 Log.w(TAG, "Removing dangling permission: " + bp.name
3805 + " from package " + bp.sourcePackage);
3806 it.remove();
3807 }
3808 }
3809
3810 // Now update the permissions for all packages, in particular
3811 // replace the granted permissions of the system packages.
3812 for (PackageParser.Package pkg : mPackages.values()) {
3813 grantPermissionsLP(pkg, false);
3814 }
3815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3818 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3819 if (ps == null) {
3820 return;
3821 }
3822 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3823 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 if (replace) {
3826 ps.permissionsFixed = false;
3827 if (gp == ps) {
3828 gp.grantedPermissions.clear();
3829 gp.gids = mGlobalGids;
3830 }
3831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 if (gp.gids == null) {
3834 gp.gids = mGlobalGids;
3835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 final int N = pkg.requestedPermissions.size();
3838 for (int i=0; i<N; i++) {
3839 String name = pkg.requestedPermissions.get(i);
3840 BasePermission bp = mSettings.mPermissions.get(name);
3841 PackageParser.Permission p = bp != null ? bp.perm : null;
3842 if (false) {
3843 if (gp != ps) {
3844 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3845 + ": " + p);
3846 }
3847 }
3848 if (p != null) {
3849 final String perm = p.info.name;
3850 boolean allowed;
3851 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3852 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3853 allowed = true;
3854 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3855 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003856 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003858 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 == PackageManager.SIGNATURE_MATCH);
3860 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3861 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3862 // For updated system applications, the signatureOrSystem permission
3863 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003864 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3866 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3867 if(sysPs.grantedPermissions.contains(perm)) {
3868 allowed = true;
3869 } else {
3870 allowed = false;
3871 }
3872 } else {
3873 allowed = true;
3874 }
3875 }
3876 }
3877 } else {
3878 allowed = false;
3879 }
3880 if (false) {
3881 if (gp != ps) {
3882 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3883 }
3884 }
3885 if (allowed) {
3886 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3887 && ps.permissionsFixed) {
3888 // If this is an existing, non-system package, then
3889 // we can't add any new permissions to it.
3890 if (!gp.loadedPermissions.contains(perm)) {
3891 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003892 // Except... if this is a permission that was added
3893 // to the platform (note: need to only do this when
3894 // updating the platform).
3895 final int NP = PackageParser.NEW_PERMISSIONS.length;
3896 for (int ip=0; ip<NP; ip++) {
3897 final PackageParser.NewPermissionInfo npi
3898 = PackageParser.NEW_PERMISSIONS[ip];
3899 if (npi.name.equals(perm)
3900 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3901 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003902 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003903 + pkg.packageName);
3904 break;
3905 }
3906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 }
3908 }
3909 if (allowed) {
3910 if (!gp.grantedPermissions.contains(perm)) {
3911 addedPermission = true;
3912 gp.grantedPermissions.add(perm);
3913 gp.gids = appendInts(gp.gids, bp.gids);
3914 }
3915 } else {
3916 Log.w(TAG, "Not granting permission " + perm
3917 + " to package " + pkg.packageName
3918 + " because it was previously installed without");
3919 }
3920 } else {
3921 Log.w(TAG, "Not granting permission " + perm
3922 + " to package " + pkg.packageName
3923 + " (protectionLevel=" + p.info.protectionLevel
3924 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3925 + ")");
3926 }
3927 } else {
3928 Log.w(TAG, "Unknown permission " + name
3929 + " in package " + pkg.packageName);
3930 }
3931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003934 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3935 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 // This is the first that we have heard about this package, so the
3937 // permissions we have now selected are fixed until explicitly
3938 // changed.
3939 ps.permissionsFixed = true;
3940 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3941 }
3942 }
3943
3944 private final class ActivityIntentResolver
3945 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003946 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003948 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 }
3950
Mihai Preda074edef2009-05-18 17:13:31 +02003951 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003953 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3955 }
3956
Mihai Predaeae850c2009-05-13 10:13:48 +02003957 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3958 ArrayList<PackageParser.Activity> packageActivities) {
3959 if (packageActivities == null) {
3960 return null;
3961 }
3962 mFlags = flags;
3963 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3964 int N = packageActivities.size();
3965 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3966 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003967
3968 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003969 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003970 intentFilters = packageActivities.get(i).intents;
3971 if (intentFilters != null && intentFilters.size() > 0) {
3972 listCut.add(intentFilters);
3973 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003974 }
3975 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3976 }
3977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003979 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 if (SHOW_INFO || Config.LOGV) Log.v(
3981 TAG, " " + type + " " +
3982 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3983 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3984 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003985 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3987 if (SHOW_INFO || Config.LOGV) {
3988 Log.v(TAG, " IntentFilter:");
3989 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3990 }
3991 if (!intent.debugCheck()) {
3992 Log.w(TAG, "==> For Activity " + a.info.name);
3993 }
3994 addFilter(intent);
3995 }
3996 }
3997
3998 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003999 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 if (SHOW_INFO || Config.LOGV) Log.v(
4001 TAG, " " + type + " " +
4002 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4003 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4004 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004005 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4007 if (SHOW_INFO || Config.LOGV) {
4008 Log.v(TAG, " IntentFilter:");
4009 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4010 }
4011 removeFilter(intent);
4012 }
4013 }
4014
4015 @Override
4016 protected boolean allowFilterResult(
4017 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4018 ActivityInfo filterAi = filter.activity.info;
4019 for (int i=dest.size()-1; i>=0; i--) {
4020 ActivityInfo destAi = dest.get(i).activityInfo;
4021 if (destAi.name == filterAi.name
4022 && destAi.packageName == filterAi.packageName) {
4023 return false;
4024 }
4025 }
4026 return true;
4027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 @Override
4030 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4031 int match) {
4032 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4033 return null;
4034 }
4035 final PackageParser.Activity activity = info.activity;
4036 if (mSafeMode && (activity.info.applicationInfo.flags
4037 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4038 return null;
4039 }
4040 final ResolveInfo res = new ResolveInfo();
4041 res.activityInfo = PackageParser.generateActivityInfo(activity,
4042 mFlags);
4043 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4044 res.filter = info;
4045 }
4046 res.priority = info.getPriority();
4047 res.preferredOrder = activity.owner.mPreferredOrder;
4048 //System.out.println("Result: " + res.activityInfo.className +
4049 // " = " + res.priority);
4050 res.match = match;
4051 res.isDefault = info.hasDefault;
4052 res.labelRes = info.labelRes;
4053 res.nonLocalizedLabel = info.nonLocalizedLabel;
4054 res.icon = info.icon;
4055 return res;
4056 }
4057
4058 @Override
4059 protected void sortResults(List<ResolveInfo> results) {
4060 Collections.sort(results, mResolvePrioritySorter);
4061 }
4062
4063 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004064 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004066 out.print(prefix); out.print(
4067 Integer.toHexString(System.identityHashCode(filter.activity)));
4068 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004069 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 }
4071
4072// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4073// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4074// final List<ResolveInfo> retList = Lists.newArrayList();
4075// while (i.hasNext()) {
4076// final ResolveInfo resolveInfo = i.next();
4077// if (isEnabledLP(resolveInfo.activityInfo)) {
4078// retList.add(resolveInfo);
4079// }
4080// }
4081// return retList;
4082// }
4083
4084 // Keys are String (activity class name), values are Activity.
4085 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4086 = new HashMap<ComponentName, PackageParser.Activity>();
4087 private int mFlags;
4088 }
4089
4090 private final class ServiceIntentResolver
4091 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004092 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004094 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 }
4096
Mihai Preda074edef2009-05-18 17:13:31 +02004097 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004099 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4101 }
4102
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004103 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4104 ArrayList<PackageParser.Service> packageServices) {
4105 if (packageServices == null) {
4106 return null;
4107 }
4108 mFlags = flags;
4109 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4110 int N = packageServices.size();
4111 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4112 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4113
4114 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4115 for (int i = 0; i < N; ++i) {
4116 intentFilters = packageServices.get(i).intents;
4117 if (intentFilters != null && intentFilters.size() > 0) {
4118 listCut.add(intentFilters);
4119 }
4120 }
4121 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4122 }
4123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004125 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 if (SHOW_INFO || Config.LOGV) Log.v(
4127 TAG, " " + (s.info.nonLocalizedLabel != null
4128 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4129 if (SHOW_INFO || Config.LOGV) Log.v(
4130 TAG, " Class=" + s.info.name);
4131 int NI = s.intents.size();
4132 int j;
4133 for (j=0; j<NI; j++) {
4134 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4135 if (SHOW_INFO || Config.LOGV) {
4136 Log.v(TAG, " IntentFilter:");
4137 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4138 }
4139 if (!intent.debugCheck()) {
4140 Log.w(TAG, "==> For Service " + s.info.name);
4141 }
4142 addFilter(intent);
4143 }
4144 }
4145
4146 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004147 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 if (SHOW_INFO || Config.LOGV) Log.v(
4149 TAG, " " + (s.info.nonLocalizedLabel != null
4150 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4151 if (SHOW_INFO || Config.LOGV) Log.v(
4152 TAG, " Class=" + s.info.name);
4153 int NI = s.intents.size();
4154 int j;
4155 for (j=0; j<NI; j++) {
4156 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4157 if (SHOW_INFO || Config.LOGV) {
4158 Log.v(TAG, " IntentFilter:");
4159 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4160 }
4161 removeFilter(intent);
4162 }
4163 }
4164
4165 @Override
4166 protected boolean allowFilterResult(
4167 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4168 ServiceInfo filterSi = filter.service.info;
4169 for (int i=dest.size()-1; i>=0; i--) {
4170 ServiceInfo destAi = dest.get(i).serviceInfo;
4171 if (destAi.name == filterSi.name
4172 && destAi.packageName == filterSi.packageName) {
4173 return false;
4174 }
4175 }
4176 return true;
4177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 @Override
4180 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4181 int match) {
4182 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4183 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4184 return null;
4185 }
4186 final PackageParser.Service service = info.service;
4187 if (mSafeMode && (service.info.applicationInfo.flags
4188 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4189 return null;
4190 }
4191 final ResolveInfo res = new ResolveInfo();
4192 res.serviceInfo = PackageParser.generateServiceInfo(service,
4193 mFlags);
4194 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4195 res.filter = filter;
4196 }
4197 res.priority = info.getPriority();
4198 res.preferredOrder = service.owner.mPreferredOrder;
4199 //System.out.println("Result: " + res.activityInfo.className +
4200 // " = " + res.priority);
4201 res.match = match;
4202 res.isDefault = info.hasDefault;
4203 res.labelRes = info.labelRes;
4204 res.nonLocalizedLabel = info.nonLocalizedLabel;
4205 res.icon = info.icon;
4206 return res;
4207 }
4208
4209 @Override
4210 protected void sortResults(List<ResolveInfo> results) {
4211 Collections.sort(results, mResolvePrioritySorter);
4212 }
4213
4214 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004215 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004217 out.print(prefix); out.print(
4218 Integer.toHexString(System.identityHashCode(filter.service)));
4219 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004220 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 }
4222
4223// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4224// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4225// final List<ResolveInfo> retList = Lists.newArrayList();
4226// while (i.hasNext()) {
4227// final ResolveInfo resolveInfo = (ResolveInfo) i;
4228// if (isEnabledLP(resolveInfo.serviceInfo)) {
4229// retList.add(resolveInfo);
4230// }
4231// }
4232// return retList;
4233// }
4234
4235 // Keys are String (activity class name), values are Activity.
4236 private final HashMap<ComponentName, PackageParser.Service> mServices
4237 = new HashMap<ComponentName, PackageParser.Service>();
4238 private int mFlags;
4239 };
4240
4241 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4242 new Comparator<ResolveInfo>() {
4243 public int compare(ResolveInfo r1, ResolveInfo r2) {
4244 int v1 = r1.priority;
4245 int v2 = r2.priority;
4246 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4247 if (v1 != v2) {
4248 return (v1 > v2) ? -1 : 1;
4249 }
4250 v1 = r1.preferredOrder;
4251 v2 = r2.preferredOrder;
4252 if (v1 != v2) {
4253 return (v1 > v2) ? -1 : 1;
4254 }
4255 if (r1.isDefault != r2.isDefault) {
4256 return r1.isDefault ? -1 : 1;
4257 }
4258 v1 = r1.match;
4259 v2 = r2.match;
4260 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4261 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4262 }
4263 };
4264
4265 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4266 new Comparator<ProviderInfo>() {
4267 public int compare(ProviderInfo p1, ProviderInfo p2) {
4268 final int v1 = p1.initOrder;
4269 final int v2 = p2.initOrder;
4270 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4271 }
4272 };
4273
4274 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4275 IActivityManager am = ActivityManagerNative.getDefault();
4276 if (am != null) {
4277 try {
4278 final Intent intent = new Intent(action,
4279 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4280 if (extras != null) {
4281 intent.putExtras(extras);
4282 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004283 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 am.broadcastIntent(
4285 null, intent,
4286 null, null, 0, null, null, null, false, false);
4287 } catch (RemoteException ex) {
4288 }
4289 }
4290 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004291
4292 public String nextPackageToClean(String lastPackage) {
4293 synchronized (mPackages) {
4294 if (!mMediaMounted) {
4295 // If the external storage is no longer mounted at this point,
4296 // the caller may not have been able to delete all of this
4297 // packages files and can not delete any more. Bail.
4298 return null;
4299 }
4300 if (lastPackage != null) {
4301 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4302 }
4303 return mSettings.mPackagesToBeCleaned.size() > 0
4304 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4305 }
4306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004308 void schedulePackageCleaning(String packageName) {
4309 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4310 }
4311
4312 void startCleaningPackages() {
4313 synchronized (mPackages) {
4314 if (!mMediaMounted) {
4315 return;
4316 }
4317 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4318 return;
4319 }
4320 }
4321 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4322 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4323 IActivityManager am = ActivityManagerNative.getDefault();
4324 if (am != null) {
4325 try {
4326 am.startService(null, intent, null);
4327 } catch (RemoteException e) {
4328 }
4329 }
4330 }
4331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 private final class AppDirObserver extends FileObserver {
4333 public AppDirObserver(String path, int mask, boolean isrom) {
4334 super(path, mask);
4335 mRootDir = path;
4336 mIsRom = isrom;
4337 }
4338
4339 public void onEvent(int event, String path) {
4340 String removedPackage = null;
4341 int removedUid = -1;
4342 String addedPackage = null;
4343 int addedUid = -1;
4344
4345 synchronized (mInstallLock) {
4346 String fullPathStr = null;
4347 File fullPath = null;
4348 if (path != null) {
4349 fullPath = new File(mRootDir, path);
4350 fullPathStr = fullPath.getPath();
4351 }
4352
4353 if (Config.LOGV) Log.v(
4354 TAG, "File " + fullPathStr + " changed: "
4355 + Integer.toHexString(event));
4356
4357 if (!isPackageFilename(path)) {
4358 if (Config.LOGV) Log.v(
4359 TAG, "Ignoring change of non-package file: " + fullPathStr);
4360 return;
4361 }
4362
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004363 // Ignore packages that are being installed or
4364 // have just been installed.
4365 if (ignoreCodePath(fullPathStr)) {
4366 return;
4367 }
4368 PackageParser.Package p = null;
4369 synchronized (mPackages) {
4370 p = mAppDirs.get(fullPathStr);
4371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004373 if (p != null) {
4374 removePackageLI(p, true);
4375 removedPackage = p.applicationInfo.packageName;
4376 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377 }
4378 }
4379
4380 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004382 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4384 PackageParser.PARSE_CHATTY |
4385 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004386 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 if (p != null) {
4388 synchronized (mPackages) {
4389 grantPermissionsLP(p, false);
4390 }
4391 addedPackage = p.applicationInfo.packageName;
4392 addedUid = p.applicationInfo.uid;
4393 }
4394 }
4395 }
4396
4397 synchronized (mPackages) {
4398 mSettings.writeLP();
4399 }
4400 }
4401
4402 if (removedPackage != null) {
4403 Bundle extras = new Bundle(1);
4404 extras.putInt(Intent.EXTRA_UID, removedUid);
4405 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4406 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4407 }
4408 if (addedPackage != null) {
4409 Bundle extras = new Bundle(1);
4410 extras.putInt(Intent.EXTRA_UID, addedUid);
4411 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4412 }
4413 }
4414
4415 private final String mRootDir;
4416 private final boolean mIsRom;
4417 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 /* Called when a downloaded package installation has been confirmed by the user */
4420 public void installPackage(
4421 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004422 installPackage(packageURI, observer, flags, null);
4423 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004424
Jacek Surazski65e13172009-04-28 15:26:38 +02004425 /* Called when a downloaded package installation has been confirmed by the user */
4426 public void installPackage(
4427 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4428 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 mContext.enforceCallingOrSelfPermission(
4430 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004431
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004432 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004433 msg.obj = new InstallParams(packageURI, observer, flags,
4434 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004435 mHandler.sendMessage(msg);
4436 }
4437
Christopher Tate1bb69062010-02-19 17:02:12 -08004438 public void finishPackageInstall(int token) {
4439 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4440 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4441 mHandler.sendMessage(msg);
4442 }
4443
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004444 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 // Queue up an async operation since the package installation may take a little while.
4446 mHandler.post(new Runnable() {
4447 public void run() {
4448 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004449 // Result object to be returned
4450 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004451 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004452 res.uid = -1;
4453 res.pkg = null;
4454 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004455 args.doPreInstall(res.returnCode);
4456 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004457 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004458 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004459 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004460 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004462
4463 // A restore should be performed at this point if (a) the install
4464 // succeeded, (b) the operation is not an update, and (c) the new
4465 // package has a backupAgent defined.
4466 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004467 boolean doRestore = (!update
4468 && res.pkg != null
4469 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004470
4471 // Set up the post-install work request bookkeeping. This will be used
4472 // and cleaned up by the post-install event handling regardless of whether
4473 // there's a restore pass performed. Token values are >= 1.
4474 int token;
4475 if (mNextInstallToken < 0) mNextInstallToken = 1;
4476 token = mNextInstallToken++;
4477
4478 PostInstallData data = new PostInstallData(args, res);
4479 mRunningInstalls.put(token, data);
4480 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4481
4482 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4483 // Pass responsibility to the Backup Manager. It will perform a
4484 // restore if appropriate, then pass responsibility back to the
4485 // Package Manager to run the post-install observer callbacks
4486 // and broadcasts.
4487 IBackupManager bm = IBackupManager.Stub.asInterface(
4488 ServiceManager.getService(Context.BACKUP_SERVICE));
4489 if (bm != null) {
4490 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4491 + " to BM for possible restore");
4492 try {
4493 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4494 } catch (RemoteException e) {
4495 // can't happen; the backup manager is local
4496 } catch (Exception e) {
4497 Log.e(TAG, "Exception trying to enqueue restore", e);
4498 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004499 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004500 } else {
4501 Log.e(TAG, "Backup Manager not found!");
4502 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004505
4506 if (!doRestore) {
4507 // No restore possible, or the Backup Manager was mysteriously not
4508 // available -- just fire the post-install work request directly.
4509 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4510 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4511 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 }
4514 });
4515 }
4516
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004517 abstract class HandlerParams {
4518 final static int MAX_RETRIES = 4;
4519 int retry = 0;
4520 final void startCopy() {
4521 try {
4522 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4523 retry++;
4524 if (retry > MAX_RETRIES) {
4525 Log.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
4526 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4527 handleServiceError();
4528 return;
4529 } else {
4530 handleStartCopy();
4531 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4532 mHandler.sendEmptyMessage(MCS_UNBIND);
4533 }
4534 } catch (RemoteException e) {
4535 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4536 mHandler.sendEmptyMessage(MCS_RECONNECT);
4537 }
4538 handleReturnCode();
4539 }
4540
4541 final void serviceError() {
4542 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4543 handleServiceError();
4544 handleReturnCode();
4545 }
4546 abstract void handleStartCopy() throws RemoteException;
4547 abstract void handleServiceError();
4548 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004549 }
4550
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004551 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004552 final IPackageInstallObserver observer;
4553 int flags;
4554 final Uri packageURI;
4555 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004556 private InstallArgs mArgs;
4557 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004558 InstallParams(Uri packageURI,
4559 IPackageInstallObserver observer, int flags,
4560 String installerPackageName) {
4561 this.packageURI = packageURI;
4562 this.flags = flags;
4563 this.observer = observer;
4564 this.installerPackageName = installerPackageName;
4565 }
4566
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004567 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004568 int ret = PackageManager.INSTALL_SUCCEEDED;
4569 // Dont need to invoke getInstallLocation for forward locked apps.
4570 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4571 flags &= ~PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004572 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004573 // Remote call to find out default install location
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004574 int loc = mContainerService.getRecommendedInstallLocation(packageURI);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004575 // Use install location to create InstallArgs and temporary
4576 // install location
4577 if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
4578 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4579 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4580 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
4581 } else {
4582 if ((flags & PackageManager.INSTALL_EXTERNAL) == 0){
4583 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4584 // Set the flag to install on external media.
4585 flags |= PackageManager.INSTALL_EXTERNAL;
4586 } else {
4587 // Make sure the flag for installing on external
4588 // media is unset
4589 flags &= ~PackageManager.INSTALL_EXTERNAL;
4590 }
4591 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004592 }
4593 }
4594 // Create the file args now.
4595 mArgs = createInstallArgs(this);
4596 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4597 // Create copy only if we are not in an erroneous state.
4598 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004599 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004600 }
4601 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004602 }
4603
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004604 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004605 void handleReturnCode() {
4606 processPendingInstall(mArgs, mRet);
4607 }
4608
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004609 @Override
4610 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004611 mArgs = createInstallArgs(this);
4612 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004613 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004614 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004615
4616 /*
4617 * Utility class used in movePackage api.
4618 * srcArgs and targetArgs are not set for invalid flags and make
4619 * sure to do null checks when invoking methods on them.
4620 * We probably want to return ErrorPrams for both failed installs
4621 * and moves.
4622 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004623 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004624 final IPackageMoveObserver observer;
4625 final int flags;
4626 final String packageName;
4627 final InstallArgs srcArgs;
4628 final InstallArgs targetArgs;
4629 int mRet;
4630 MoveParams(InstallArgs srcArgs,
4631 IPackageMoveObserver observer,
4632 int flags, String packageName) {
4633 this.srcArgs = srcArgs;
4634 this.observer = observer;
4635 this.flags = flags;
4636 this.packageName = packageName;
4637 if (srcArgs != null) {
4638 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4639 targetArgs = createInstallArgs(packageUri, flags, packageName);
4640 } else {
4641 targetArgs = null;
4642 }
4643 }
4644
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004645 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004646 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004647 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004648 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004649 if (DEBUG_SD_INSTALL) {
4650 StringBuilder builder = new StringBuilder();
4651 if (srcArgs != null) {
4652 builder.append("src: ");
4653 builder.append(srcArgs.getCodePath());
4654 }
4655 if (targetArgs != null) {
4656 builder.append(" target : ");
4657 builder.append(targetArgs.getCodePath());
4658 }
4659 Log.i(TAG, "Posting move MCS_UNBIND for " + builder.toString());
4660 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004661 }
4662
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004663 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004664 void handleReturnCode() {
4665 targetArgs.doPostInstall(mRet);
4666 // TODO invoke pending move
4667 processPendingMove(this, mRet);
4668 }
4669
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004670 @Override
4671 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004672 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004673 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004674 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004675
4676 private InstallArgs createInstallArgs(InstallParams params) {
4677 if (installOnSd(params.flags)) {
4678 return new SdInstallArgs(params);
4679 } else {
4680 return new FileInstallArgs(params);
4681 }
4682 }
4683
4684 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4685 if (installOnSd(flags)) {
4686 return new SdInstallArgs(fullCodePath, fullResourcePath);
4687 } else {
4688 return new FileInstallArgs(fullCodePath, fullResourcePath);
4689 }
4690 }
4691
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004692 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4693 if (installOnSd(flags)) {
4694 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4695 return new SdInstallArgs(packageURI, cid);
4696 } else {
4697 return new FileInstallArgs(packageURI, pkgName);
4698 }
4699 }
4700
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004701 static abstract class InstallArgs {
4702 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004703 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004704 final int flags;
4705 final Uri packageURI;
4706 final String installerPackageName;
4707
4708 InstallArgs(Uri packageURI,
4709 IPackageInstallObserver observer, int flags,
4710 String installerPackageName) {
4711 this.packageURI = packageURI;
4712 this.flags = flags;
4713 this.observer = observer;
4714 this.installerPackageName = installerPackageName;
4715 }
4716
4717 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004718 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004719 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004720 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004721 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004722 abstract String getCodePath();
4723 abstract String getResourcePath();
4724 // Need installer lock especially for dex file removal.
4725 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004726 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004727 }
4728
4729 class FileInstallArgs extends InstallArgs {
4730 File installDir;
4731 String codeFileName;
4732 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004733 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004734
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004735 FileInstallArgs(InstallParams params) {
4736 super(params.packageURI, params.observer,
4737 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004738 }
4739
4740 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4741 super(null, null, 0, null);
4742 File codeFile = new File(fullCodePath);
4743 installDir = codeFile.getParentFile();
4744 codeFileName = fullCodePath;
4745 resourceFileName = fullResourcePath;
4746 }
4747
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004748 FileInstallArgs(Uri packageURI, String pkgName) {
4749 super(packageURI, null, 0, null);
4750 boolean fwdLocked = isFwdLocked(flags);
4751 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4752 String apkName = getNextCodePath(null, pkgName, ".apk");
4753 codeFileName = new File(installDir, apkName + ".apk").getPath();
4754 resourceFileName = getResourcePathFromCodePath();
4755 }
4756
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004757 String getCodePath() {
4758 return codeFileName;
4759 }
4760
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004761 void createCopyFile() {
4762 boolean fwdLocked = isFwdLocked(flags);
4763 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4764 codeFileName = createTempPackageFile(installDir).getPath();
4765 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004766 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004767 }
4768
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004769 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004770 if (temp) {
4771 // Generate temp file name
4772 createCopyFile();
4773 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004774 // Get a ParcelFileDescriptor to write to the output file
4775 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004776 if (!created) {
4777 try {
4778 codeFile.createNewFile();
4779 // Set permissions
4780 if (!setPermissions()) {
4781 // Failed setting permissions.
4782 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4783 }
4784 } catch (IOException e) {
4785 Log.w(TAG, "Failed to create file " + codeFile);
4786 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4787 }
4788 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004789 ParcelFileDescriptor out = null;
4790 try {
4791 out = ParcelFileDescriptor.open(codeFile,
4792 ParcelFileDescriptor.MODE_READ_WRITE);
4793 } catch (FileNotFoundException e) {
4794 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4795 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4796 }
4797 // Copy the resource now
4798 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4799 try {
4800 if (imcs.copyResource(packageURI, out)) {
4801 ret = PackageManager.INSTALL_SUCCEEDED;
4802 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004803 } finally {
4804 try { if (out != null) out.close(); } catch (IOException e) {}
4805 }
4806 return ret;
4807 }
4808
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004809 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004810 if (status != PackageManager.INSTALL_SUCCEEDED) {
4811 cleanUp();
4812 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004813 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004814 }
4815
4816 boolean doRename(int status, final String pkgName, String oldCodePath) {
4817 if (status != PackageManager.INSTALL_SUCCEEDED) {
4818 cleanUp();
4819 return false;
4820 } else {
4821 // Rename based on packageName
4822 File codeFile = new File(getCodePath());
4823 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4824 File desFile = new File(installDir, apkName + ".apk");
4825 if (!codeFile.renameTo(desFile)) {
4826 return false;
4827 }
4828 // Reset paths since the file has been renamed.
4829 codeFileName = desFile.getPath();
4830 resourceFileName = getResourcePathFromCodePath();
4831 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004832 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004833 // Failed setting permissions.
4834 return false;
4835 }
4836 return true;
4837 }
4838 }
4839
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004840 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004841 if (status != PackageManager.INSTALL_SUCCEEDED) {
4842 cleanUp();
4843 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004844 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004845 }
4846
4847 String getResourcePath() {
4848 return resourceFileName;
4849 }
4850
4851 String getResourcePathFromCodePath() {
4852 String codePath = getCodePath();
4853 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4854 String apkNameOnly = getApkName(codePath);
4855 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4856 } else {
4857 return codePath;
4858 }
4859 }
4860
4861 private boolean cleanUp() {
4862 boolean ret = true;
4863 String sourceDir = getCodePath();
4864 String publicSourceDir = getResourcePath();
4865 if (sourceDir != null) {
4866 File sourceFile = new File(sourceDir);
4867 if (!sourceFile.exists()) {
4868 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4869 ret = false;
4870 }
4871 // Delete application's code and resources
4872 sourceFile.delete();
4873 }
4874 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4875 final File publicSourceFile = new File(publicSourceDir);
4876 if (!publicSourceFile.exists()) {
4877 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4878 }
4879 if (publicSourceFile.exists()) {
4880 publicSourceFile.delete();
4881 }
4882 }
4883 return ret;
4884 }
4885
4886 void cleanUpResourcesLI() {
4887 String sourceDir = getCodePath();
4888 if (cleanUp() && mInstaller != null) {
4889 int retCode = mInstaller.rmdex(sourceDir);
4890 if (retCode < 0) {
4891 Log.w(TAG, "Couldn't remove dex file for package: "
4892 + " at location "
4893 + sourceDir + ", retcode=" + retCode);
4894 // we don't consider this to be a failure of the core package deletion
4895 }
4896 }
4897 }
4898
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004899 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004900 // TODO Do this in a more elegant way later on. for now just a hack
4901 if (!isFwdLocked(flags)) {
4902 final int filePermissions =
4903 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4904 |FileUtils.S_IROTH;
4905 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4906 if (retCode != 0) {
4907 Log.e(TAG, "Couldn't set new package file permissions for " +
4908 getCodePath()
4909 + ". The return code was: " + retCode);
4910 // TODO Define new internal error
4911 return false;
4912 }
4913 return true;
4914 }
4915 return true;
4916 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004917
4918 boolean doPostDeleteLI(boolean delete) {
4919 cleanUpResourcesLI();
4920 return true;
4921 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004922 }
4923
4924 class SdInstallArgs extends InstallArgs {
4925 String cid;
4926 String cachePath;
4927 static final String RES_FILE_NAME = "pkg.apk";
4928
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004929 SdInstallArgs(InstallParams params) {
4930 super(params.packageURI, params.observer,
4931 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004932 }
4933
4934 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004935 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004936 // Extract cid from fullCodePath
4937 int eidx = fullCodePath.lastIndexOf("/");
4938 String subStr1 = fullCodePath.substring(0, eidx);
4939 int sidx = subStr1.lastIndexOf("/");
4940 cid = subStr1.substring(sidx+1, eidx);
4941 cachePath = subStr1;
4942 }
4943
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004944 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004945 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
4946 this.cid = cid;
4947 }
4948
4949 SdInstallArgs(Uri packageURI, String cid) {
4950 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004951 this.cid = cid;
4952 }
4953
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004954 void createCopyFile() {
4955 cid = getTempContainerId();
4956 }
4957
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004958 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004959 if (temp) {
4960 createCopyFile();
4961 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004962 cachePath = imcs.copyResourceToContainer(
4963 packageURI, cid,
4964 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004965 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4966 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004967 }
4968
4969 @Override
4970 String getCodePath() {
4971 return cachePath + "/" + RES_FILE_NAME;
4972 }
4973
4974 @Override
4975 String getResourcePath() {
4976 return cachePath + "/" + RES_FILE_NAME;
4977 }
4978
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004979 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004980 if (status != PackageManager.INSTALL_SUCCEEDED) {
4981 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004982 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004983 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004984 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004985 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004986 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004987 if (cachePath == null) {
4988 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4989 }
4990 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004991 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004992 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004993 }
4994
4995 boolean doRename(int status, final String pkgName,
4996 String oldCodePath) {
4997 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004998 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004999 if (PackageHelper.isContainerMounted(cid)) {
5000 // Unmount the container
5001 if (!PackageHelper.unMountSdDir(cid)) {
5002 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005003 return false;
5004 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005005 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005006 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5007 Log.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
5008 return false;
5009 }
5010 if (!PackageHelper.isContainerMounted(newCacheId)) {
5011 Log.w(TAG, "Mounting container " + newCacheId);
5012 newCachePath = PackageHelper.mountSdDir(newCacheId,
5013 getEncryptKey(), Process.SYSTEM_UID);
5014 } else {
5015 newCachePath = PackageHelper.getSdDir(newCacheId);
5016 }
5017 if (newCachePath == null) {
5018 Log.w(TAG, "Failed to get cache path for " + newCacheId);
5019 return false;
5020 }
5021 Log.i(TAG, "Succesfully renamed " + cid +
5022 " at path: " + cachePath + " to " + newCacheId +
5023 " at new path: " + newCachePath);
5024 cid = newCacheId;
5025 cachePath = newCachePath;
5026 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005027 }
5028
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005029 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005030 if (status != PackageManager.INSTALL_SUCCEEDED) {
5031 cleanUp();
5032 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005033 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005034 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005035 PackageHelper.mountSdDir(cid,
5036 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005037 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005038 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005039 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005040 }
5041
5042 private void cleanUp() {
5043 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005044 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005045 }
5046
5047 void cleanUpResourcesLI() {
5048 String sourceFile = getCodePath();
5049 // Remove dex file
5050 if (mInstaller != null) {
5051 int retCode = mInstaller.rmdex(sourceFile.toString());
5052 if (retCode < 0) {
5053 Log.w(TAG, "Couldn't remove dex file for package: "
5054 + " at location "
5055 + sourceFile.toString() + ", retcode=" + retCode);
5056 // we don't consider this to be a failure of the core package deletion
5057 }
5058 }
5059 cleanUp();
5060 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005061
5062 boolean matchContainer(String app) {
5063 if (cid.startsWith(app)) {
5064 return true;
5065 }
5066 return false;
5067 }
5068
5069 String getPackageName() {
5070 int idx = cid.lastIndexOf("-");
5071 if (idx == -1) {
5072 return cid;
5073 }
5074 return cid.substring(0, idx);
5075 }
5076
5077 boolean doPostDeleteLI(boolean delete) {
5078 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005079 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005080 if (mounted) {
5081 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005082 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005083 }
5084 if (ret && delete) {
5085 cleanUpResourcesLI();
5086 }
5087 return ret;
5088 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005089 };
5090
5091 // Utility method used to create code paths based on package name and available index.
5092 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5093 String idxStr = "";
5094 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005095 // Fall back to default value of idx=1 if prefix is not
5096 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005097 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005098 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005099 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005100 if (subStr.endsWith(suffix)) {
5101 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005102 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005103 // If oldCodePath already contains prefix find out the
5104 // ending index to either increment or decrement.
5105 int sidx = subStr.lastIndexOf(prefix);
5106 if (sidx != -1) {
5107 subStr = subStr.substring(sidx + prefix.length());
5108 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005109 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5110 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005111 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005112 try {
5113 idx = Integer.parseInt(subStr);
5114 if (idx <= 1) {
5115 idx++;
5116 } else {
5117 idx--;
5118 }
5119 } catch(NumberFormatException e) {
5120 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005121 }
5122 }
5123 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005124 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005125 return prefix + idxStr;
5126 }
5127
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005128 // Utility method used to ignore ADD/REMOVE events
5129 // by directory observer.
5130 private static boolean ignoreCodePath(String fullPathStr) {
5131 String apkName = getApkName(fullPathStr);
5132 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5133 if (idx != -1 && ((idx+1) < apkName.length())) {
5134 // Make sure the package ends with a numeral
5135 String version = apkName.substring(idx+1);
5136 try {
5137 Integer.parseInt(version);
5138 return true;
5139 } catch (NumberFormatException e) {}
5140 }
5141 return false;
5142 }
5143
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005144 // Utility method that returns the relative package path with respect
5145 // to the installation directory. Like say for /data/data/com.test-1.apk
5146 // string com.test-1 is returned.
5147 static String getApkName(String codePath) {
5148 if (codePath == null) {
5149 return null;
5150 }
5151 int sidx = codePath.lastIndexOf("/");
5152 int eidx = codePath.lastIndexOf(".");
5153 if (eidx == -1) {
5154 eidx = codePath.length();
5155 } else if (eidx == 0) {
5156 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
5157 return null;
5158 }
5159 return codePath.substring(sidx+1, eidx);
5160 }
5161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005162 class PackageInstalledInfo {
5163 String name;
5164 int uid;
5165 PackageParser.Package pkg;
5166 int returnCode;
5167 PackageRemovedInfo removedInfo;
5168 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005170 /*
5171 * Install a non-existing package.
5172 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005173 private void installNewPackageLI(PackageParser.Package pkg,
5174 int parseFlags,
5175 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005176 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005177 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005178 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005179
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005180 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005181 res.name = pkgName;
5182 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005183 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005185 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 + " without first uninstalling.");
5187 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5188 return;
5189 }
5190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005192 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005193 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005194 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005195 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5196 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5197 }
5198 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005199 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005200 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005201 res);
5202 // delete the partially installed application. the data directory will have to be
5203 // restored if it was already existing
5204 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5205 // remove package from internal structures. Note that we want deletePackageX to
5206 // delete the package data and cache directories that it created in
5207 // scanPackageLocked, unless those directories existed before we even tried to
5208 // install.
5209 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005210 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5212 res.removedInfo);
5213 }
5214 }
5215 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005216
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005217 private void replacePackageLI(PackageParser.Package pkg,
5218 int parseFlags,
5219 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005220 String installerPackageName, PackageInstalledInfo res) {
5221
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005222 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005223 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 // First find the old package info and check signatures
5225 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005226 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005227 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005228 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5230 return;
5231 }
5232 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005233 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005234 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005235 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005236 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005237 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 }
5239 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005241 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005242 PackageParser.Package pkg,
5243 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005244 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005245 PackageParser.Package newPackage = null;
5246 String pkgName = deletedPackage.packageName;
5247 boolean deletedPkg = true;
5248 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005249
Jacek Surazski65e13172009-04-28 15:26:38 +02005250 String oldInstallerPackageName = null;
5251 synchronized (mPackages) {
5252 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5253 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005254
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005255 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005257 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005258 res.removedInfo)) {
5259 // If the existing package was'nt successfully deleted
5260 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5261 deletedPkg = false;
5262 } else {
5263 // Successfully deleted the old package. Now proceed with re-installation
5264 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005265 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005266 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005267 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005268 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5269 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005270 }
5271 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005272 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005273 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005274 res);
5275 updatedSettings = true;
5276 }
5277 }
5278
5279 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5280 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005281 // were keeping around in case we needed them (see below) can now be deleted.
5282 // This info will be set on the res.removedInfo to clean up later on as post
5283 // install action.
5284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005285 //update signature on the new package setting
5286 //this should always succeed, since we checked the
5287 //signature earlier.
5288 synchronized(mPackages) {
5289 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5290 parseFlags, true);
5291 }
5292 } else {
5293 // remove package from internal structures. Note that we want deletePackageX to
5294 // delete the package data and cache directories that it created in
5295 // scanPackageLocked, unless those directories existed before we even tried to
5296 // install.
5297 if(updatedSettings) {
5298 deletePackageLI(
5299 pkgName, true,
5300 PackageManager.DONT_DELETE_DATA,
5301 res.removedInfo);
5302 }
5303 // Since we failed to install the new package we need to restore the old
5304 // package that we deleted.
5305 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005306 File restoreFile = new File(deletedPackage.mPath);
5307 if (restoreFile == null) {
5308 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
5309 return;
5310 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005311 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5312 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005313 // Parse old package
5314 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5315 scanPackageLI(restoreFile, parseFlags, scanMode);
5316 synchronized (mPackages) {
5317 grantPermissionsLP(deletedPackage, false);
5318 mSettings.writeLP();
5319 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005320 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5321 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
5322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005323 }
5324 }
5325 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005328 PackageParser.Package pkg,
5329 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005330 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 PackageParser.Package newPackage = null;
5332 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005333 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 PackageParser.PARSE_IS_SYSTEM;
5335 String packageName = deletedPackage.packageName;
5336 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5337 if (packageName == null) {
5338 Log.w(TAG, "Attempt to delete null packageName.");
5339 return;
5340 }
5341 PackageParser.Package oldPkg;
5342 PackageSetting oldPkgSetting;
5343 synchronized (mPackages) {
5344 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005345 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005346 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5347 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005348 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349 return;
5350 }
5351 }
5352 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5353 res.removedInfo.removedPackage = packageName;
5354 // Remove existing system package
5355 removePackageLI(oldPkg, true);
5356 synchronized (mPackages) {
5357 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5358 }
5359
5360 // Successfully disabled the old package. Now proceed with re-installation
5361 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5362 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005363 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005364 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005365 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005366 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5367 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5368 }
5369 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005370 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005371 updatedSettings = true;
5372 }
5373
5374 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5375 //update signature on the new package setting
5376 //this should always succeed, since we checked the
5377 //signature earlier.
5378 synchronized(mPackages) {
5379 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5380 parseFlags, true);
5381 }
5382 } else {
5383 // Re installation failed. Restore old information
5384 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005385 if (newPackage != null) {
5386 removePackageLI(newPackage, true);
5387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005388 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005389 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005390 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005391 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392 // Restore the old system information in Settings
5393 synchronized(mPackages) {
5394 if(updatedSettings) {
5395 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005396 mSettings.setInstallerPackageName(packageName,
5397 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398 }
5399 mSettings.writeLP();
5400 }
5401 }
5402 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005403
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005404 // Utility method used to move dex files during install.
5405 private int moveDexFiles(PackageParser.Package newPackage) {
5406 int retCode;
5407 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5408 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5409 if (retCode != 0) {
5410 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5411 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5412 }
5413 }
5414 return PackageManager.INSTALL_SUCCEEDED;
5415 }
5416
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005417 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005418 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005419 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 synchronized (mPackages) {
5421 //write settings. the installStatus will be incomplete at this stage.
5422 //note that the new package setting would have already been
5423 //added to mPackages. It hasn't been persisted yet.
5424 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5425 mSettings.writeLP();
5426 }
5427
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005428 if ((res.returnCode = moveDexFiles(newPackage))
5429 != PackageManager.INSTALL_SUCCEEDED) {
5430 // Discontinue if moving dex files failed.
5431 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005433 if((res.returnCode = setPermissionsLI(newPackage))
5434 != PackageManager.INSTALL_SUCCEEDED) {
5435 if (mInstaller != null) {
5436 mInstaller.rmdex(newPackage.mScanPath);
5437 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005438 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005440 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442 synchronized (mPackages) {
5443 grantPermissionsLP(newPackage, true);
5444 res.name = pkgName;
5445 res.uid = newPackage.applicationInfo.uid;
5446 res.pkg = newPackage;
5447 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005448 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5450 //to update install status
5451 mSettings.writeLP();
5452 }
5453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005454
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005455 private void installPackageLI(InstallArgs args,
5456 boolean newInstall, PackageInstalledInfo res) {
5457 int pFlags = args.flags;
5458 String installerPackageName = args.installerPackageName;
5459 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005460 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005461 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005462 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005463 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5464 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005465 // Result object to be returned
5466 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5467
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005468 // Retrieve PackageSettings and parse package
5469 int parseFlags = PackageParser.PARSE_CHATTY |
5470 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5471 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5472 parseFlags |= mDefParseFlags;
5473 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5474 pp.setSeparateProcesses(mSeparateProcesses);
5475 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5476 null, mMetrics, parseFlags);
5477 if (pkg == null) {
5478 res.returnCode = pp.getParseError();
5479 return;
5480 }
5481 String pkgName = res.name = pkg.packageName;
5482 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5483 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5484 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5485 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005487 }
5488 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5489 res.returnCode = pp.getParseError();
5490 return;
5491 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005492 // Get rid of all references to package scan path via parser.
5493 pp = null;
5494 String oldCodePath = null;
5495 boolean systemApp = false;
5496 synchronized (mPackages) {
5497 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005498 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5499 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005500 if (pkg.mOriginalPackages != null
5501 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005502 && mPackages.containsKey(oldName)) {
5503 // This package is derived from an original package,
5504 // and this device has been updating from that original
5505 // name. We must continue using the original name, so
5506 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005507 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005508 pkgName = pkg.packageName;
5509 replace = true;
5510 } else if (mPackages.containsKey(pkgName)) {
5511 // This package, under its official name, already exists
5512 // on the device; we should replace it.
5513 replace = true;
5514 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005515 }
5516 PackageSetting ps = mSettings.mPackages.get(pkgName);
5517 if (ps != null) {
5518 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5519 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5520 systemApp = (ps.pkg.applicationInfo.flags &
5521 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005522 }
5523 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005524 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005525
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005526 if (systemApp && onSd) {
5527 // Disable updates to system apps on sdcard
5528 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5529 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5530 return;
5531 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005532
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005533 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5534 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5535 return;
5536 }
5537 // Set application objects path explicitly after the rename
5538 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005539 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005540 replacePackageLI(pkg, parseFlags, scanMode,
5541 installerPackageName, res);
5542 } else {
5543 installNewPackageLI(pkg, parseFlags, scanMode,
5544 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 }
5546 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005547
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005548 private int setPermissionsLI(PackageParser.Package newPackage) {
5549 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005550 int retCode = 0;
5551 // TODO Gross hack but fix later. Ideally move this to be a post installation
5552 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005553 if ((newPackage.applicationInfo.flags
5554 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5555 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 try {
5557 extractPublicFiles(newPackage, destResourceFile);
5558 } catch (IOException e) {
5559 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5560 " forward-locked app.");
5561 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5562 } finally {
5563 //TODO clean up the extracted public files
5564 }
5565 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005566 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 newPackage.applicationInfo.uid);
5568 } else {
5569 final int filePermissions =
5570 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005571 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 newPackage.applicationInfo.uid);
5573 }
5574 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005575 // The permissions on the resource file was set when it was copied for
5576 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005580 Log.e(TAG, "Couldn't set new package file permissions for " +
5581 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005583 // TODO Define new internal error
5584 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 }
5586 return PackageManager.INSTALL_SUCCEEDED;
5587 }
5588
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005589 private boolean isForwardLocked(PackageParser.Package pkg) {
5590 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591 }
5592
5593 private void extractPublicFiles(PackageParser.Package newPackage,
5594 File publicZipFile) throws IOException {
5595 final ZipOutputStream publicZipOutStream =
5596 new ZipOutputStream(new FileOutputStream(publicZipFile));
5597 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5598
5599 // Copy manifest, resources.arsc and res directory to public zip
5600
5601 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5602 while (privateZipEntries.hasMoreElements()) {
5603 final ZipEntry zipEntry = privateZipEntries.nextElement();
5604 final String zipEntryName = zipEntry.getName();
5605 if ("AndroidManifest.xml".equals(zipEntryName)
5606 || "resources.arsc".equals(zipEntryName)
5607 || zipEntryName.startsWith("res/")) {
5608 try {
5609 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5610 } catch (IOException e) {
5611 try {
5612 publicZipOutStream.close();
5613 throw e;
5614 } finally {
5615 publicZipFile.delete();
5616 }
5617 }
5618 }
5619 }
5620
5621 publicZipOutStream.close();
5622 FileUtils.setPermissions(
5623 publicZipFile.getAbsolutePath(),
5624 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5625 -1, -1);
5626 }
5627
5628 private static void copyZipEntry(ZipEntry zipEntry,
5629 ZipFile inZipFile,
5630 ZipOutputStream outZipStream) throws IOException {
5631 byte[] buffer = new byte[4096];
5632 int num;
5633
5634 ZipEntry newEntry;
5635 if (zipEntry.getMethod() == ZipEntry.STORED) {
5636 // Preserve the STORED method of the input entry.
5637 newEntry = new ZipEntry(zipEntry);
5638 } else {
5639 // Create a new entry so that the compressed len is recomputed.
5640 newEntry = new ZipEntry(zipEntry.getName());
5641 }
5642 outZipStream.putNextEntry(newEntry);
5643
5644 InputStream data = inZipFile.getInputStream(zipEntry);
5645 while ((num = data.read(buffer)) > 0) {
5646 outZipStream.write(buffer, 0, num);
5647 }
5648 outZipStream.flush();
5649 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 private void deleteTempPackageFiles() {
5652 FilenameFilter filter = new FilenameFilter() {
5653 public boolean accept(File dir, String name) {
5654 return name.startsWith("vmdl") && name.endsWith(".tmp");
5655 }
5656 };
5657 String tmpFilesList[] = mAppInstallDir.list(filter);
5658 if(tmpFilesList == null) {
5659 return;
5660 }
5661 for(int i = 0; i < tmpFilesList.length; i++) {
5662 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5663 tmpFile.delete();
5664 }
5665 }
5666
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005667 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 File tmpPackageFile;
5669 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005670 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 } catch (IOException e) {
5672 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5673 return null;
5674 }
5675 try {
5676 FileUtils.setPermissions(
5677 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5678 -1, -1);
5679 } catch (IOException e) {
5680 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5681 return null;
5682 }
5683 return tmpPackageFile;
5684 }
5685
5686 public void deletePackage(final String packageName,
5687 final IPackageDeleteObserver observer,
5688 final int flags) {
5689 mContext.enforceCallingOrSelfPermission(
5690 android.Manifest.permission.DELETE_PACKAGES, null);
5691 // Queue up an async operation since the package deletion may take a little while.
5692 mHandler.post(new Runnable() {
5693 public void run() {
5694 mHandler.removeCallbacks(this);
5695 final boolean succeded = deletePackageX(packageName, true, true, flags);
5696 if (observer != null) {
5697 try {
5698 observer.packageDeleted(succeded);
5699 } catch (RemoteException e) {
5700 Log.i(TAG, "Observer no longer exists.");
5701 } //end catch
5702 } //end if
5703 } //end run
5704 });
5705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 /**
5708 * This method is an internal method that could be get invoked either
5709 * to delete an installed package or to clean up a failed installation.
5710 * After deleting an installed package, a broadcast is sent to notify any
5711 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005712 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 * installation wouldn't have sent the initial broadcast either
5714 * The key steps in deleting a package are
5715 * deleting the package information in internal structures like mPackages,
5716 * deleting the packages base directories through installd
5717 * updating mSettings to reflect current status
5718 * persisting settings for later use
5719 * sending a broadcast if necessary
5720 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5722 boolean deleteCodeAndResources, int flags) {
5723 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005724 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005726 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5727 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5728 try {
5729 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
5730 Log.w(TAG, "Not removing package " + packageName + ": has active device admin");
5731 return false;
5732 }
5733 } catch (RemoteException e) {
5734 }
5735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 synchronized (mInstallLock) {
5737 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005741 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5742 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5743
5744 // If the removed package was a system update, the old system packaged
5745 // was re-enabled; we need to broadcast this information
5746 if (systemUpdate) {
5747 Bundle extras = new Bundle(1);
5748 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5749 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5750
5751 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5752 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005755 // Force a gc here.
5756 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005757 // Delete the resources here after sending the broadcast to let
5758 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005759 if (info.args != null) {
5760 synchronized (mInstallLock) {
5761 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005762 }
5763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005764 return res;
5765 }
5766
5767 static class PackageRemovedInfo {
5768 String removedPackage;
5769 int uid = -1;
5770 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005771 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005772 // Clean up resources deleted packages.
5773 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 void sendBroadcast(boolean fullRemove, boolean replacing) {
5776 Bundle extras = new Bundle(1);
5777 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5778 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5779 if (replacing) {
5780 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5781 }
5782 if (removedPackage != null) {
5783 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5784 }
5785 if (removedUid >= 0) {
5786 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5787 }
5788 }
5789 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 /*
5792 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5793 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005794 * 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 -08005795 * delete a partially installed application.
5796 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005797 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 int flags) {
5799 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005800 if (outInfo != null) {
5801 outInfo.removedPackage = packageName;
5802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 removePackageLI(p, true);
5804 // Retrieve object to delete permissions for shared user later on
5805 PackageSetting deletedPs;
5806 synchronized (mPackages) {
5807 deletedPs = mSettings.mPackages.get(packageName);
5808 }
5809 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005810 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005812 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005813 if (retCode < 0) {
5814 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5815 + packageName + ", retcode=" + retCode);
5816 // we don't consider this to be a failure of the core package deletion
5817 }
5818 } else {
5819 //for emulator
5820 PackageParser.Package pkg = mPackages.get(packageName);
5821 File dataDir = new File(pkg.applicationInfo.dataDir);
5822 dataDir.delete();
5823 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005824 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005826 if (outInfo != null) {
5827 outInfo.removedUid = mSettings.removePackageLP(packageName);
5828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 }
5830 }
5831 synchronized (mPackages) {
5832 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5833 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005834 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005836 if (deletedPs != null) {
5837 // remove from preferred activities.
5838 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
5839 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
5840 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
5841 removed.add(pa);
5842 }
5843 }
5844 for (PreferredActivity pa : removed) {
5845 mSettings.mPreferredActivities.removeFilter(pa);
5846 }
5847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005848 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005849 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005850 }
5851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 /*
5854 * Tries to delete system package.
5855 */
5856 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005857 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 ApplicationInfo applicationInfo = p.applicationInfo;
5859 //applicable for non-partially installed applications only
5860 if (applicationInfo == null) {
5861 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5862 return false;
5863 }
5864 PackageSetting ps = null;
5865 // Confirm if the system package has been updated
5866 // An updated system app can be deleted. This will also have to restore
5867 // the system pkg from system partition
5868 synchronized (mPackages) {
5869 ps = mSettings.getDisabledSystemPkg(p.packageName);
5870 }
5871 if (ps == null) {
5872 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5873 return false;
5874 } else {
5875 Log.i(TAG, "Deleting system pkg from data partition");
5876 }
5877 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005878 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005879 boolean deleteCodeAndResources = false;
5880 if (ps.versionCode < p.mVersionCode) {
5881 // Delete code and resources for downgrades
5882 deleteCodeAndResources = true;
5883 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5884 flags &= ~PackageManager.DONT_DELETE_DATA;
5885 }
5886 } else {
5887 // Preserve data by setting flag
5888 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5889 flags |= PackageManager.DONT_DELETE_DATA;
5890 }
5891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5893 if (!ret) {
5894 return false;
5895 }
5896 synchronized (mPackages) {
5897 // Reinstate the old system package
5898 mSettings.enableSystemPackageLP(p.packageName);
5899 }
5900 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005901 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005903 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 if (newPkg == null) {
5906 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5907 return false;
5908 }
5909 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005910 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005911 mSettings.writeLP();
5912 }
5913 return true;
5914 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5917 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5918 ApplicationInfo applicationInfo = p.applicationInfo;
5919 if (applicationInfo == null) {
5920 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5921 return false;
5922 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005923 if (outInfo != null) {
5924 outInfo.uid = applicationInfo.uid;
5925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926
5927 // Delete package data from internal structures and also remove data if flag is set
5928 removePackageDataLI(p, outInfo, flags);
5929
5930 // Delete application code and resources
5931 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005932 // TODO can pick up from PackageSettings as well
5933 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005934 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005935 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5936 PackageManager.INSTALL_FORWARD_LOCK : 0;
5937 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005938 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005939 }
5940 return true;
5941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 /*
5944 * This method handles package deletion in general
5945 */
5946 private boolean deletePackageLI(String packageName,
5947 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5948 if (packageName == null) {
5949 Log.w(TAG, "Attempt to delete null packageName.");
5950 return false;
5951 }
5952 PackageParser.Package p;
5953 boolean dataOnly = false;
5954 synchronized (mPackages) {
5955 p = mPackages.get(packageName);
5956 if (p == null) {
5957 //this retrieves partially installed apps
5958 dataOnly = true;
5959 PackageSetting ps = mSettings.mPackages.get(packageName);
5960 if (ps == null) {
5961 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5962 return false;
5963 }
5964 p = ps.pkg;
5965 }
5966 }
5967 if (p == null) {
5968 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5969 return false;
5970 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 if (dataOnly) {
5973 // Delete application data first
5974 removePackageDataLI(p, outInfo, flags);
5975 return true;
5976 }
5977 // At this point the package should have ApplicationInfo associated with it
5978 if (p.applicationInfo == null) {
5979 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5980 return false;
5981 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005982 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5984 Log.i(TAG, "Removing system package:"+p.packageName);
5985 // When an updated system application is deleted we delete the existing resources as well and
5986 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005987 ret = deleteSystemPackageLI(p, flags, outInfo);
5988 } else {
5989 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005990 // Kill application pre-emptively especially for apps on sd.
5991 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005992 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005994 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 public void clearApplicationUserData(final String packageName,
5998 final IPackageDataObserver observer) {
5999 mContext.enforceCallingOrSelfPermission(
6000 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6001 // Queue up an async operation since the package deletion may take a little while.
6002 mHandler.post(new Runnable() {
6003 public void run() {
6004 mHandler.removeCallbacks(this);
6005 final boolean succeeded;
6006 synchronized (mInstallLock) {
6007 succeeded = clearApplicationUserDataLI(packageName);
6008 }
6009 if (succeeded) {
6010 // invoke DeviceStorageMonitor's update method to clear any notifications
6011 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6012 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6013 if (dsm != null) {
6014 dsm.updateMemory();
6015 }
6016 }
6017 if(observer != null) {
6018 try {
6019 observer.onRemoveCompleted(packageName, succeeded);
6020 } catch (RemoteException e) {
6021 Log.i(TAG, "Observer no longer exists.");
6022 }
6023 } //end if observer
6024 } //end run
6025 });
6026 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 private boolean clearApplicationUserDataLI(String packageName) {
6029 if (packageName == null) {
6030 Log.w(TAG, "Attempt to delete null packageName.");
6031 return false;
6032 }
6033 PackageParser.Package p;
6034 boolean dataOnly = false;
6035 synchronized (mPackages) {
6036 p = mPackages.get(packageName);
6037 if(p == null) {
6038 dataOnly = true;
6039 PackageSetting ps = mSettings.mPackages.get(packageName);
6040 if((ps == null) || (ps.pkg == null)) {
6041 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6042 return false;
6043 }
6044 p = ps.pkg;
6045 }
6046 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006047 boolean useEncryptedFSDir = false;
6048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 if(!dataOnly) {
6050 //need to check this only for fully installed applications
6051 if (p == null) {
6052 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6053 return false;
6054 }
6055 final ApplicationInfo applicationInfo = p.applicationInfo;
6056 if (applicationInfo == null) {
6057 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6058 return false;
6059 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006060 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 }
6062 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006063 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 if (retCode < 0) {
6065 Log.w(TAG, "Couldn't remove cache files for package: "
6066 + packageName);
6067 return false;
6068 }
6069 }
6070 return true;
6071 }
6072
6073 public void deleteApplicationCacheFiles(final String packageName,
6074 final IPackageDataObserver observer) {
6075 mContext.enforceCallingOrSelfPermission(
6076 android.Manifest.permission.DELETE_CACHE_FILES, null);
6077 // Queue up an async operation since the package deletion may take a little while.
6078 mHandler.post(new Runnable() {
6079 public void run() {
6080 mHandler.removeCallbacks(this);
6081 final boolean succeded;
6082 synchronized (mInstallLock) {
6083 succeded = deleteApplicationCacheFilesLI(packageName);
6084 }
6085 if(observer != null) {
6086 try {
6087 observer.onRemoveCompleted(packageName, succeded);
6088 } catch (RemoteException e) {
6089 Log.i(TAG, "Observer no longer exists.");
6090 }
6091 } //end if observer
6092 } //end run
6093 });
6094 }
6095
6096 private boolean deleteApplicationCacheFilesLI(String packageName) {
6097 if (packageName == null) {
6098 Log.w(TAG, "Attempt to delete null packageName.");
6099 return false;
6100 }
6101 PackageParser.Package p;
6102 synchronized (mPackages) {
6103 p = mPackages.get(packageName);
6104 }
6105 if (p == null) {
6106 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6107 return false;
6108 }
6109 final ApplicationInfo applicationInfo = p.applicationInfo;
6110 if (applicationInfo == null) {
6111 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6112 return false;
6113 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006114 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006116 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 if (retCode < 0) {
6118 Log.w(TAG, "Couldn't remove cache files for package: "
6119 + packageName);
6120 return false;
6121 }
6122 }
6123 return true;
6124 }
6125
6126 public void getPackageSizeInfo(final String packageName,
6127 final IPackageStatsObserver observer) {
6128 mContext.enforceCallingOrSelfPermission(
6129 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6130 // Queue up an async operation since the package deletion may take a little while.
6131 mHandler.post(new Runnable() {
6132 public void run() {
6133 mHandler.removeCallbacks(this);
6134 PackageStats lStats = new PackageStats(packageName);
6135 final boolean succeded;
6136 synchronized (mInstallLock) {
6137 succeded = getPackageSizeInfoLI(packageName, lStats);
6138 }
6139 if(observer != null) {
6140 try {
6141 observer.onGetStatsCompleted(lStats, succeded);
6142 } catch (RemoteException e) {
6143 Log.i(TAG, "Observer no longer exists.");
6144 }
6145 } //end if observer
6146 } //end run
6147 });
6148 }
6149
6150 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6151 if (packageName == null) {
6152 Log.w(TAG, "Attempt to get size of null packageName.");
6153 return false;
6154 }
6155 PackageParser.Package p;
6156 boolean dataOnly = false;
6157 synchronized (mPackages) {
6158 p = mPackages.get(packageName);
6159 if(p == null) {
6160 dataOnly = true;
6161 PackageSetting ps = mSettings.mPackages.get(packageName);
6162 if((ps == null) || (ps.pkg == null)) {
6163 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6164 return false;
6165 }
6166 p = ps.pkg;
6167 }
6168 }
6169 String publicSrcDir = null;
6170 if(!dataOnly) {
6171 final ApplicationInfo applicationInfo = p.applicationInfo;
6172 if (applicationInfo == null) {
6173 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6174 return false;
6175 }
6176 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6177 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006178 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 if (mInstaller != null) {
6180 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006181 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 if (res < 0) {
6183 return false;
6184 } else {
6185 return true;
6186 }
6187 }
6188 return true;
6189 }
6190
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 public void addPackageToPreferred(String packageName) {
6193 mContext.enforceCallingOrSelfPermission(
6194 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006195 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 }
6197
6198 public void removePackageFromPreferred(String packageName) {
6199 mContext.enforceCallingOrSelfPermission(
6200 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006201 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 }
6203
6204 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006205 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 }
6207
6208 public void addPreferredActivity(IntentFilter filter, int match,
6209 ComponentName[] set, ComponentName activity) {
6210 mContext.enforceCallingOrSelfPermission(
6211 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6212
6213 synchronized (mPackages) {
6214 Log.i(TAG, "Adding preferred activity " + activity + ":");
6215 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6216 mSettings.mPreferredActivities.addFilter(
6217 new PreferredActivity(filter, match, set, activity));
6218 mSettings.writeLP();
6219 }
6220 }
6221
Satish Sampath8dbe6122009-06-02 23:35:54 +01006222 public void replacePreferredActivity(IntentFilter filter, int match,
6223 ComponentName[] set, ComponentName activity) {
6224 mContext.enforceCallingOrSelfPermission(
6225 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6226 if (filter.countActions() != 1) {
6227 throw new IllegalArgumentException(
6228 "replacePreferredActivity expects filter to have only 1 action.");
6229 }
6230 if (filter.countCategories() != 1) {
6231 throw new IllegalArgumentException(
6232 "replacePreferredActivity expects filter to have only 1 category.");
6233 }
6234 if (filter.countDataAuthorities() != 0
6235 || filter.countDataPaths() != 0
6236 || filter.countDataSchemes() != 0
6237 || filter.countDataTypes() != 0) {
6238 throw new IllegalArgumentException(
6239 "replacePreferredActivity expects filter to have no data authorities, " +
6240 "paths, schemes or types.");
6241 }
6242 synchronized (mPackages) {
6243 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6244 String action = filter.getAction(0);
6245 String category = filter.getCategory(0);
6246 while (it.hasNext()) {
6247 PreferredActivity pa = it.next();
6248 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6249 it.remove();
6250 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6251 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6252 }
6253 }
6254 addPreferredActivity(filter, match, set, activity);
6255 }
6256 }
6257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 public void clearPackagePreferredActivities(String packageName) {
6259 mContext.enforceCallingOrSelfPermission(
6260 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6261
6262 synchronized (mPackages) {
6263 if (clearPackagePreferredActivitiesLP(packageName)) {
6264 mSettings.writeLP();
6265 }
6266 }
6267 }
6268
6269 boolean clearPackagePreferredActivitiesLP(String packageName) {
6270 boolean changed = false;
6271 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6272 while (it.hasNext()) {
6273 PreferredActivity pa = it.next();
6274 if (pa.mActivity.getPackageName().equals(packageName)) {
6275 it.remove();
6276 changed = true;
6277 }
6278 }
6279 return changed;
6280 }
6281
6282 public int getPreferredActivities(List<IntentFilter> outFilters,
6283 List<ComponentName> outActivities, String packageName) {
6284
6285 int num = 0;
6286 synchronized (mPackages) {
6287 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6288 while (it.hasNext()) {
6289 PreferredActivity pa = it.next();
6290 if (packageName == null
6291 || pa.mActivity.getPackageName().equals(packageName)) {
6292 if (outFilters != null) {
6293 outFilters.add(new IntentFilter(pa));
6294 }
6295 if (outActivities != null) {
6296 outActivities.add(pa.mActivity);
6297 }
6298 }
6299 }
6300 }
6301
6302 return num;
6303 }
6304
6305 public void setApplicationEnabledSetting(String appPackageName,
6306 int newState, int flags) {
6307 setEnabledSetting(appPackageName, null, newState, flags);
6308 }
6309
6310 public void setComponentEnabledSetting(ComponentName componentName,
6311 int newState, int flags) {
6312 setEnabledSetting(componentName.getPackageName(),
6313 componentName.getClassName(), newState, flags);
6314 }
6315
6316 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006317 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6319 || newState == COMPONENT_ENABLED_STATE_ENABLED
6320 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6321 throw new IllegalArgumentException("Invalid new component state: "
6322 + newState);
6323 }
6324 PackageSetting pkgSetting;
6325 final int uid = Binder.getCallingUid();
6326 final int permission = mContext.checkCallingPermission(
6327 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6328 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006329 boolean sendNow = false;
6330 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006331 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006333 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006335 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006337 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006339 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 }
6341 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006342 "Unknown component: " + packageName
6343 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 }
6345 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6346 throw new SecurityException(
6347 "Permission Denial: attempt to change component state from pid="
6348 + Binder.getCallingPid()
6349 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6350 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006351 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 // We're dealing with an application/package level state change
6353 pkgSetting.enabled = newState;
6354 } else {
6355 // We're dealing with a component level state change
6356 switch (newState) {
6357 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006358 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 break;
6360 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006361 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 break;
6363 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006364 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 break;
6366 default:
6367 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006368 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 }
6370 }
6371 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006372 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006373 components = mPendingBroadcasts.get(packageName);
6374 boolean newPackage = components == null;
6375 if (newPackage) {
6376 components = new ArrayList<String>();
6377 }
6378 if (!components.contains(componentName)) {
6379 components.add(componentName);
6380 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006381 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6382 sendNow = true;
6383 // Purge entry from pending broadcast list if another one exists already
6384 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006385 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006386 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006387 if (newPackage) {
6388 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006389 }
6390 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6391 // Schedule a message
6392 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6393 }
6394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 long callingId = Binder.clearCallingIdentity();
6398 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006399 if (sendNow) {
6400 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006401 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 } finally {
6404 Binder.restoreCallingIdentity(callingId);
6405 }
6406 }
6407
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006408 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006409 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6410 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6411 + " components=" + componentNames);
6412 Bundle extras = new Bundle(4);
6413 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6414 String nameList[] = new String[componentNames.size()];
6415 componentNames.toArray(nameList);
6416 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006417 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6418 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006419 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006420 }
6421
Jacek Surazski65e13172009-04-28 15:26:38 +02006422 public String getInstallerPackageName(String packageName) {
6423 synchronized (mPackages) {
6424 PackageSetting pkg = mSettings.mPackages.get(packageName);
6425 if (pkg == null) {
6426 throw new IllegalArgumentException("Unknown package: " + packageName);
6427 }
6428 return pkg.installerPackageName;
6429 }
6430 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006432 public int getApplicationEnabledSetting(String appPackageName) {
6433 synchronized (mPackages) {
6434 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6435 if (pkg == null) {
6436 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6437 }
6438 return pkg.enabled;
6439 }
6440 }
6441
6442 public int getComponentEnabledSetting(ComponentName componentName) {
6443 synchronized (mPackages) {
6444 final String packageNameStr = componentName.getPackageName();
6445 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6446 if (pkg == null) {
6447 throw new IllegalArgumentException("Unknown component: " + componentName);
6448 }
6449 final String classNameStr = componentName.getClassName();
6450 return pkg.currentEnabledStateLP(classNameStr);
6451 }
6452 }
6453
6454 public void enterSafeMode() {
6455 if (!mSystemReady) {
6456 mSafeMode = true;
6457 }
6458 }
6459
6460 public void systemReady() {
6461 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006462
6463 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006464 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006465 mContext.getContentResolver(),
6466 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006467 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006468 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006469 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 }
6472
6473 public boolean isSafeMode() {
6474 return mSafeMode;
6475 }
6476
6477 public boolean hasSystemUidErrors() {
6478 return mHasSystemUidErrors;
6479 }
6480
6481 static String arrayToString(int[] array) {
6482 StringBuffer buf = new StringBuffer(128);
6483 buf.append('[');
6484 if (array != null) {
6485 for (int i=0; i<array.length; i++) {
6486 if (i > 0) buf.append(", ");
6487 buf.append(array[i]);
6488 }
6489 }
6490 buf.append(']');
6491 return buf.toString();
6492 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 @Override
6495 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6496 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6497 != PackageManager.PERMISSION_GRANTED) {
6498 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6499 + Binder.getCallingPid()
6500 + ", uid=" + Binder.getCallingUid()
6501 + " without permission "
6502 + android.Manifest.permission.DUMP);
6503 return;
6504 }
6505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 synchronized (mPackages) {
6507 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006508 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006509 pw.println(" ");
6510 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006511 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 pw.println(" ");
6513 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006514 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 pw.println(" ");
6516 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006517 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 pw.println("Permissions:");
6520 {
6521 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006522 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6523 pw.print(Integer.toHexString(System.identityHashCode(p)));
6524 pw.println("):");
6525 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6526 pw.print(" uid="); pw.print(p.uid);
6527 pw.print(" gids="); pw.print(arrayToString(p.gids));
6528 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 }
6530 }
6531 pw.println(" ");
6532 pw.println("Packages:");
6533 {
6534 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006535 pw.print(" Package [");
6536 pw.print(ps.realName != null ? ps.realName : ps.name);
6537 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006538 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6539 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006540 if (ps.realName != null) {
6541 pw.print(" compat name="); pw.println(ps.name);
6542 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006543 pw.print(" userId="); pw.print(ps.userId);
6544 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6545 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6546 pw.print(" pkg="); pw.println(ps.pkg);
6547 pw.print(" codePath="); pw.println(ps.codePathString);
6548 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006550 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006551 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006552 pw.print(" supportsScreens=[");
6553 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006554 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006555 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006556 if (!first) pw.print(", ");
6557 first = false;
6558 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006560 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006561 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006562 if (!first) pw.print(", ");
6563 first = false;
6564 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006565 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006566 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006567 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006568 if (!first) pw.print(", ");
6569 first = false;
6570 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006571 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006572 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006573 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006574 if (!first) pw.print(", ");
6575 first = false;
6576 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006578 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006579 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6580 if (!first) pw.print(", ");
6581 first = false;
6582 pw.print("anyDensity");
6583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006585 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006586 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6587 pw.print(" signatures="); pw.println(ps.signatures);
6588 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6589 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6590 pw.print(" installStatus="); pw.print(ps.installStatus);
6591 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 if (ps.disabledComponents.size() > 0) {
6593 pw.println(" disabledComponents:");
6594 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006595 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 }
6597 }
6598 if (ps.enabledComponents.size() > 0) {
6599 pw.println(" enabledComponents:");
6600 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006601 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 }
6603 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006604 if (ps.grantedPermissions.size() > 0) {
6605 pw.println(" grantedPermissions:");
6606 for (String s : ps.grantedPermissions) {
6607 pw.print(" "); pw.println(s);
6608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006610 if (ps.loadedPermissions.size() > 0) {
6611 pw.println(" loadedPermissions:");
6612 for (String s : ps.loadedPermissions) {
6613 pw.print(" "); pw.println(s);
6614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 }
6616 }
6617 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006618 if (mSettings.mRenamedPackages.size() > 0) {
6619 pw.println(" ");
6620 pw.println("Renamed packages:");
6621 for (HashMap.Entry<String, String> e
6622 : mSettings.mRenamedPackages.entrySet()) {
6623 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6624 pw.println(e.getValue());
6625 }
6626 }
6627 if (mSettings.mDisabledSysPackages.size() > 0) {
6628 pw.println(" ");
6629 pw.println("Hidden system packages:");
6630 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6631 pw.print(" Package [");
6632 pw.print(ps.realName != null ? ps.realName : ps.name);
6633 pw.print("] (");
6634 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6635 pw.println("):");
6636 if (ps.realName != null) {
6637 pw.print(" compat name="); pw.println(ps.name);
6638 }
6639 pw.print(" userId="); pw.println(ps.userId);
6640 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6641 pw.print(" codePath="); pw.println(ps.codePathString);
6642 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6643 }
6644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 pw.println(" ");
6646 pw.println("Shared Users:");
6647 {
6648 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006649 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6650 pw.print(Integer.toHexString(System.identityHashCode(su)));
6651 pw.println("):");
6652 pw.print(" userId="); pw.print(su.userId);
6653 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006654 pw.println(" grantedPermissions:");
6655 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006656 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657 }
6658 pw.println(" loadedPermissions:");
6659 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006660 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 }
6662 }
6663 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 pw.println(" ");
6666 pw.println("Settings parse messages:");
6667 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006668
6669 pw.println(" ");
6670 pw.println("Package warning messages:");
6671 File fname = getSettingsProblemFile();
6672 FileInputStream in;
6673 try {
6674 in = new FileInputStream(fname);
6675 int avail = in.available();
6676 byte[] data = new byte[avail];
6677 in.read(data);
6678 pw.println(new String(data));
6679 } catch (FileNotFoundException e) {
6680 } catch (IOException e) {
6681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006682 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006683
6684 synchronized (mProviders) {
6685 pw.println(" ");
6686 pw.println("Registered ContentProviders:");
6687 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006688 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006689 pw.println(p.toString());
6690 }
6691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 }
6693
6694 static final class BasePermission {
6695 final static int TYPE_NORMAL = 0;
6696 final static int TYPE_BUILTIN = 1;
6697 final static int TYPE_DYNAMIC = 2;
6698
6699 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006700 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 final int type;
6702 PackageParser.Permission perm;
6703 PermissionInfo pendingInfo;
6704 int uid;
6705 int[] gids;
6706
6707 BasePermission(String _name, String _sourcePackage, int _type) {
6708 name = _name;
6709 sourcePackage = _sourcePackage;
6710 type = _type;
6711 }
6712 }
6713
6714 static class PackageSignatures {
6715 private Signature[] mSignatures;
6716
6717 PackageSignatures(Signature[] sigs) {
6718 assignSignatures(sigs);
6719 }
6720
6721 PackageSignatures() {
6722 }
6723
6724 void writeXml(XmlSerializer serializer, String tagName,
6725 ArrayList<Signature> pastSignatures) throws IOException {
6726 if (mSignatures == null) {
6727 return;
6728 }
6729 serializer.startTag(null, tagName);
6730 serializer.attribute(null, "count",
6731 Integer.toString(mSignatures.length));
6732 for (int i=0; i<mSignatures.length; i++) {
6733 serializer.startTag(null, "cert");
6734 final Signature sig = mSignatures[i];
6735 final int sigHash = sig.hashCode();
6736 final int numPast = pastSignatures.size();
6737 int j;
6738 for (j=0; j<numPast; j++) {
6739 Signature pastSig = pastSignatures.get(j);
6740 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6741 serializer.attribute(null, "index", Integer.toString(j));
6742 break;
6743 }
6744 }
6745 if (j >= numPast) {
6746 pastSignatures.add(sig);
6747 serializer.attribute(null, "index", Integer.toString(numPast));
6748 serializer.attribute(null, "key", sig.toCharsString());
6749 }
6750 serializer.endTag(null, "cert");
6751 }
6752 serializer.endTag(null, tagName);
6753 }
6754
6755 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6756 throws IOException, XmlPullParserException {
6757 String countStr = parser.getAttributeValue(null, "count");
6758 if (countStr == null) {
6759 reportSettingsProblem(Log.WARN,
6760 "Error in package manager settings: <signatures> has"
6761 + " no count at " + parser.getPositionDescription());
6762 XmlUtils.skipCurrentTag(parser);
6763 }
6764 final int count = Integer.parseInt(countStr);
6765 mSignatures = new Signature[count];
6766 int pos = 0;
6767
6768 int outerDepth = parser.getDepth();
6769 int type;
6770 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6771 && (type != XmlPullParser.END_TAG
6772 || parser.getDepth() > outerDepth)) {
6773 if (type == XmlPullParser.END_TAG
6774 || type == XmlPullParser.TEXT) {
6775 continue;
6776 }
6777
6778 String tagName = parser.getName();
6779 if (tagName.equals("cert")) {
6780 if (pos < count) {
6781 String index = parser.getAttributeValue(null, "index");
6782 if (index != null) {
6783 try {
6784 int idx = Integer.parseInt(index);
6785 String key = parser.getAttributeValue(null, "key");
6786 if (key == null) {
6787 if (idx >= 0 && idx < pastSignatures.size()) {
6788 Signature sig = pastSignatures.get(idx);
6789 if (sig != null) {
6790 mSignatures[pos] = pastSignatures.get(idx);
6791 pos++;
6792 } else {
6793 reportSettingsProblem(Log.WARN,
6794 "Error in package manager settings: <cert> "
6795 + "index " + index + " is not defined at "
6796 + parser.getPositionDescription());
6797 }
6798 } else {
6799 reportSettingsProblem(Log.WARN,
6800 "Error in package manager settings: <cert> "
6801 + "index " + index + " is out of bounds at "
6802 + parser.getPositionDescription());
6803 }
6804 } else {
6805 while (pastSignatures.size() <= idx) {
6806 pastSignatures.add(null);
6807 }
6808 Signature sig = new Signature(key);
6809 pastSignatures.set(idx, sig);
6810 mSignatures[pos] = sig;
6811 pos++;
6812 }
6813 } catch (NumberFormatException e) {
6814 reportSettingsProblem(Log.WARN,
6815 "Error in package manager settings: <cert> "
6816 + "index " + index + " is not a number at "
6817 + parser.getPositionDescription());
6818 }
6819 } else {
6820 reportSettingsProblem(Log.WARN,
6821 "Error in package manager settings: <cert> has"
6822 + " no index at " + parser.getPositionDescription());
6823 }
6824 } else {
6825 reportSettingsProblem(Log.WARN,
6826 "Error in package manager settings: too "
6827 + "many <cert> tags, expected " + count
6828 + " at " + parser.getPositionDescription());
6829 }
6830 } else {
6831 reportSettingsProblem(Log.WARN,
6832 "Unknown element under <cert>: "
6833 + parser.getName());
6834 }
6835 XmlUtils.skipCurrentTag(parser);
6836 }
6837
6838 if (pos < count) {
6839 // Should never happen -- there is an error in the written
6840 // settings -- but if it does we don't want to generate
6841 // a bad array.
6842 Signature[] newSigs = new Signature[pos];
6843 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6844 mSignatures = newSigs;
6845 }
6846 }
6847
6848 /**
6849 * If any of the given 'sigs' is contained in the existing signatures,
6850 * then completely replace the current signatures with the ones in
6851 * 'sigs'. This is used for updating an existing package to a newly
6852 * installed version.
6853 */
6854 boolean updateSignatures(Signature[] sigs, boolean update) {
6855 if (mSignatures == null) {
6856 if (update) {
6857 assignSignatures(sigs);
6858 }
6859 return true;
6860 }
6861 if (sigs == null) {
6862 return false;
6863 }
6864
6865 for (int i=0; i<sigs.length; i++) {
6866 Signature sig = sigs[i];
6867 for (int j=0; j<mSignatures.length; j++) {
6868 if (mSignatures[j].equals(sig)) {
6869 if (update) {
6870 assignSignatures(sigs);
6871 }
6872 return true;
6873 }
6874 }
6875 }
6876 return false;
6877 }
6878
6879 /**
6880 * If any of the given 'sigs' is contained in the existing signatures,
6881 * then add in any new signatures found in 'sigs'. This is used for
6882 * including a new package into an existing shared user id.
6883 */
6884 boolean mergeSignatures(Signature[] sigs, boolean update) {
6885 if (mSignatures == null) {
6886 if (update) {
6887 assignSignatures(sigs);
6888 }
6889 return true;
6890 }
6891 if (sigs == null) {
6892 return false;
6893 }
6894
6895 Signature[] added = null;
6896 int addedCount = 0;
6897 boolean haveMatch = false;
6898 for (int i=0; i<sigs.length; i++) {
6899 Signature sig = sigs[i];
6900 boolean found = false;
6901 for (int j=0; j<mSignatures.length; j++) {
6902 if (mSignatures[j].equals(sig)) {
6903 found = true;
6904 haveMatch = true;
6905 break;
6906 }
6907 }
6908
6909 if (!found) {
6910 if (added == null) {
6911 added = new Signature[sigs.length];
6912 }
6913 added[i] = sig;
6914 addedCount++;
6915 }
6916 }
6917
6918 if (!haveMatch) {
6919 // Nothing matched -- reject the new signatures.
6920 return false;
6921 }
6922 if (added == null) {
6923 // Completely matched -- nothing else to do.
6924 return true;
6925 }
6926
6927 // Add additional signatures in.
6928 if (update) {
6929 Signature[] total = new Signature[addedCount+mSignatures.length];
6930 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6931 int j = mSignatures.length;
6932 for (int i=0; i<added.length; i++) {
6933 if (added[i] != null) {
6934 total[j] = added[i];
6935 j++;
6936 }
6937 }
6938 mSignatures = total;
6939 }
6940 return true;
6941 }
6942
6943 private void assignSignatures(Signature[] sigs) {
6944 if (sigs == null) {
6945 mSignatures = null;
6946 return;
6947 }
6948 mSignatures = new Signature[sigs.length];
6949 for (int i=0; i<sigs.length; i++) {
6950 mSignatures[i] = sigs[i];
6951 }
6952 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954 @Override
6955 public String toString() {
6956 StringBuffer buf = new StringBuffer(128);
6957 buf.append("PackageSignatures{");
6958 buf.append(Integer.toHexString(System.identityHashCode(this)));
6959 buf.append(" [");
6960 if (mSignatures != null) {
6961 for (int i=0; i<mSignatures.length; i++) {
6962 if (i > 0) buf.append(", ");
6963 buf.append(Integer.toHexString(
6964 System.identityHashCode(mSignatures[i])));
6965 }
6966 }
6967 buf.append("]}");
6968 return buf.toString();
6969 }
6970 }
6971
6972 static class PreferredActivity extends IntentFilter {
6973 final int mMatch;
6974 final String[] mSetPackages;
6975 final String[] mSetClasses;
6976 final String[] mSetComponents;
6977 final ComponentName mActivity;
6978 final String mShortActivity;
6979 String mParseError;
6980
6981 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6982 ComponentName activity) {
6983 super(filter);
6984 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6985 mActivity = activity;
6986 mShortActivity = activity.flattenToShortString();
6987 mParseError = null;
6988 if (set != null) {
6989 final int N = set.length;
6990 String[] myPackages = new String[N];
6991 String[] myClasses = new String[N];
6992 String[] myComponents = new String[N];
6993 for (int i=0; i<N; i++) {
6994 ComponentName cn = set[i];
6995 if (cn == null) {
6996 mSetPackages = null;
6997 mSetClasses = null;
6998 mSetComponents = null;
6999 return;
7000 }
7001 myPackages[i] = cn.getPackageName().intern();
7002 myClasses[i] = cn.getClassName().intern();
7003 myComponents[i] = cn.flattenToShortString().intern();
7004 }
7005 mSetPackages = myPackages;
7006 mSetClasses = myClasses;
7007 mSetComponents = myComponents;
7008 } else {
7009 mSetPackages = null;
7010 mSetClasses = null;
7011 mSetComponents = null;
7012 }
7013 }
7014
7015 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7016 IOException {
7017 mShortActivity = parser.getAttributeValue(null, "name");
7018 mActivity = ComponentName.unflattenFromString(mShortActivity);
7019 if (mActivity == null) {
7020 mParseError = "Bad activity name " + mShortActivity;
7021 }
7022 String matchStr = parser.getAttributeValue(null, "match");
7023 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7024 String setCountStr = parser.getAttributeValue(null, "set");
7025 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7026
7027 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7028 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7029 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7030
7031 int setPos = 0;
7032
7033 int outerDepth = parser.getDepth();
7034 int type;
7035 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7036 && (type != XmlPullParser.END_TAG
7037 || parser.getDepth() > outerDepth)) {
7038 if (type == XmlPullParser.END_TAG
7039 || type == XmlPullParser.TEXT) {
7040 continue;
7041 }
7042
7043 String tagName = parser.getName();
7044 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7045 // + parser.getDepth() + " tag=" + tagName);
7046 if (tagName.equals("set")) {
7047 String name = parser.getAttributeValue(null, "name");
7048 if (name == null) {
7049 if (mParseError == null) {
7050 mParseError = "No name in set tag in preferred activity "
7051 + mShortActivity;
7052 }
7053 } else if (setPos >= setCount) {
7054 if (mParseError == null) {
7055 mParseError = "Too many set tags in preferred activity "
7056 + mShortActivity;
7057 }
7058 } else {
7059 ComponentName cn = ComponentName.unflattenFromString(name);
7060 if (cn == null) {
7061 if (mParseError == null) {
7062 mParseError = "Bad set name " + name + " in preferred activity "
7063 + mShortActivity;
7064 }
7065 } else {
7066 myPackages[setPos] = cn.getPackageName();
7067 myClasses[setPos] = cn.getClassName();
7068 myComponents[setPos] = name;
7069 setPos++;
7070 }
7071 }
7072 XmlUtils.skipCurrentTag(parser);
7073 } else if (tagName.equals("filter")) {
7074 //Log.i(TAG, "Starting to parse filter...");
7075 readFromXml(parser);
7076 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7077 // + parser.getDepth() + " tag=" + parser.getName());
7078 } else {
7079 reportSettingsProblem(Log.WARN,
7080 "Unknown element under <preferred-activities>: "
7081 + parser.getName());
7082 XmlUtils.skipCurrentTag(parser);
7083 }
7084 }
7085
7086 if (setPos != setCount) {
7087 if (mParseError == null) {
7088 mParseError = "Not enough set tags (expected " + setCount
7089 + " but found " + setPos + ") in " + mShortActivity;
7090 }
7091 }
7092
7093 mSetPackages = myPackages;
7094 mSetClasses = myClasses;
7095 mSetComponents = myComponents;
7096 }
7097
7098 public void writeToXml(XmlSerializer serializer) throws IOException {
7099 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7100 serializer.attribute(null, "name", mShortActivity);
7101 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7102 serializer.attribute(null, "set", Integer.toString(NS));
7103 for (int s=0; s<NS; s++) {
7104 serializer.startTag(null, "set");
7105 serializer.attribute(null, "name", mSetComponents[s]);
7106 serializer.endTag(null, "set");
7107 }
7108 serializer.startTag(null, "filter");
7109 super.writeToXml(serializer);
7110 serializer.endTag(null, "filter");
7111 }
7112
7113 boolean sameSet(List<ResolveInfo> query, int priority) {
7114 if (mSetPackages == null) return false;
7115 final int NQ = query.size();
7116 final int NS = mSetPackages.length;
7117 int numMatch = 0;
7118 for (int i=0; i<NQ; i++) {
7119 ResolveInfo ri = query.get(i);
7120 if (ri.priority != priority) continue;
7121 ActivityInfo ai = ri.activityInfo;
7122 boolean good = false;
7123 for (int j=0; j<NS; j++) {
7124 if (mSetPackages[j].equals(ai.packageName)
7125 && mSetClasses[j].equals(ai.name)) {
7126 numMatch++;
7127 good = true;
7128 break;
7129 }
7130 }
7131 if (!good) return false;
7132 }
7133 return numMatch == NS;
7134 }
7135 }
7136
7137 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007138 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007140 HashSet<String> grantedPermissions = new HashSet<String>();
7141 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007143 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007145 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007146 setFlags(pkgFlags);
7147 }
7148
7149 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007150 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007151 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08007152 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD) |
7153 (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007154 }
7155 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007157 /**
7158 * Settings base class for pending and resolved classes.
7159 */
7160 static class PackageSettingBase extends GrantedPermissions {
7161 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007162 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007163 File codePath;
7164 String codePathString;
7165 File resourcePath;
7166 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007167 private long timeStamp;
7168 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007169 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007170
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007171 boolean uidError;
7172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007173 PackageSignatures signatures = new PackageSignatures();
7174
7175 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 /* Explicitly disabled components */
7178 HashSet<String> disabledComponents = new HashSet<String>(0);
7179 /* Explicitly enabled components */
7180 HashSet<String> enabledComponents = new HashSet<String>(0);
7181 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7182 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007183
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007184 PackageSettingBase origPackage;
7185
Jacek Surazski65e13172009-04-28 15:26:38 +02007186 /* package name of the app that installed this package */
7187 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007188
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007189 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007190 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007191 super(pkgFlags);
7192 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007193 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007194 init(codePath, resourcePath, pVersionCode);
7195 }
7196
7197 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007198 this.codePath = codePath;
7199 this.codePathString = codePath.toString();
7200 this.resourcePath = resourcePath;
7201 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007202 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007203 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007204
Jacek Surazski65e13172009-04-28 15:26:38 +02007205 public void setInstallerPackageName(String packageName) {
7206 installerPackageName = packageName;
7207 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007208
Jacek Surazski65e13172009-04-28 15:26:38 +02007209 String getInstallerPackageName() {
7210 return installerPackageName;
7211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213 public void setInstallStatus(int newStatus) {
7214 installStatus = newStatus;
7215 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007217 public int getInstallStatus() {
7218 return installStatus;
7219 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 public void setTimeStamp(long newStamp) {
7222 if (newStamp != timeStamp) {
7223 timeStamp = newStamp;
7224 timeStampString = Long.toString(newStamp);
7225 }
7226 }
7227
7228 public void setTimeStamp(long newStamp, String newStampStr) {
7229 timeStamp = newStamp;
7230 timeStampString = newStampStr;
7231 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007233 public long getTimeStamp() {
7234 return timeStamp;
7235 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007237 public String getTimeStampStr() {
7238 return timeStampString;
7239 }
7240
7241 public void copyFrom(PackageSettingBase base) {
7242 grantedPermissions = base.grantedPermissions;
7243 gids = base.gids;
7244 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007246 timeStamp = base.timeStamp;
7247 timeStampString = base.timeStampString;
7248 signatures = base.signatures;
7249 permissionsFixed = base.permissionsFixed;
7250 disabledComponents = base.disabledComponents;
7251 enabledComponents = base.enabledComponents;
7252 enabled = base.enabled;
7253 installStatus = base.installStatus;
7254 }
7255
7256 void enableComponentLP(String componentClassName) {
7257 disabledComponents.remove(componentClassName);
7258 enabledComponents.add(componentClassName);
7259 }
7260
7261 void disableComponentLP(String componentClassName) {
7262 enabledComponents.remove(componentClassName);
7263 disabledComponents.add(componentClassName);
7264 }
7265
7266 void restoreComponentLP(String componentClassName) {
7267 enabledComponents.remove(componentClassName);
7268 disabledComponents.remove(componentClassName);
7269 }
7270
7271 int currentEnabledStateLP(String componentName) {
7272 if (enabledComponents.contains(componentName)) {
7273 return COMPONENT_ENABLED_STATE_ENABLED;
7274 } else if (disabledComponents.contains(componentName)) {
7275 return COMPONENT_ENABLED_STATE_DISABLED;
7276 } else {
7277 return COMPONENT_ENABLED_STATE_DEFAULT;
7278 }
7279 }
7280 }
7281
7282 /**
7283 * Settings data for a particular package we know about.
7284 */
7285 static final class PackageSetting extends PackageSettingBase {
7286 int userId;
7287 PackageParser.Package pkg;
7288 SharedUserSetting sharedUser;
7289
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007290 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007291 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007292 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007293 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 @Override
7296 public String toString() {
7297 return "PackageSetting{"
7298 + Integer.toHexString(System.identityHashCode(this))
7299 + " " + name + "/" + userId + "}";
7300 }
7301 }
7302
7303 /**
7304 * Settings data for a particular shared user ID we know about.
7305 */
7306 static final class SharedUserSetting extends GrantedPermissions {
7307 final String name;
7308 int userId;
7309 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7310 final PackageSignatures signatures = new PackageSignatures();
7311
7312 SharedUserSetting(String _name, int _pkgFlags) {
7313 super(_pkgFlags);
7314 name = _name;
7315 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007317 @Override
7318 public String toString() {
7319 return "SharedUserSetting{"
7320 + Integer.toHexString(System.identityHashCode(this))
7321 + " " + name + "/" + userId + "}";
7322 }
7323 }
7324
7325 /**
7326 * Holds information about dynamic settings.
7327 */
7328 private static final class Settings {
7329 private final File mSettingsFilename;
7330 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007331 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007332 private final HashMap<String, PackageSetting> mPackages =
7333 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 // List of replaced system applications
7335 final HashMap<String, PackageSetting> mDisabledSysPackages =
7336 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007338 // The user's preferred activities associated with particular intent
7339 // filters.
7340 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7341 new IntentResolver<PreferredActivity, PreferredActivity>() {
7342 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007343 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007345 out.print(prefix); out.print(
7346 Integer.toHexString(System.identityHashCode(filter)));
7347 out.print(' ');
7348 out.print(filter.mActivity.flattenToShortString());
7349 out.print(" match=0x");
7350 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007352 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007353 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007354 out.print(prefix); out.print(" ");
7355 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007356 }
7357 }
7358 }
7359 };
7360 private final HashMap<String, SharedUserSetting> mSharedUsers =
7361 new HashMap<String, SharedUserSetting>();
7362 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7363 private final SparseArray<Object> mOtherUserIds =
7364 new SparseArray<Object>();
7365
7366 // For reading/writing settings file.
7367 private final ArrayList<Signature> mPastSignatures =
7368 new ArrayList<Signature>();
7369
7370 // Mapping from permission names to info about them.
7371 final HashMap<String, BasePermission> mPermissions =
7372 new HashMap<String, BasePermission>();
7373
7374 // Mapping from permission tree names to info about them.
7375 final HashMap<String, BasePermission> mPermissionTrees =
7376 new HashMap<String, BasePermission>();
7377
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007378 // Packages that have been uninstalled and still need their external
7379 // storage data deleted.
7380 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7381
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007382 // Packages that have been renamed since they were first installed.
7383 // Keys are the new names of the packages, values are the original
7384 // names. The packages appear everwhere else under their original
7385 // names.
7386 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007388 private final StringBuilder mReadMessages = new StringBuilder();
7389
7390 private static final class PendingPackage extends PackageSettingBase {
7391 final int sharedId;
7392
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007393 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007394 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007395 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 this.sharedId = sharedId;
7397 }
7398 }
7399 private final ArrayList<PendingPackage> mPendingPackages
7400 = new ArrayList<PendingPackage>();
7401
7402 Settings() {
7403 File dataDir = Environment.getDataDirectory();
7404 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007405 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7406 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007407 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007408 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 FileUtils.setPermissions(systemDir.toString(),
7410 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7411 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7412 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007413 FileUtils.setPermissions(systemSecureDir.toString(),
7414 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7415 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7416 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007417 mSettingsFilename = new File(systemDir, "packages.xml");
7418 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007419 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007420 }
7421
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007422 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007423 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007424 int pkgFlags, boolean create, boolean add) {
7425 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007426 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007427 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007428 return p;
7429 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007430
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007431 PackageSetting peekPackageLP(String name) {
7432 return mPackages.get(name);
7433 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007434 PackageSetting p = mPackages.get(name);
7435 if (p != null && p.codePath.getPath().equals(codePath)) {
7436 return p;
7437 }
7438 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007439 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007442 void setInstallStatus(String pkgName, int status) {
7443 PackageSetting p = mPackages.get(pkgName);
7444 if(p != null) {
7445 if(p.getInstallStatus() != status) {
7446 p.setInstallStatus(status);
7447 }
7448 }
7449 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007450
Jacek Surazski65e13172009-04-28 15:26:38 +02007451 void setInstallerPackageName(String pkgName,
7452 String installerPkgName) {
7453 PackageSetting p = mPackages.get(pkgName);
7454 if(p != null) {
7455 p.setInstallerPackageName(installerPkgName);
7456 }
7457 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007458
Jacek Surazski65e13172009-04-28 15:26:38 +02007459 String getInstallerPackageName(String pkgName) {
7460 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007461 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007462 }
7463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007464 int getInstallStatus(String pkgName) {
7465 PackageSetting p = mPackages.get(pkgName);
7466 if(p != null) {
7467 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 return -1;
7470 }
7471
7472 SharedUserSetting getSharedUserLP(String name,
7473 int pkgFlags, boolean create) {
7474 SharedUserSetting s = mSharedUsers.get(name);
7475 if (s == null) {
7476 if (!create) {
7477 return null;
7478 }
7479 s = new SharedUserSetting(name, pkgFlags);
7480 if (MULTIPLE_APPLICATION_UIDS) {
7481 s.userId = newUserIdLP(s);
7482 } else {
7483 s.userId = FIRST_APPLICATION_UID;
7484 }
7485 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7486 // < 0 means we couldn't assign a userid; fall out and return
7487 // s, which is currently null
7488 if (s.userId >= 0) {
7489 mSharedUsers.put(name, s);
7490 }
7491 }
7492
7493 return s;
7494 }
7495
7496 int disableSystemPackageLP(String name) {
7497 PackageSetting p = mPackages.get(name);
7498 if(p == null) {
7499 Log.w(TAG, "Package:"+name+" is not an installed package");
7500 return -1;
7501 }
7502 PackageSetting dp = mDisabledSysPackages.get(name);
7503 // always make sure the system package code and resource paths dont change
7504 if(dp == null) {
7505 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7506 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7507 }
7508 mDisabledSysPackages.put(name, p);
7509 }
7510 return removePackageLP(name);
7511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007513 PackageSetting enableSystemPackageLP(String name) {
7514 PackageSetting p = mDisabledSysPackages.get(name);
7515 if(p == null) {
7516 Log.w(TAG, "Package:"+name+" is not disabled");
7517 return null;
7518 }
7519 // Reset flag in ApplicationInfo object
7520 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7521 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7522 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007523 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007524 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007525 mDisabledSysPackages.remove(name);
7526 return ret;
7527 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007528
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007529 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007530 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007531 PackageSetting p = mPackages.get(name);
7532 if (p != null) {
7533 if (p.userId == uid) {
7534 return p;
7535 }
7536 reportSettingsProblem(Log.ERROR,
7537 "Adding duplicate package, keeping first: " + name);
7538 return null;
7539 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007540 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007541 p.userId = uid;
7542 if (addUserIdLP(uid, p, name)) {
7543 mPackages.put(name, p);
7544 return p;
7545 }
7546 return null;
7547 }
7548
7549 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7550 SharedUserSetting s = mSharedUsers.get(name);
7551 if (s != null) {
7552 if (s.userId == uid) {
7553 return s;
7554 }
7555 reportSettingsProblem(Log.ERROR,
7556 "Adding duplicate shared user, keeping first: " + name);
7557 return null;
7558 }
7559 s = new SharedUserSetting(name, pkgFlags);
7560 s.userId = uid;
7561 if (addUserIdLP(uid, s, name)) {
7562 mSharedUsers.put(name, s);
7563 return s;
7564 }
7565 return null;
7566 }
7567
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007568 // Transfer ownership of permissions from one package to another.
7569 private void transferPermissions(String origPkg, String newPkg) {
7570 // Transfer ownership of permissions to the new package.
7571 for (int i=0; i<2; i++) {
7572 HashMap<String, BasePermission> permissions =
7573 i == 0 ? mPermissionTrees : mPermissions;
7574 for (BasePermission bp : permissions.values()) {
7575 if (origPkg.equals(bp.sourcePackage)) {
7576 if (DEBUG_UPGRADE) Log.v(TAG,
7577 "Moving permission " + bp.name
7578 + " from pkg " + bp.sourcePackage
7579 + " to " + newPkg);
7580 bp.sourcePackage = newPkg;
7581 bp.perm = null;
7582 if (bp.pendingInfo != null) {
7583 bp.sourcePackage = newPkg;
7584 }
7585 bp.uid = 0;
7586 bp.gids = null;
7587 }
7588 }
7589 }
7590 }
7591
7592 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007593 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007594 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007595 PackageSetting p = mPackages.get(name);
7596 if (p != null) {
7597 if (!p.codePath.equals(codePath)) {
7598 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007599 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007600 // This is an updated system app with versions in both system
7601 // and data partition. Just let the most recent version
7602 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007603 Log.w(TAG, "Trying to update system app code path from " +
7604 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007605 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007606 // Just a change in the code path is not an issue, but
7607 // let's log a message about it.
7608 Log.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007609 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007610 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007611 }
7612 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 reportSettingsProblem(Log.WARN,
7614 "Package " + name + " shared user changed from "
7615 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7616 + " to "
7617 + (sharedUser != null ? sharedUser.name : "<nothing>")
7618 + "; replacing with new");
7619 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007620 } else {
7621 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7622 // If what we are scanning is a system package, then
7623 // make it so, regardless of whether it was previously
7624 // installed only in the data partition.
7625 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 }
7628 }
7629 if (p == null) {
7630 // Create a new PackageSettings entry. this can end up here because
7631 // of code path mismatch or user id mismatch of an updated system partition
7632 if (!create) {
7633 return null;
7634 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007635 if (origPackage != null) {
7636 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007637 p = new PackageSetting(origPackage.name, name, codePath,
7638 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007639 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7640 + " is adopting original package " + origPackage.name);
7641 p.copyFrom(origPackage);
7642 p.sharedUser = origPackage.sharedUser;
7643 p.userId = origPackage.userId;
7644 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007645 mRenamedPackages.put(name, origPackage.name);
7646 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007647 // Update new package state.
7648 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007650 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007651 p.setTimeStamp(codePath.lastModified());
7652 p.sharedUser = sharedUser;
7653 if (sharedUser != null) {
7654 p.userId = sharedUser.userId;
7655 } else if (MULTIPLE_APPLICATION_UIDS) {
7656 // Clone the setting here for disabled system packages
7657 PackageSetting dis = mDisabledSysPackages.get(name);
7658 if (dis != null) {
7659 // For disabled packages a new setting is created
7660 // from the existing user id. This still has to be
7661 // added to list of user id's
7662 // Copy signatures from previous setting
7663 if (dis.signatures.mSignatures != null) {
7664 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7665 }
7666 p.userId = dis.userId;
7667 // Clone permissions
7668 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7669 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7670 // Clone component info
7671 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7672 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7673 // Add new setting to list of user ids
7674 addUserIdLP(p.userId, p, name);
7675 } else {
7676 // Assign new user id
7677 p.userId = newUserIdLP(p);
7678 }
7679 } else {
7680 p.userId = FIRST_APPLICATION_UID;
7681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 }
7683 if (p.userId < 0) {
7684 reportSettingsProblem(Log.WARN,
7685 "Package " + name + " could not be assigned a valid uid");
7686 return null;
7687 }
7688 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007689 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007691 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 }
7693 }
7694 return p;
7695 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007696
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007697 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007698 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007699 String codePath = pkg.applicationInfo.sourceDir;
7700 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007701 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007702 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007703 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007704 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007705 p.codePath = new File(codePath);
7706 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007707 }
7708 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007709 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007710 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007711 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007712 p.resourcePath = new File(resourcePath);
7713 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007714 }
7715 // Update version code if needed
7716 if (pkg.mVersionCode != p.versionCode) {
7717 p.versionCode = pkg.mVersionCode;
7718 }
7719 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7720 }
7721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 // Utility method that adds a PackageSetting to mPackages and
7723 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007724 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007725 SharedUserSetting sharedUser) {
7726 mPackages.put(name, p);
7727 if (sharedUser != null) {
7728 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7729 reportSettingsProblem(Log.ERROR,
7730 "Package " + p.name + " was user "
7731 + p.sharedUser + " but is now " + sharedUser
7732 + "; I am not changing its files so it will probably fail!");
7733 p.sharedUser.packages.remove(p);
7734 } else if (p.userId != sharedUser.userId) {
7735 reportSettingsProblem(Log.ERROR,
7736 "Package " + p.name + " was user id " + p.userId
7737 + " but is now user " + sharedUser
7738 + " with id " + sharedUser.userId
7739 + "; I am not changing its files so it will probably fail!");
7740 }
7741
7742 sharedUser.packages.add(p);
7743 p.sharedUser = sharedUser;
7744 p.userId = sharedUser.userId;
7745 }
7746 }
7747
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007748 /*
7749 * Update the shared user setting when a package using
7750 * specifying the shared user id is removed. The gids
7751 * associated with each permission of the deleted package
7752 * are removed from the shared user's gid list only if its
7753 * not in use by other permissions of packages in the
7754 * shared user setting.
7755 */
7756 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007757 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7758 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7759 return;
7760 }
7761 // No sharedUserId
7762 if (deletedPs.sharedUser == null) {
7763 return;
7764 }
7765 SharedUserSetting sus = deletedPs.sharedUser;
7766 // Update permissions
7767 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7768 boolean used = false;
7769 if (!sus.grantedPermissions.contains (eachPerm)) {
7770 continue;
7771 }
7772 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007773 if (pkg.pkg != null &&
7774 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7775 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 used = true;
7777 break;
7778 }
7779 }
7780 if (!used) {
7781 // can safely delete this permission from list
7782 sus.grantedPermissions.remove(eachPerm);
7783 sus.loadedPermissions.remove(eachPerm);
7784 }
7785 }
7786 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007787 int newGids[] = globalGids;
7788 for (String eachPerm : sus.grantedPermissions) {
7789 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007790 if (bp != null) {
7791 newGids = appendInts(newGids, bp.gids);
7792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 }
7794 sus.gids = newGids;
7795 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 private int removePackageLP(String name) {
7798 PackageSetting p = mPackages.get(name);
7799 if (p != null) {
7800 mPackages.remove(name);
7801 if (p.sharedUser != null) {
7802 p.sharedUser.packages.remove(p);
7803 if (p.sharedUser.packages.size() == 0) {
7804 mSharedUsers.remove(p.sharedUser.name);
7805 removeUserIdLP(p.sharedUser.userId);
7806 return p.sharedUser.userId;
7807 }
7808 } else {
7809 removeUserIdLP(p.userId);
7810 return p.userId;
7811 }
7812 }
7813 return -1;
7814 }
7815
7816 private boolean addUserIdLP(int uid, Object obj, Object name) {
7817 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7818 return false;
7819 }
7820
7821 if (uid >= FIRST_APPLICATION_UID) {
7822 int N = mUserIds.size();
7823 final int index = uid - FIRST_APPLICATION_UID;
7824 while (index >= N) {
7825 mUserIds.add(null);
7826 N++;
7827 }
7828 if (mUserIds.get(index) != null) {
7829 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007830 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007831 + " name=" + name);
7832 return false;
7833 }
7834 mUserIds.set(index, obj);
7835 } else {
7836 if (mOtherUserIds.get(uid) != null) {
7837 reportSettingsProblem(Log.ERROR,
7838 "Adding duplicate shared id: " + uid
7839 + " name=" + name);
7840 return false;
7841 }
7842 mOtherUserIds.put(uid, obj);
7843 }
7844 return true;
7845 }
7846
7847 public Object getUserIdLP(int uid) {
7848 if (uid >= FIRST_APPLICATION_UID) {
7849 int N = mUserIds.size();
7850 final int index = uid - FIRST_APPLICATION_UID;
7851 return index < N ? mUserIds.get(index) : null;
7852 } else {
7853 return mOtherUserIds.get(uid);
7854 }
7855 }
7856
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007857 private Set<String> findPackagesWithFlag(int flag) {
7858 Set<String> ret = new HashSet<String>();
7859 for (PackageSetting ps : mPackages.values()) {
7860 // Has to match atleast all the flag bits set on flag
7861 if ((ps.pkgFlags & flag) == flag) {
7862 ret.add(ps.name);
7863 }
7864 }
7865 return ret;
7866 }
7867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007868 private void removeUserIdLP(int uid) {
7869 if (uid >= FIRST_APPLICATION_UID) {
7870 int N = mUserIds.size();
7871 final int index = uid - FIRST_APPLICATION_UID;
7872 if (index < N) mUserIds.set(index, null);
7873 } else {
7874 mOtherUserIds.remove(uid);
7875 }
7876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007878 void writeLP() {
7879 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7880
7881 // Keep the old settings around until we know the new ones have
7882 // been successfully written.
7883 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007884 // Presence of backup settings file indicates that we failed
7885 // to persist settings earlier. So preserve the older
7886 // backup for future reference since the current settings
7887 // might have been corrupted.
7888 if (!mBackupSettingsFilename.exists()) {
7889 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7890 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7891 return;
7892 }
7893 } else {
7894 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007896 }
7897
7898 mPastSignatures.clear();
7899
7900 try {
7901 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7902
7903 //XmlSerializer serializer = XmlUtils.serializerInstance();
7904 XmlSerializer serializer = new FastXmlSerializer();
7905 serializer.setOutput(str, "utf-8");
7906 serializer.startDocument(null, true);
7907 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7908
7909 serializer.startTag(null, "packages");
7910
7911 serializer.startTag(null, "permission-trees");
7912 for (BasePermission bp : mPermissionTrees.values()) {
7913 writePermission(serializer, bp);
7914 }
7915 serializer.endTag(null, "permission-trees");
7916
7917 serializer.startTag(null, "permissions");
7918 for (BasePermission bp : mPermissions.values()) {
7919 writePermission(serializer, bp);
7920 }
7921 serializer.endTag(null, "permissions");
7922
7923 for (PackageSetting pkg : mPackages.values()) {
7924 writePackage(serializer, pkg);
7925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7928 writeDisabledSysPackage(serializer, pkg);
7929 }
7930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007931 serializer.startTag(null, "preferred-activities");
7932 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7933 serializer.startTag(null, "item");
7934 pa.writeToXml(serializer);
7935 serializer.endTag(null, "item");
7936 }
7937 serializer.endTag(null, "preferred-activities");
7938
7939 for (SharedUserSetting usr : mSharedUsers.values()) {
7940 serializer.startTag(null, "shared-user");
7941 serializer.attribute(null, "name", usr.name);
7942 serializer.attribute(null, "userId",
7943 Integer.toString(usr.userId));
7944 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7945 serializer.startTag(null, "perms");
7946 for (String name : usr.grantedPermissions) {
7947 serializer.startTag(null, "item");
7948 serializer.attribute(null, "name", name);
7949 serializer.endTag(null, "item");
7950 }
7951 serializer.endTag(null, "perms");
7952 serializer.endTag(null, "shared-user");
7953 }
7954
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007955 if (mPackagesToBeCleaned.size() > 0) {
7956 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7957 serializer.startTag(null, "cleaning-package");
7958 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7959 serializer.endTag(null, "cleaning-package");
7960 }
7961 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007962
7963 if (mRenamedPackages.size() > 0) {
7964 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
7965 serializer.startTag(null, "renamed-package");
7966 serializer.attribute(null, "new", e.getKey());
7967 serializer.attribute(null, "old", e.getValue());
7968 serializer.endTag(null, "renamed-package");
7969 }
7970 }
7971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 serializer.endTag(null, "packages");
7973
7974 serializer.endDocument();
7975
7976 str.flush();
7977 str.close();
7978
7979 // New settings successfully written, old ones are no longer
7980 // needed.
7981 mBackupSettingsFilename.delete();
7982 FileUtils.setPermissions(mSettingsFilename.toString(),
7983 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7984 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7985 |FileUtils.S_IROTH,
7986 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007987
7988 // Write package list file now, use a JournaledFile.
7989 //
7990 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
7991 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
7992
7993 str = new FileOutputStream(journal.chooseForWrite());
7994 try {
7995 StringBuilder sb = new StringBuilder();
7996 for (PackageSetting pkg : mPackages.values()) {
7997 ApplicationInfo ai = pkg.pkg.applicationInfo;
7998 String dataPath = ai.dataDir;
7999 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8000
8001 // Avoid any application that has a space in its path
8002 // or that is handled by the system.
8003 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8004 continue;
8005
8006 // we store on each line the following information for now:
8007 //
8008 // pkgName - package name
8009 // userId - application-specific user id
8010 // debugFlag - 0 or 1 if the package is debuggable.
8011 // dataPath - path to package's data path
8012 //
8013 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8014 //
8015 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8016 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8017 // system/core/run-as/run-as.c
8018 //
8019 sb.setLength(0);
8020 sb.append(ai.packageName);
8021 sb.append(" ");
8022 sb.append((int)ai.uid);
8023 sb.append(isDebug ? " 1 " : " 0 ");
8024 sb.append(dataPath);
8025 sb.append("\n");
8026 str.write(sb.toString().getBytes());
8027 }
8028 str.flush();
8029 str.close();
8030 journal.commit();
8031 }
8032 catch (Exception e) {
8033 journal.rollback();
8034 }
8035
8036 FileUtils.setPermissions(mPackageListFilename.toString(),
8037 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8038 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8039 |FileUtils.S_IROTH,
8040 -1, -1);
8041
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008042 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008043
8044 } catch(XmlPullParserException e) {
8045 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 -08008046 } catch(java.io.IOException e) {
8047 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 -08008048 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008049 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008050 if (mSettingsFilename.exists()) {
8051 if (!mSettingsFilename.delete()) {
8052 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8053 }
8054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008055 //Debug.stopMethodTracing();
8056 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008057
8058 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008059 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 serializer.startTag(null, "updated-package");
8061 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008062 if (pkg.realName != null) {
8063 serializer.attribute(null, "realName", pkg.realName);
8064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008065 serializer.attribute(null, "codePath", pkg.codePathString);
8066 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008067 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008068 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8069 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8070 }
8071 if (pkg.sharedUser == null) {
8072 serializer.attribute(null, "userId",
8073 Integer.toString(pkg.userId));
8074 } else {
8075 serializer.attribute(null, "sharedUserId",
8076 Integer.toString(pkg.userId));
8077 }
8078 serializer.startTag(null, "perms");
8079 if (pkg.sharedUser == null) {
8080 // If this is a shared user, the permissions will
8081 // be written there. We still need to write an
8082 // empty permissions list so permissionsFixed will
8083 // be set.
8084 for (final String name : pkg.grantedPermissions) {
8085 BasePermission bp = mPermissions.get(name);
8086 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
8087 // We only need to write signature or system permissions but this wont
8088 // match the semantics of grantedPermissions. So write all permissions.
8089 serializer.startTag(null, "item");
8090 serializer.attribute(null, "name", name);
8091 serializer.endTag(null, "item");
8092 }
8093 }
8094 }
8095 serializer.endTag(null, "perms");
8096 serializer.endTag(null, "updated-package");
8097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008098
8099 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008100 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008101 serializer.startTag(null, "package");
8102 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008103 if (pkg.realName != null) {
8104 serializer.attribute(null, "realName", pkg.realName);
8105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008106 serializer.attribute(null, "codePath", pkg.codePathString);
8107 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8108 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8109 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008110 serializer.attribute(null, "flags",
8111 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008112 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008113 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008114 if (pkg.sharedUser == null) {
8115 serializer.attribute(null, "userId",
8116 Integer.toString(pkg.userId));
8117 } else {
8118 serializer.attribute(null, "sharedUserId",
8119 Integer.toString(pkg.userId));
8120 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008121 if (pkg.uidError) {
8122 serializer.attribute(null, "uidError", "true");
8123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008124 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8125 serializer.attribute(null, "enabled",
8126 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8127 ? "true" : "false");
8128 }
8129 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8130 serializer.attribute(null, "installStatus", "false");
8131 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008132 if (pkg.installerPackageName != null) {
8133 serializer.attribute(null, "installer", pkg.installerPackageName);
8134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8136 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8137 serializer.startTag(null, "perms");
8138 if (pkg.sharedUser == null) {
8139 // If this is a shared user, the permissions will
8140 // be written there. We still need to write an
8141 // empty permissions list so permissionsFixed will
8142 // be set.
8143 for (final String name : pkg.grantedPermissions) {
8144 serializer.startTag(null, "item");
8145 serializer.attribute(null, "name", name);
8146 serializer.endTag(null, "item");
8147 }
8148 }
8149 serializer.endTag(null, "perms");
8150 }
8151 if (pkg.disabledComponents.size() > 0) {
8152 serializer.startTag(null, "disabled-components");
8153 for (final String name : pkg.disabledComponents) {
8154 serializer.startTag(null, "item");
8155 serializer.attribute(null, "name", name);
8156 serializer.endTag(null, "item");
8157 }
8158 serializer.endTag(null, "disabled-components");
8159 }
8160 if (pkg.enabledComponents.size() > 0) {
8161 serializer.startTag(null, "enabled-components");
8162 for (final String name : pkg.enabledComponents) {
8163 serializer.startTag(null, "item");
8164 serializer.attribute(null, "name", name);
8165 serializer.endTag(null, "item");
8166 }
8167 serializer.endTag(null, "enabled-components");
8168 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 serializer.endTag(null, "package");
8171 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 void writePermission(XmlSerializer serializer, BasePermission bp)
8174 throws XmlPullParserException, java.io.IOException {
8175 if (bp.type != BasePermission.TYPE_BUILTIN
8176 && bp.sourcePackage != null) {
8177 serializer.startTag(null, "item");
8178 serializer.attribute(null, "name", bp.name);
8179 serializer.attribute(null, "package", bp.sourcePackage);
8180 if (DEBUG_SETTINGS) Log.v(TAG,
8181 "Writing perm: name=" + bp.name + " type=" + bp.type);
8182 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8183 PermissionInfo pi = bp.perm != null ? bp.perm.info
8184 : bp.pendingInfo;
8185 if (pi != null) {
8186 serializer.attribute(null, "type", "dynamic");
8187 if (pi.icon != 0) {
8188 serializer.attribute(null, "icon",
8189 Integer.toString(pi.icon));
8190 }
8191 if (pi.nonLocalizedLabel != null) {
8192 serializer.attribute(null, "label",
8193 pi.nonLocalizedLabel.toString());
8194 }
8195 if (pi.protectionLevel !=
8196 PermissionInfo.PROTECTION_NORMAL) {
8197 serializer.attribute(null, "protection",
8198 Integer.toString(pi.protectionLevel));
8199 }
8200 }
8201 }
8202 serializer.endTag(null, "item");
8203 }
8204 }
8205
8206 String getReadMessagesLP() {
8207 return mReadMessages.toString();
8208 }
8209
Oscar Montemayora8529f62009-11-18 10:14:20 -08008210 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008211 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8212 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008213 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008214 while(its.hasNext()) {
8215 String key = its.next();
8216 PackageSetting ps = mPackages.get(key);
8217 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008218 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008219 }
8220 }
8221 return ret;
8222 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008224 boolean readLP() {
8225 FileInputStream str = null;
8226 if (mBackupSettingsFilename.exists()) {
8227 try {
8228 str = new FileInputStream(mBackupSettingsFilename);
8229 mReadMessages.append("Reading from backup settings file\n");
8230 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008231 if (mSettingsFilename.exists()) {
8232 // If both the backup and settings file exist, we
8233 // ignore the settings since it might have been
8234 // corrupted.
8235 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
8236 mSettingsFilename.delete();
8237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008238 } catch (java.io.IOException e) {
8239 // We'll try for the normal settings file.
8240 }
8241 }
8242
8243 mPastSignatures.clear();
8244
8245 try {
8246 if (str == null) {
8247 if (!mSettingsFilename.exists()) {
8248 mReadMessages.append("No settings file found\n");
8249 Log.i(TAG, "No current settings file!");
8250 return false;
8251 }
8252 str = new FileInputStream(mSettingsFilename);
8253 }
8254 XmlPullParser parser = Xml.newPullParser();
8255 parser.setInput(str, null);
8256
8257 int type;
8258 while ((type=parser.next()) != XmlPullParser.START_TAG
8259 && type != XmlPullParser.END_DOCUMENT) {
8260 ;
8261 }
8262
8263 if (type != XmlPullParser.START_TAG) {
8264 mReadMessages.append("No start tag found in settings file\n");
8265 Log.e(TAG, "No start tag found in package manager settings");
8266 return false;
8267 }
8268
8269 int outerDepth = parser.getDepth();
8270 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8271 && (type != XmlPullParser.END_TAG
8272 || parser.getDepth() > outerDepth)) {
8273 if (type == XmlPullParser.END_TAG
8274 || type == XmlPullParser.TEXT) {
8275 continue;
8276 }
8277
8278 String tagName = parser.getName();
8279 if (tagName.equals("package")) {
8280 readPackageLP(parser);
8281 } else if (tagName.equals("permissions")) {
8282 readPermissionsLP(mPermissions, parser);
8283 } else if (tagName.equals("permission-trees")) {
8284 readPermissionsLP(mPermissionTrees, parser);
8285 } else if (tagName.equals("shared-user")) {
8286 readSharedUserLP(parser);
8287 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008288 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289 } else if (tagName.equals("preferred-activities")) {
8290 readPreferredActivitiesLP(parser);
8291 } else if(tagName.equals("updated-package")) {
8292 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008293 } else if (tagName.equals("cleaning-package")) {
8294 String name = parser.getAttributeValue(null, "name");
8295 if (name != null) {
8296 mPackagesToBeCleaned.add(name);
8297 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008298 } else if (tagName.equals("renamed-package")) {
8299 String nname = parser.getAttributeValue(null, "new");
8300 String oname = parser.getAttributeValue(null, "old");
8301 if (nname != null && oname != null) {
8302 mRenamedPackages.put(nname, oname);
8303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 } else {
8305 Log.w(TAG, "Unknown element under <packages>: "
8306 + parser.getName());
8307 XmlUtils.skipCurrentTag(parser);
8308 }
8309 }
8310
8311 str.close();
8312
8313 } catch(XmlPullParserException e) {
8314 mReadMessages.append("Error reading: " + e.toString());
8315 Log.e(TAG, "Error reading package manager settings", e);
8316
8317 } catch(java.io.IOException e) {
8318 mReadMessages.append("Error reading: " + e.toString());
8319 Log.e(TAG, "Error reading package manager settings", e);
8320
8321 }
8322
8323 int N = mPendingPackages.size();
8324 for (int i=0; i<N; i++) {
8325 final PendingPackage pp = mPendingPackages.get(i);
8326 Object idObj = getUserIdLP(pp.sharedId);
8327 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008328 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008329 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008330 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 if (p == null) {
8332 Log.w(TAG, "Unable to create application package for "
8333 + pp.name);
8334 continue;
8335 }
8336 p.copyFrom(pp);
8337 } else if (idObj != null) {
8338 String msg = "Bad package setting: package " + pp.name
8339 + " has shared uid " + pp.sharedId
8340 + " that is not a shared uid\n";
8341 mReadMessages.append(msg);
8342 Log.e(TAG, msg);
8343 } else {
8344 String msg = "Bad package setting: package " + pp.name
8345 + " has shared uid " + pp.sharedId
8346 + " that is not defined\n";
8347 mReadMessages.append(msg);
8348 Log.e(TAG, msg);
8349 }
8350 }
8351 mPendingPackages.clear();
8352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008353 mReadMessages.append("Read completed successfully: "
8354 + mPackages.size() + " packages, "
8355 + mSharedUsers.size() + " shared uids\n");
8356
8357 return true;
8358 }
8359
8360 private int readInt(XmlPullParser parser, String ns, String name,
8361 int defValue) {
8362 String v = parser.getAttributeValue(ns, name);
8363 try {
8364 if (v == null) {
8365 return defValue;
8366 }
8367 return Integer.parseInt(v);
8368 } catch (NumberFormatException e) {
8369 reportSettingsProblem(Log.WARN,
8370 "Error in package manager settings: attribute " +
8371 name + " has bad integer value " + v + " at "
8372 + parser.getPositionDescription());
8373 }
8374 return defValue;
8375 }
8376
8377 private void readPermissionsLP(HashMap<String, BasePermission> out,
8378 XmlPullParser parser)
8379 throws IOException, XmlPullParserException {
8380 int outerDepth = parser.getDepth();
8381 int type;
8382 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8383 && (type != XmlPullParser.END_TAG
8384 || parser.getDepth() > outerDepth)) {
8385 if (type == XmlPullParser.END_TAG
8386 || type == XmlPullParser.TEXT) {
8387 continue;
8388 }
8389
8390 String tagName = parser.getName();
8391 if (tagName.equals("item")) {
8392 String name = parser.getAttributeValue(null, "name");
8393 String sourcePackage = parser.getAttributeValue(null, "package");
8394 String ptype = parser.getAttributeValue(null, "type");
8395 if (name != null && sourcePackage != null) {
8396 boolean dynamic = "dynamic".equals(ptype);
8397 BasePermission bp = new BasePermission(name, sourcePackage,
8398 dynamic
8399 ? BasePermission.TYPE_DYNAMIC
8400 : BasePermission.TYPE_NORMAL);
8401 if (dynamic) {
8402 PermissionInfo pi = new PermissionInfo();
8403 pi.packageName = sourcePackage.intern();
8404 pi.name = name.intern();
8405 pi.icon = readInt(parser, null, "icon", 0);
8406 pi.nonLocalizedLabel = parser.getAttributeValue(
8407 null, "label");
8408 pi.protectionLevel = readInt(parser, null, "protection",
8409 PermissionInfo.PROTECTION_NORMAL);
8410 bp.pendingInfo = pi;
8411 }
8412 out.put(bp.name, bp);
8413 } else {
8414 reportSettingsProblem(Log.WARN,
8415 "Error in package manager settings: permissions has"
8416 + " no name at " + parser.getPositionDescription());
8417 }
8418 } else {
8419 reportSettingsProblem(Log.WARN,
8420 "Unknown element reading permissions: "
8421 + parser.getName() + " at "
8422 + parser.getPositionDescription());
8423 }
8424 XmlUtils.skipCurrentTag(parser);
8425 }
8426 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008428 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008429 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008430 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008431 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008432 String codePathStr = parser.getAttributeValue(null, "codePath");
8433 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008434 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008435 resourcePathStr = codePathStr;
8436 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008437 String version = parser.getAttributeValue(null, "version");
8438 int versionCode = 0;
8439 if (version != null) {
8440 try {
8441 versionCode = Integer.parseInt(version);
8442 } catch (NumberFormatException e) {
8443 }
8444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008446 int pkgFlags = 0;
8447 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008448 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008449 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008450 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008451 String timeStampStr = parser.getAttributeValue(null, "ts");
8452 if (timeStampStr != null) {
8453 try {
8454 long timeStamp = Long.parseLong(timeStampStr);
8455 ps.setTimeStamp(timeStamp, timeStampStr);
8456 } catch (NumberFormatException e) {
8457 }
8458 }
8459 String idStr = parser.getAttributeValue(null, "userId");
8460 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8461 if(ps.userId <= 0) {
8462 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8463 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8464 }
8465 int outerDepth = parser.getDepth();
8466 int type;
8467 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8468 && (type != XmlPullParser.END_TAG
8469 || parser.getDepth() > outerDepth)) {
8470 if (type == XmlPullParser.END_TAG
8471 || type == XmlPullParser.TEXT) {
8472 continue;
8473 }
8474
8475 String tagName = parser.getName();
8476 if (tagName.equals("perms")) {
8477 readGrantedPermissionsLP(parser,
8478 ps.grantedPermissions);
8479 } else {
8480 reportSettingsProblem(Log.WARN,
8481 "Unknown element under <updated-package>: "
8482 + parser.getName());
8483 XmlUtils.skipCurrentTag(parser);
8484 }
8485 }
8486 mDisabledSysPackages.put(name, ps);
8487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 private void readPackageLP(XmlPullParser parser)
8490 throws XmlPullParserException, IOException {
8491 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008492 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008493 String idStr = null;
8494 String sharedIdStr = null;
8495 String codePathStr = null;
8496 String resourcePathStr = null;
8497 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008498 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008499 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008500 int pkgFlags = 0;
8501 String timeStampStr;
8502 long timeStamp = 0;
8503 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008504 String version = null;
8505 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 try {
8507 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008508 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008509 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008510 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008511 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8512 codePathStr = parser.getAttributeValue(null, "codePath");
8513 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008514 version = parser.getAttributeValue(null, "version");
8515 if (version != null) {
8516 try {
8517 versionCode = Integer.parseInt(version);
8518 } catch (NumberFormatException e) {
8519 }
8520 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008521 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008522
8523 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008525 try {
8526 pkgFlags = Integer.parseInt(systemStr);
8527 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528 }
8529 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008530 // For backward compatibility
8531 systemStr = parser.getAttributeValue(null, "system");
8532 if (systemStr != null) {
8533 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8534 } else {
8535 // Old settings that don't specify system... just treat
8536 // them as system, good enough.
8537 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 }
8540 timeStampStr = parser.getAttributeValue(null, "ts");
8541 if (timeStampStr != null) {
8542 try {
8543 timeStamp = Long.parseLong(timeStampStr);
8544 } catch (NumberFormatException e) {
8545 }
8546 }
8547 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8548 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8549 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8550 if (resourcePathStr == null) {
8551 resourcePathStr = codePathStr;
8552 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008553 if (realName != null) {
8554 realName = realName.intern();
8555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 if (name == null) {
8557 reportSettingsProblem(Log.WARN,
8558 "Error in package manager settings: <package> has no name at "
8559 + parser.getPositionDescription());
8560 } else if (codePathStr == null) {
8561 reportSettingsProblem(Log.WARN,
8562 "Error in package manager settings: <package> has no codePath at "
8563 + parser.getPositionDescription());
8564 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008565 packageSetting = addPackageLP(name.intern(), realName,
8566 new File(codePathStr), new File(resourcePathStr),
8567 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008568 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8569 + ": userId=" + userId + " pkg=" + packageSetting);
8570 if (packageSetting == null) {
8571 reportSettingsProblem(Log.ERROR,
8572 "Failure adding uid " + userId
8573 + " while parsing settings at "
8574 + parser.getPositionDescription());
8575 } else {
8576 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8577 }
8578 } else if (sharedIdStr != null) {
8579 userId = sharedIdStr != null
8580 ? Integer.parseInt(sharedIdStr) : 0;
8581 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008582 packageSetting = new PendingPackage(name.intern(), realName,
8583 new File(codePathStr), new File(resourcePathStr),
8584 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008585 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8586 mPendingPackages.add((PendingPackage) packageSetting);
8587 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8588 + ": sharedUserId=" + userId + " pkg="
8589 + packageSetting);
8590 } else {
8591 reportSettingsProblem(Log.WARN,
8592 "Error in package manager settings: package "
8593 + name + " has bad sharedId " + sharedIdStr
8594 + " at " + parser.getPositionDescription());
8595 }
8596 } else {
8597 reportSettingsProblem(Log.WARN,
8598 "Error in package manager settings: package "
8599 + name + " has bad userId " + idStr + " at "
8600 + parser.getPositionDescription());
8601 }
8602 } catch (NumberFormatException e) {
8603 reportSettingsProblem(Log.WARN,
8604 "Error in package manager settings: package "
8605 + name + " has bad userId " + idStr + " at "
8606 + parser.getPositionDescription());
8607 }
8608 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008609 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008610 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 final String enabledStr = parser.getAttributeValue(null, "enabled");
8612 if (enabledStr != null) {
8613 if (enabledStr.equalsIgnoreCase("true")) {
8614 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8615 } else if (enabledStr.equalsIgnoreCase("false")) {
8616 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8617 } else if (enabledStr.equalsIgnoreCase("default")) {
8618 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8619 } else {
8620 reportSettingsProblem(Log.WARN,
8621 "Error in package manager settings: package "
8622 + name + " has bad enabled value: " + idStr
8623 + " at " + parser.getPositionDescription());
8624 }
8625 } else {
8626 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8627 }
8628 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8629 if (installStatusStr != null) {
8630 if (installStatusStr.equalsIgnoreCase("false")) {
8631 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8632 } else {
8633 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8634 }
8635 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008637 int outerDepth = parser.getDepth();
8638 int type;
8639 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8640 && (type != XmlPullParser.END_TAG
8641 || parser.getDepth() > outerDepth)) {
8642 if (type == XmlPullParser.END_TAG
8643 || type == XmlPullParser.TEXT) {
8644 continue;
8645 }
8646
8647 String tagName = parser.getName();
8648 if (tagName.equals("disabled-components")) {
8649 readDisabledComponentsLP(packageSetting, parser);
8650 } else if (tagName.equals("enabled-components")) {
8651 readEnabledComponentsLP(packageSetting, parser);
8652 } else if (tagName.equals("sigs")) {
8653 packageSetting.signatures.readXml(parser, mPastSignatures);
8654 } else if (tagName.equals("perms")) {
8655 readGrantedPermissionsLP(parser,
8656 packageSetting.loadedPermissions);
8657 packageSetting.permissionsFixed = true;
8658 } else {
8659 reportSettingsProblem(Log.WARN,
8660 "Unknown element under <package>: "
8661 + parser.getName());
8662 XmlUtils.skipCurrentTag(parser);
8663 }
8664 }
8665 } else {
8666 XmlUtils.skipCurrentTag(parser);
8667 }
8668 }
8669
8670 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8671 XmlPullParser parser)
8672 throws IOException, XmlPullParserException {
8673 int outerDepth = parser.getDepth();
8674 int type;
8675 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8676 && (type != XmlPullParser.END_TAG
8677 || parser.getDepth() > outerDepth)) {
8678 if (type == XmlPullParser.END_TAG
8679 || type == XmlPullParser.TEXT) {
8680 continue;
8681 }
8682
8683 String tagName = parser.getName();
8684 if (tagName.equals("item")) {
8685 String name = parser.getAttributeValue(null, "name");
8686 if (name != null) {
8687 packageSetting.disabledComponents.add(name.intern());
8688 } else {
8689 reportSettingsProblem(Log.WARN,
8690 "Error in package manager settings: <disabled-components> has"
8691 + " no name at " + parser.getPositionDescription());
8692 }
8693 } else {
8694 reportSettingsProblem(Log.WARN,
8695 "Unknown element under <disabled-components>: "
8696 + parser.getName());
8697 }
8698 XmlUtils.skipCurrentTag(parser);
8699 }
8700 }
8701
8702 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8703 XmlPullParser parser)
8704 throws IOException, XmlPullParserException {
8705 int outerDepth = parser.getDepth();
8706 int type;
8707 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8708 && (type != XmlPullParser.END_TAG
8709 || parser.getDepth() > outerDepth)) {
8710 if (type == XmlPullParser.END_TAG
8711 || type == XmlPullParser.TEXT) {
8712 continue;
8713 }
8714
8715 String tagName = parser.getName();
8716 if (tagName.equals("item")) {
8717 String name = parser.getAttributeValue(null, "name");
8718 if (name != null) {
8719 packageSetting.enabledComponents.add(name.intern());
8720 } else {
8721 reportSettingsProblem(Log.WARN,
8722 "Error in package manager settings: <enabled-components> has"
8723 + " no name at " + parser.getPositionDescription());
8724 }
8725 } else {
8726 reportSettingsProblem(Log.WARN,
8727 "Unknown element under <enabled-components>: "
8728 + parser.getName());
8729 }
8730 XmlUtils.skipCurrentTag(parser);
8731 }
8732 }
8733
8734 private void readSharedUserLP(XmlPullParser parser)
8735 throws XmlPullParserException, IOException {
8736 String name = null;
8737 String idStr = null;
8738 int pkgFlags = 0;
8739 SharedUserSetting su = null;
8740 try {
8741 name = parser.getAttributeValue(null, "name");
8742 idStr = parser.getAttributeValue(null, "userId");
8743 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8744 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8745 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8746 }
8747 if (name == null) {
8748 reportSettingsProblem(Log.WARN,
8749 "Error in package manager settings: <shared-user> has no name at "
8750 + parser.getPositionDescription());
8751 } else if (userId == 0) {
8752 reportSettingsProblem(Log.WARN,
8753 "Error in package manager settings: shared-user "
8754 + name + " has bad userId " + idStr + " at "
8755 + parser.getPositionDescription());
8756 } else {
8757 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8758 reportSettingsProblem(Log.ERROR,
8759 "Occurred while parsing settings at "
8760 + parser.getPositionDescription());
8761 }
8762 }
8763 } catch (NumberFormatException e) {
8764 reportSettingsProblem(Log.WARN,
8765 "Error in package manager settings: package "
8766 + name + " has bad userId " + idStr + " at "
8767 + parser.getPositionDescription());
8768 };
8769
8770 if (su != null) {
8771 int outerDepth = parser.getDepth();
8772 int type;
8773 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8774 && (type != XmlPullParser.END_TAG
8775 || parser.getDepth() > outerDepth)) {
8776 if (type == XmlPullParser.END_TAG
8777 || type == XmlPullParser.TEXT) {
8778 continue;
8779 }
8780
8781 String tagName = parser.getName();
8782 if (tagName.equals("sigs")) {
8783 su.signatures.readXml(parser, mPastSignatures);
8784 } else if (tagName.equals("perms")) {
8785 readGrantedPermissionsLP(parser, su.loadedPermissions);
8786 } else {
8787 reportSettingsProblem(Log.WARN,
8788 "Unknown element under <shared-user>: "
8789 + parser.getName());
8790 XmlUtils.skipCurrentTag(parser);
8791 }
8792 }
8793
8794 } else {
8795 XmlUtils.skipCurrentTag(parser);
8796 }
8797 }
8798
8799 private void readGrantedPermissionsLP(XmlPullParser parser,
8800 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8801 int outerDepth = parser.getDepth();
8802 int type;
8803 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8804 && (type != XmlPullParser.END_TAG
8805 || parser.getDepth() > outerDepth)) {
8806 if (type == XmlPullParser.END_TAG
8807 || type == XmlPullParser.TEXT) {
8808 continue;
8809 }
8810
8811 String tagName = parser.getName();
8812 if (tagName.equals("item")) {
8813 String name = parser.getAttributeValue(null, "name");
8814 if (name != null) {
8815 outPerms.add(name.intern());
8816 } else {
8817 reportSettingsProblem(Log.WARN,
8818 "Error in package manager settings: <perms> has"
8819 + " no name at " + parser.getPositionDescription());
8820 }
8821 } else {
8822 reportSettingsProblem(Log.WARN,
8823 "Unknown element under <perms>: "
8824 + parser.getName());
8825 }
8826 XmlUtils.skipCurrentTag(parser);
8827 }
8828 }
8829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008830 private void readPreferredActivitiesLP(XmlPullParser parser)
8831 throws XmlPullParserException, IOException {
8832 int outerDepth = parser.getDepth();
8833 int type;
8834 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8835 && (type != XmlPullParser.END_TAG
8836 || parser.getDepth() > outerDepth)) {
8837 if (type == XmlPullParser.END_TAG
8838 || type == XmlPullParser.TEXT) {
8839 continue;
8840 }
8841
8842 String tagName = parser.getName();
8843 if (tagName.equals("item")) {
8844 PreferredActivity pa = new PreferredActivity(parser);
8845 if (pa.mParseError == null) {
8846 mPreferredActivities.addFilter(pa);
8847 } else {
8848 reportSettingsProblem(Log.WARN,
8849 "Error in package manager settings: <preferred-activity> "
8850 + pa.mParseError + " at "
8851 + parser.getPositionDescription());
8852 }
8853 } else {
8854 reportSettingsProblem(Log.WARN,
8855 "Unknown element under <preferred-activities>: "
8856 + parser.getName());
8857 XmlUtils.skipCurrentTag(parser);
8858 }
8859 }
8860 }
8861
8862 // Returns -1 if we could not find an available UserId to assign
8863 private int newUserIdLP(Object obj) {
8864 // Let's be stupidly inefficient for now...
8865 final int N = mUserIds.size();
8866 for (int i=0; i<N; i++) {
8867 if (mUserIds.get(i) == null) {
8868 mUserIds.set(i, obj);
8869 return FIRST_APPLICATION_UID + i;
8870 }
8871 }
8872
8873 // None left?
8874 if (N >= MAX_APPLICATION_UIDS) {
8875 return -1;
8876 }
8877
8878 mUserIds.add(obj);
8879 return FIRST_APPLICATION_UID + N;
8880 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882 public PackageSetting getDisabledSystemPkg(String name) {
8883 synchronized(mPackages) {
8884 PackageSetting ps = mDisabledSysPackages.get(name);
8885 return ps;
8886 }
8887 }
8888
8889 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8890 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8891 if (Config.LOGV) {
8892 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8893 + " componentName = " + componentInfo.name);
8894 Log.v(TAG, "enabledComponents: "
8895 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8896 Log.v(TAG, "disabledComponents: "
8897 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8898 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008899 if (packageSettings == null) {
8900 if (false) {
8901 Log.w(TAG, "WAITING FOR DEBUGGER");
8902 Debug.waitForDebugger();
8903 Log.i(TAG, "We will crash!");
8904 }
8905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8907 || ((componentInfo.enabled
8908 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8909 || (componentInfo.applicationInfo.enabled
8910 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8911 && !packageSettings.disabledComponents.contains(componentInfo.name))
8912 || packageSettings.enabledComponents.contains(componentInfo.name));
8913 }
8914 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008915
8916 // ------- apps on sdcard specific code -------
8917 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008918 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008919 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008920 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008921 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008922
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008923 private String getEncryptKey() {
8924 try {
8925 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8926 if (sdEncKey == null) {
8927 sdEncKey = SystemKeyStore.getInstance().
8928 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8929 if (sdEncKey == null) {
8930 Log.e(TAG, "Failed to create encryption keys");
8931 return null;
8932 }
8933 }
8934 return sdEncKey;
8935 } catch (NoSuchAlgorithmException nsae) {
8936 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8937 return null;
8938 }
8939 }
8940
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008941 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008942 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008943 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008944 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008945 if (list != null) {
8946 int idx = 0;
8947 int idList[] = new int[MAX_CONTAINERS];
8948 boolean neverFound = true;
8949 for (String name : list) {
8950 // Ignore null entries
8951 if (name == null) {
8952 continue;
8953 }
8954 int sidx = name.indexOf(prefix);
8955 if (sidx == -1) {
8956 // Not a temp file. just ignore
8957 continue;
8958 }
8959 String subStr = name.substring(sidx + prefix.length());
8960 idList[idx] = -1;
8961 if (subStr != null) {
8962 try {
8963 int cid = Integer.parseInt(subStr);
8964 idList[idx++] = cid;
8965 neverFound = false;
8966 } catch (NumberFormatException e) {
8967 }
8968 }
8969 }
8970 if (!neverFound) {
8971 // Sort idList
8972 Arrays.sort(idList);
8973 for (int j = 1; j <= idList.length; j++) {
8974 if (idList[j-1] != j) {
8975 tmpIdx = j;
8976 break;
8977 }
8978 }
8979 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008980 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008981 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008982 }
8983
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08008984 /*
8985 * Return true if PackageManager does have packages to be updated.
8986 */
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008987 public boolean updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008988 final boolean ret;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008989 synchronized (mPackages) {
8990 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8991 mediaStatus+", mMediaMounted=" + mMediaMounted);
8992 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008993 return false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008994 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008995 mMediaMounted = mediaStatus;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008996 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8997 ret = appList != null && appList.size() > 0;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008998 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008999 // Queue up an async operation since the package installation may take a little while.
9000 mHandler.post(new Runnable() {
9001 public void run() {
9002 mHandler.removeCallbacks(this);
9003 updateExternalMediaStatusInner(mediaStatus, ret);
9004 }
9005 });
9006 return ret;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009007 }
9008
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009009 private void updateExternalMediaStatusInner(boolean mediaStatus,
9010 boolean sendUpdateBroadcast) {
9011 // If we are up here that means there are packages to be
9012 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009013 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009014 if (list == null || list.length == 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009015 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009016 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009017
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009018 int uidList[] = new int[list.length];
9019 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009020 HashSet<String> removeCids = new HashSet<String>();
9021 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9022 /*HashMap<String, String> cidPathMap = new HashMap<String, String>();
9023 // Don't hold any locks when getting cache paths
9024 for (String cid : list) {
9025 String cpath = PackageHelper.getSdDir(cid);
9026 if (cpath == null) {
9027 removeCids.add(cid);
9028 } else {
9029 cidPathMap.put(cid, cpath);
9030 }
9031 }*/
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009032 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009033 for (String cid : list) {
9034 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009035 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9036 boolean failed = true;
9037 try {
9038 String pkgName = args.getPackageName();
9039 if (pkgName == null) {
9040 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009041 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009042 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9043 PackageSetting ps = mSettings.mPackages.get(pkgName);
9044 if (ps != null && ps.codePathString != null &&
9045 (ps.pkgFlags & ApplicationInfo.FLAG_ON_SDCARD) != 0) {
9046 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9047 " corresponds to pkg : " + pkgName +
9048 " at code path: " + ps.codePathString);
9049 // We do have a valid package installed on sdcard
9050 processCids.put(args, ps.codePathString);
9051 failed = false;
9052 int uid = ps.userId;
9053 if (uid != -1) {
9054 uidList[num++] = uid;
9055 }
9056 }
9057 } finally {
9058 if (failed) {
9059 // Stale container on sdcard. Just delete
9060 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9061 removeCids.add(cid);
9062 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009063 }
9064 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009065 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009066 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009067 int uidArr[] = null;
9068 if (num > 0) {
9069 // Sort uid list
9070 Arrays.sort(uidList, 0, num);
9071 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009072 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009073 uidArr[0] = uidList[0];
9074 int di = 0;
9075 for (int i = 1; i < num; i++) {
9076 if (uidList[i-1] != uidList[i]) {
9077 uidArr[di++] = uidList[i];
9078 }
9079 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009080 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009081 // Process packages with valid entries.
9082 if (mediaStatus) {
9083 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
9084 loadMediaPackages(processCids, uidArr, sendUpdateBroadcast, removeCids);
9085 startCleaningPackages();
9086 } else {
9087 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
9088 unloadMediaPackages(processCids, uidArr, sendUpdateBroadcast);
9089 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009090 }
9091
9092 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9093 ArrayList<String> pkgList, int uidArr[]) {
9094 int size = pkgList.size();
9095 if (size > 0) {
9096 // Send broadcasts here
9097 Bundle extras = new Bundle();
9098 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9099 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009100 if (uidArr != null) {
9101 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9102 }
9103 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9104 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009105 sendPackageBroadcast(action, null, extras);
9106 }
9107 }
9108
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009109 /*
9110 * Look at potentially valid container ids from processCids
9111 * If package information doesn't match the one on record
9112 * or package scanning fails, the cid is added to list of
9113 * removeCids and cleaned up. Since cleaning up containers
9114 * involves destroying them, we do not want any parse
9115 * references to such stale containers. So force gc's
9116 * to avoid unnecessary crashes.
9117 */
9118 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9119 int uidArr[], boolean sendUpdateBroadcast,
9120 HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009121 ArrayList<String> pkgList = new ArrayList<String>();
9122 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009123 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009124 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009125 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009126 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9127 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009128 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009129 try {
9130 // Make sure there are no container errors first.
9131 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9132 != PackageManager.INSTALL_SUCCEEDED) {
9133 Log.e(TAG, "Failed to mount cid : " + args.cid +
9134 " when installing from sdcard");
9135 continue;
9136 }
9137 // Check code path here.
9138 if (codePath == null || !codePath.equals(args.getCodePath())) {
9139 Log.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
9140 " does not match one in settings " + codePath);
9141 continue;
9142 }
9143 // Parse package
9144 int parseFlags = PackageParser.PARSE_CHATTY |
9145 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9146 PackageParser pp = new PackageParser(codePath);
9147 pp.setSeparateProcesses(mSeparateProcesses);
9148 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9149 codePath, mMetrics, parseFlags);
9150 pp = null;
9151 doGc = true;
9152 // Check for parse errors
9153 if (pkg == null) {
9154 Log.e(TAG, "Parse error when installing install pkg : "
9155 + args.cid + " from " + args.cachePath);
9156 continue;
9157 }
9158 setApplicationInfoPaths(pkg, codePath, codePath);
9159 synchronized (mInstallLock) {
9160 // Scan the package
9161 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9162 synchronized (mPackages) {
9163 // Grant permissions
9164 grantPermissionsLP(pkg, false);
9165 // Persist settings
9166 mSettings.writeLP();
9167 retCode = PackageManager.INSTALL_SUCCEEDED;
9168 pkgList.add(pkg.packageName);
9169 // Post process args
9170 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9171 }
9172 } else {
9173 Log.i(TAG, "Failed to install pkg: " +
9174 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009175 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009176 }
9177
9178 } finally {
9179 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9180 // Don't destroy container here. Wait till gc clears things up.
9181 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009182 }
9183 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009184 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009185 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009186 if (sendUpdateBroadcast) {
9187 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9188 }
9189 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009190 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009191 }
9192 // Delete any stale containers if needed.
9193 if (removeCids != null) {
9194 for (String cid : removeCids) {
9195 Log.i(TAG, "Destroying stale container : " + cid);
9196 PackageHelper.destroySdDir(cid);
9197 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009198 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009199 }
9200
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009201 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9202 int uidArr[], boolean sendUpdateBroadcast) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009203 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009204 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009205 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009206 Set<SdInstallArgs> keys = processCids.keySet();
9207 for (SdInstallArgs args : keys) {
9208 String cid = args.cid;
9209 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009210 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009211 // Delete package internally
9212 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9213 synchronized (mInstallLock) {
9214 boolean res = deletePackageLI(pkgName, false,
9215 PackageManager.DONT_DELETE_DATA, outInfo);
9216 if (res) {
9217 pkgList.add(pkgName);
9218 } else {
9219 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009220 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009221 }
9222 }
9223 }
9224 // Send broadcasts
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009225 if (sendUpdateBroadcast) {
9226 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009227 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009228 // Force gc
9229 Runtime.getRuntime().gc();
9230 // Just unmount all valid containers.
9231 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009232 synchronized (mInstallLock) {
9233 args.doPostDeleteLI(false);
9234 }
9235 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009236 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009237
9238 public void movePackage(final String packageName,
9239 final IPackageMoveObserver observer, final int flags) {
9240 if (packageName == null) {
9241 return;
9242 }
9243 mContext.enforceCallingOrSelfPermission(
9244 android.Manifest.permission.MOVE_PACKAGE, null);
9245 int returnCode = PackageManager.MOVE_SUCCEEDED;
9246 int currFlags = 0;
9247 int newFlags = 0;
9248 synchronized (mPackages) {
9249 PackageParser.Package pkg = mPackages.get(packageName);
9250 if (pkg == null) {
9251 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9252 }
9253 // Disable moving fwd locked apps and system packages
9254 if (pkg.applicationInfo != null &&
9255 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9256 Log.w(TAG, "Cannot move system application");
9257 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9258 } else if (pkg.applicationInfo != null &&
9259 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9260 Log.w(TAG, "Cannot move forward locked app.");
9261 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9262 } else {
9263 // Find install location first
9264 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9265 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9266 Log.w(TAG, "Ambigous flags specified for move location.");
9267 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9268 } else {
9269 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9270 PackageManager.INSTALL_EXTERNAL : 0;
9271 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0 ?
9272 PackageManager.INSTALL_EXTERNAL : 0;
9273 if (newFlags == currFlags) {
9274 Log.w(TAG, "No move required. Trying to move to same location");
9275 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9276 }
9277 }
9278 }
9279 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9280 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9281 } else {
9282 Message msg = mHandler.obtainMessage(INIT_COPY);
9283 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9284 pkg.applicationInfo.publicSourceDir);
9285 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9286 packageName);
9287 msg.obj = mp;
9288 mHandler.sendMessage(msg);
9289 }
9290 }
9291 }
9292
9293 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9294 // Queue up an async operation since the package deletion may take a little while.
9295 mHandler.post(new Runnable() {
9296 public void run() {
9297 mHandler.removeCallbacks(this);
9298 int returnCode = currentStatus;
9299 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9300 if (moveSucceeded) {
9301 int uid = -1;
9302 synchronized (mPackages) {
9303 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9304 }
9305 ArrayList<String> pkgList = new ArrayList<String>();
9306 pkgList.add(mp.packageName);
9307 int uidArr[] = new int[] { uid };
9308 // Send resources unavailable broadcast
9309 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9310
9311 // Update package code and resource paths
9312 synchronized (mPackages) {
9313 PackageParser.Package pkg = mPackages.get(mp.packageName);
9314 if (pkg != null) {
9315 String oldCodePath = pkg.mPath;
9316 String newCodePath = mp.targetArgs.getCodePath();
9317 String newResPath = mp.targetArgs.getResourcePath();
9318 pkg.mPath = newCodePath;
9319 // Move dex files around
9320 if (moveDexFiles(pkg)
9321 != PackageManager.INSTALL_SUCCEEDED) {
9322 // Moving of dex files failed. Set
9323 // error code and abort move.
9324 pkg.mPath = pkg.mScanPath;
9325 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9326 moveSucceeded = false;
9327 } else {
9328 pkg.mScanPath = newCodePath;
9329 pkg.applicationInfo.sourceDir = newCodePath;
9330 pkg.applicationInfo.publicSourceDir = newResPath;
9331 PackageSetting ps = (PackageSetting) pkg.mExtras;
9332 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9333 ps.codePathString = ps.codePath.getPath();
9334 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9335 ps.resourcePathString = ps.resourcePath.getPath();
9336 // Set the application info flag correctly.
9337 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9338 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_ON_SDCARD;
9339 } else {
9340 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_ON_SDCARD;
9341 }
9342 ps.setFlags(pkg.applicationInfo.flags);
9343 mAppDirs.remove(oldCodePath);
9344 mAppDirs.put(newCodePath, pkg);
9345 // Persist settings
9346 mSettings.writeLP();
9347 }
9348 }
9349 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009350 // Send resources available broadcast
9351 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009352 }
9353 if (!moveSucceeded){
9354 // Clean up failed installation
9355 if (mp.targetArgs != null) {
9356 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009357 returnCode);
9358 }
9359 } else {
9360 // Force a gc to clear things up.
9361 Runtime.getRuntime().gc();
9362 // Delete older code
9363 synchronized (mInstallLock) {
9364 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009365 }
9366 }
9367 IPackageMoveObserver observer = mp.observer;
9368 if (observer != null) {
9369 try {
9370 observer.packageMoved(mp.packageName, returnCode);
9371 } catch (RemoteException e) {
9372 Log.i(TAG, "Observer no longer exists.");
9373 }
9374 }
9375 }
9376 });
9377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009378}