blob: 38d86153638a27c509104dd2d4e111210a5c218d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Tom Taylord4a47292009-12-21 13:59:18 -080021import com.android.common.FastXmlSerializer;
22import com.android.common.XmlUtils;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080023import com.android.internal.content.PackageHelper;
David 'Digit' Turneradd13762010-02-03 17:34:58 -080024import com.android.server.JournaledFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Christopher Tate1bb69062010-02-19 17:02:12 -080032import android.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070037import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080038import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070039import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.pm.ActivityInfo;
41import android.content.pm.ApplicationInfo;
42import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070043import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.IPackageDataObserver;
45import android.content.pm.IPackageDeleteObserver;
46import android.content.pm.IPackageInstallObserver;
47import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080048import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.IPackageStatsObserver;
50import android.content.pm.InstrumentationInfo;
51import android.content.pm.PackageInfo;
52import android.content.pm.PackageManager;
53import android.content.pm.PackageStats;
54import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
55import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
56import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
57import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
58import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
59import 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
152 static final int SCAN_MONITOR = 1<<0;
153 static final int SCAN_NO_DEX = 1<<1;
154 static final int SCAN_FORCE_DEX = 1<<2;
155 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800156 static final int SCAN_NEW_INSTALL = 1<<4;
157 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800159 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
160 "com.android.defcontainer",
161 "com.android.defcontainer.DefaultContainerService");
162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
164 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700165 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Dianne Hackborn851a5412009-05-08 12:06:44 -0700167 final int mSdkVersion = Build.VERSION.SDK_INT;
168 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
169 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 final Context mContext;
172 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700173 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 final DisplayMetrics mMetrics;
175 final int mDefParseFlags;
176 final String[] mSeparateProcesses;
177
178 // This is where all application persistent data goes.
179 final File mAppDataDir;
180
Oscar Montemayora8529f62009-11-18 10:14:20 -0800181 // If Encrypted File System feature is enabled, all application persistent data
182 // should go here instead.
183 final File mSecureAppDataDir;
184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 // This is the object monitoring the framework dir.
186 final FileObserver mFrameworkInstallObserver;
187
188 // This is the object monitoring the system app dir.
189 final FileObserver mSystemInstallObserver;
190
191 // This is the object monitoring mAppInstallDir.
192 final FileObserver mAppInstallObserver;
193
194 // This is the object monitoring mDrmAppPrivateInstallDir.
195 final FileObserver mDrmAppInstallObserver;
196
197 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
198 // LOCK HELD. Can be called with mInstallLock held.
199 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 final File mFrameworkDir;
202 final File mSystemAppDir;
203 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700204 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
206 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
207 // apps.
208 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 // Lock for state used when installing and doing other long running
213 // operations. Methods that must be called with this lock held have
214 // the prefix "LI".
215 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 // These are the directories in the 3rd party applications installed dir
218 // that we have currently loaded packages from. Keys are the application's
219 // installed zip file (absolute codePath), and values are Package.
220 final HashMap<String, PackageParser.Package> mAppDirs =
221 new HashMap<String, PackageParser.Package>();
222
223 // Information for the parser to write more useful error messages.
224 File mScanningPath;
225 int mLastScanError;
226
227 final int[] mOutPermissions = new int[3];
228
229 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 // Keys are String (package name), values are Package. This also serves
232 // as the lock for the global state. Methods that must be called with
233 // this lock held have the prefix "LP".
234 final HashMap<String, PackageParser.Package> mPackages =
235 new HashMap<String, PackageParser.Package>();
236
237 final Settings mSettings;
238 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
241 int[] mGlobalGids;
242
243 // These are the built-in uid -> permission mappings that were read from the
244 // etc/permissions.xml file.
245 final SparseArray<HashSet<String>> mSystemPermissions =
246 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // These are the built-in shared libraries that were read from the
249 // etc/permissions.xml file.
250 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800251
Dianne Hackborn49237342009-08-27 20:08:01 -0700252 // Temporary for building the final shared libraries for an .apk.
253 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800254
Dianne Hackborn49237342009-08-27 20:08:01 -0700255 // These are the features this devices supports that were read from the
256 // etc/permissions.xml file.
257 final HashMap<String, FeatureInfo> mAvailableFeatures =
258 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 // All available activities, for your resolving pleasure.
261 final ActivityIntentResolver mActivities =
262 new ActivityIntentResolver();
263
264 // All available receivers, for your resolving pleasure.
265 final ActivityIntentResolver mReceivers =
266 new ActivityIntentResolver();
267
268 // All available services, for your resolving pleasure.
269 final ServiceIntentResolver mServices = new ServiceIntentResolver();
270
271 // Keys are String (provider class name), values are Provider.
272 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
273 new HashMap<ComponentName, PackageParser.Provider>();
274
275 // Mapping from provider base names (first directory in content URI codePath)
276 // to the provider information.
277 final HashMap<String, PackageParser.Provider> mProviders =
278 new HashMap<String, PackageParser.Provider>();
279
280 // Mapping from instrumentation class names to info about them.
281 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
282 new HashMap<ComponentName, PackageParser.Instrumentation>();
283
284 // Mapping from permission names to info about them.
285 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
286 new HashMap<String, PackageParser.PermissionGroup>();
287
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800288 // Packages whose data we have transfered into another package, thus
289 // should no longer exist.
290 final HashSet<String> mTransferedPackages = new HashSet<String>();
291
Dianne Hackborn854060af2009-07-09 18:14:31 -0700292 // Broadcast actions that are only available to the system.
293 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 boolean mSystemReady;
296 boolean mSafeMode;
297 boolean mHasSystemUidErrors;
298
299 ApplicationInfo mAndroidApplication;
300 final ActivityInfo mResolveActivity = new ActivityInfo();
301 final ResolveInfo mResolveInfo = new ResolveInfo();
302 ComponentName mResolveComponentName;
303 PackageParser.Package mPlatformPackage;
304
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700305 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800306 final HashMap<String, ArrayList<String>> mPendingBroadcasts
307 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700308 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800309 static final int MCS_BOUND = 3;
310 static final int END_COPY = 4;
311 static final int INIT_COPY = 5;
312 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800313 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800314 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800315 static final int POST_INSTALL = 9;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700316 // Delay time in millisecs
317 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800318 private ServiceConnection mDefContainerConn = new ServiceConnection() {
319 public void onServiceConnected(ComponentName name, IBinder service) {
320 IMediaContainerService imcs =
321 IMediaContainerService.Stub.asInterface(service);
322 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
323 mHandler.sendMessage(msg);
324 }
325
326 public void onServiceDisconnected(ComponentName name) {
327 }
328 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700329
Christopher Tate1bb69062010-02-19 17:02:12 -0800330 // Recordkeeping of restore-after-install operations that are currently in flight
331 // between the Package Manager and the Backup Manager
332 class PostInstallData {
333 public InstallArgs args;
334 public PackageInstalledInfo res;
335
336 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
337 args = _a;
338 res = _r;
339 }
340 };
341 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
342 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
343
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700344 class PackageHandler extends Handler {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800345 final ArrayList<HandlerParams> mPendingInstalls =
346 new ArrayList<HandlerParams>();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800347 // Service Connection to remote media container service to copy
348 // package uri's from external media onto secure containers
349 // or internal storage.
350 private IMediaContainerService mContainerService = null;
351
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700352 PackageHandler(Looper looper) {
353 super(looper);
354 }
355 public void handleMessage(Message msg) {
356 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800357 case INIT_COPY: {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800358 HandlerParams params = (HandlerParams) msg.obj;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800359 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800360 if (mContainerService != null) {
361 // No need to add to pending list. Use remote stub directly
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800362 params.handleStartCopy(mContainerService);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800363 } else {
364 if (mContext.bindService(service, mDefContainerConn,
365 Context.BIND_AUTO_CREATE)) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800366 mPendingInstalls.add(params);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800367 } else {
368 Log.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800369 // Indicate service bind error
370 params.handleServiceError();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800371 }
372 }
373 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800374 }
375 case MCS_BOUND: {
376 // Initialize mContainerService if needed.
377 if (msg.obj != null) {
378 mContainerService = (IMediaContainerService) msg.obj;
379 }
380 if (mPendingInstalls.size() > 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800381 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800382 if (params != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800383 params.handleStartCopy(mContainerService);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800384 }
385 }
386 break;
387 }
388 case MCS_UNBIND : {
389 if (mPendingInstalls.size() == 0) {
390 mContext.unbindService(mDefContainerConn);
391 mContainerService = null;
392 }
393 break;
394 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700395 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800396 String packages[];
397 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700398 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700399 int uids[];
400 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800401 if (mPendingBroadcasts == null) {
402 return;
403 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700404 size = mPendingBroadcasts.size();
405 if (size <= 0) {
406 // Nothing to be done. Just return
407 return;
408 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800409 packages = new String[size];
410 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700411 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800412 Iterator<HashMap.Entry<String, ArrayList<String>>>
413 it = mPendingBroadcasts.entrySet().iterator();
414 int i = 0;
415 while (it.hasNext() && i < size) {
416 HashMap.Entry<String, ArrayList<String>> ent = it.next();
417 packages[i] = ent.getKey();
418 components[i] = ent.getValue();
419 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700420 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800421 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700422 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800423 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700424 mPendingBroadcasts.clear();
425 }
426 // Send broadcasts
427 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800428 sendPackageChangedBroadcast(packages[i], true,
429 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700430 }
431 break;
432 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800433 case START_CLEANING_PACKAGE: {
434 String packageName = (String)msg.obj;
435 synchronized (mPackages) {
436 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
437 mSettings.mPackagesToBeCleaned.add(packageName);
438 }
439 }
440 startCleaningPackages();
441 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800442 case POST_INSTALL: {
443 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
444 PostInstallData data = mRunningInstalls.get(msg.arg1);
445 mRunningInstalls.delete(msg.arg1);
446
447 if (data != null) {
448 InstallArgs args = data.args;
449 PackageInstalledInfo res = data.res;
450
451 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
452 res.removedInfo.sendBroadcast(false, true);
453 Bundle extras = new Bundle(1);
454 extras.putInt(Intent.EXTRA_UID, res.uid);
455 final boolean update = res.removedInfo.removedPackage != null;
456 if (update) {
457 extras.putBoolean(Intent.EXTRA_REPLACING, true);
458 }
459 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
460 res.pkg.applicationInfo.packageName,
461 extras);
462 if (update) {
463 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
464 res.pkg.applicationInfo.packageName,
465 extras);
466 }
467 if (res.removedInfo.args != null) {
468 // Remove the replaced package's older resources safely now
469 synchronized (mInstallLock) {
470 res.removedInfo.args.doPostDeleteLI(true);
471 }
472 }
473 }
474 Runtime.getRuntime().gc();
475
476 if (args.observer != null) {
477 try {
478 args.observer.packageInstalled(res.name, res.returnCode);
479 } catch (RemoteException e) {
480 Log.i(TAG, "Observer no longer exists.");
481 }
482 }
483 } else {
484 Log.e(TAG, "Bogus post-install token " + msg.arg1);
485 }
486 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700487 }
488 }
489 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800490
491 static boolean installOnSd(int flags) {
492 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800493 ((flags & PackageManager.INSTALL_EXTERNAL) == 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800494 return false;
495 }
496 return true;
497 }
498
499 static boolean isFwdLocked(int flags) {
500 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
501 return true;
502 }
503 return false;
504 }
505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 public static final IPackageManager main(Context context, boolean factoryTest) {
507 PackageManagerService m = new PackageManagerService(context, factoryTest);
508 ServiceManager.addService("package", m);
509 return m;
510 }
511
512 static String[] splitString(String str, char sep) {
513 int count = 1;
514 int i = 0;
515 while ((i=str.indexOf(sep, i)) >= 0) {
516 count++;
517 i++;
518 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 String[] res = new String[count];
521 i=0;
522 count = 0;
523 int lastI=0;
524 while ((i=str.indexOf(sep, i)) >= 0) {
525 res[count] = str.substring(lastI, i);
526 count++;
527 i++;
528 lastI = i;
529 }
530 res[count] = str.substring(lastI, str.length());
531 return res;
532 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800535 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 if (mSdkVersion <= 0) {
539 Log.w(TAG, "**** ro.build.version.sdk not set!");
540 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 mContext = context;
543 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700544 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 mMetrics = new DisplayMetrics();
546 mSettings = new Settings();
547 mSettings.addSharedUserLP("android.uid.system",
548 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
549 mSettings.addSharedUserLP("android.uid.phone",
550 MULTIPLE_APPLICATION_UIDS
551 ? RADIO_UID : FIRST_APPLICATION_UID,
552 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400553 mSettings.addSharedUserLP("android.uid.log",
554 MULTIPLE_APPLICATION_UIDS
555 ? LOG_UID : FIRST_APPLICATION_UID,
556 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557
558 String separateProcesses = SystemProperties.get("debug.separate_processes");
559 if (separateProcesses != null && separateProcesses.length() > 0) {
560 if ("*".equals(separateProcesses)) {
561 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
562 mSeparateProcesses = null;
563 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
564 } else {
565 mDefParseFlags = 0;
566 mSeparateProcesses = separateProcesses.split(",");
567 Log.w(TAG, "Running with debug.separate_processes: "
568 + separateProcesses);
569 }
570 } else {
571 mDefParseFlags = 0;
572 mSeparateProcesses = null;
573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 Installer installer = new Installer();
576 // Little hacky thing to check if installd is here, to determine
577 // whether we are running on the simulator and thus need to take
578 // care of building the /data file structure ourself.
579 // (apparently the sim now has a working installer)
580 if (installer.ping() && Process.supportsProcesses()) {
581 mInstaller = installer;
582 } else {
583 mInstaller = null;
584 }
585
586 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
587 Display d = wm.getDefaultDisplay();
588 d.getMetrics(mMetrics);
589
590 synchronized (mInstallLock) {
591 synchronized (mPackages) {
592 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700593 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 File dataDir = Environment.getDataDirectory();
596 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800597 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
599
600 if (mInstaller == null) {
601 // Make sure these dirs exist, when we are running in
602 // the simulator.
603 // Make a wide-open directory for random misc stuff.
604 File miscDir = new File(dataDir, "misc");
605 miscDir.mkdirs();
606 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800607 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 mDrmAppPrivateInstallDir.mkdirs();
609 }
610
611 readPermissions();
612
613 mRestoredSettings = mSettings.readLP();
614 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800615
616 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800618
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800619 // Set flag to monitor and not change apk file paths when
620 // scanning install directories.
621 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700622 if (mNoDexOpt) {
623 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800624 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700630 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700633 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 /**
636 * Out of paranoia, ensure that everything in the boot class
637 * path has been dexed.
638 */
639 String bootClassPath = System.getProperty("java.boot.class.path");
640 if (bootClassPath != null) {
641 String[] paths = splitString(bootClassPath, ':');
642 for (int i=0; i<paths.length; i++) {
643 try {
644 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
645 libFiles.add(paths[i]);
646 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700647 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 }
649 } catch (FileNotFoundException e) {
650 Log.w(TAG, "Boot class path not found: " + paths[i]);
651 } catch (IOException e) {
652 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
653 }
654 }
655 } else {
656 Log.w(TAG, "No BOOTCLASSPATH found!");
657 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 /**
660 * Also ensure all external libraries have had dexopt run on them.
661 */
662 if (mSharedLibraries.size() > 0) {
663 Iterator<String> libs = mSharedLibraries.values().iterator();
664 while (libs.hasNext()) {
665 String lib = libs.next();
666 try {
667 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
668 libFiles.add(lib);
669 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700670 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
672 } catch (FileNotFoundException e) {
673 Log.w(TAG, "Library not found: " + lib);
674 } catch (IOException e) {
675 Log.w(TAG, "Exception reading library: " + lib, e);
676 }
677 }
678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 // Gross hack for now: we know this file doesn't contain any
681 // code, so don't dexopt it to avoid the resulting log spew.
682 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 /**
685 * And there are a number of commands implemented in Java, which
686 * we currently need to do the dexopt on so that they can be
687 * run from a non-root shell.
688 */
689 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700690 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 for (int i=0; i<frameworkFiles.length; i++) {
692 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
693 String path = libPath.getPath();
694 // Skip the file if we alrady did it.
695 if (libFiles.contains(path)) {
696 continue;
697 }
698 // Skip the file if it is not a type we want to dexopt.
699 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
700 continue;
701 }
702 try {
703 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
704 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700705 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 }
707 } catch (FileNotFoundException e) {
708 Log.w(TAG, "Jar not found: " + path);
709 } catch (IOException e) {
710 Log.w(TAG, "Exception reading jar: " + path, e);
711 }
712 }
713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800714
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700715 if (didDexOpt) {
716 // If we had to do a dexopt of one of the previous
717 // things, then something on the system has changed.
718 // Consider this significant, and wipe away all other
719 // existing dexopt files to ensure we don't leave any
720 // dangling around.
721 String[] files = mDalvikCacheDir.list();
722 if (files != null) {
723 for (int i=0; i<files.length; i++) {
724 String fn = files[i];
725 if (fn.startsWith("data@app@")
726 || fn.startsWith("data@app-private@")) {
727 Log.i(TAG, "Pruning dalvik file: " + fn);
728 (new File(mDalvikCacheDir, fn)).delete();
729 }
730 }
731 }
732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800734
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800735 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 mFrameworkInstallObserver = new AppDirObserver(
737 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
738 mFrameworkInstallObserver.startWatching();
739 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800740 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800741
742 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
744 mSystemInstallObserver = new AppDirObserver(
745 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
746 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800747 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800748
749 if (mInstaller != null) {
750 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
751 mInstaller.moveFiles();
752 }
753
754 // Prune any system packages that no longer exist.
755 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
756 while (psit.hasNext()) {
757 PackageSetting ps = psit.next();
758 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800759 && !mPackages.containsKey(ps.name)
760 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800761 psit.remove();
762 String msg = "System package " + ps.name
763 + " no longer exists; wiping its data";
764 reportSettingsProblem(Log.WARN, msg);
765 if (mInstaller != null) {
766 // XXX how to set useEncryptedFSDir for packages that
767 // are not encrypted?
768 mInstaller.remove(ps.name, true);
769 }
770 }
771 }
772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 mAppInstallDir = new File(dataDir, "app");
774 if (mInstaller == null) {
775 // Make sure these dirs exist, when we are running in
776 // the simulator.
777 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
778 }
779 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800780 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 //clean up list
782 for(int i = 0; i < deletePkgsList.size(); i++) {
783 //clean up here
784 cleanupInstallFailedPackage(deletePkgsList.get(i));
785 }
786 //delete tmp files
787 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800788
789 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 SystemClock.uptimeMillis());
791 mAppInstallObserver = new AppDirObserver(
792 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
793 mAppInstallObserver.startWatching();
794 scanDirLI(mAppInstallDir, 0, scanMode);
795
796 mDrmAppInstallObserver = new AppDirObserver(
797 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
798 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800799 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800801 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 SystemClock.uptimeMillis());
803 Log.i(TAG, "Time to scan packages: "
804 + ((SystemClock.uptimeMillis()-startTime)/1000f)
805 + " seconds");
806
807 updatePermissionsLP();
808
809 mSettings.writeLP();
810
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800811 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 // Now after opening every single application zip, make sure they
815 // are all flushed. Not really needed, but keeps things nice and
816 // tidy.
817 Runtime.getRuntime().gc();
818 } // synchronized (mPackages)
819 } // synchronized (mInstallLock)
820 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 @Override
823 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
824 throws RemoteException {
825 try {
826 return super.onTransact(code, data, reply, flags);
827 } catch (RuntimeException e) {
828 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
829 Log.e(TAG, "Package Manager Crash", e);
830 }
831 throw e;
832 }
833 }
834
Dianne Hackborne6620b22010-01-22 14:46:21 -0800835 void cleanupInstallFailedPackage(PackageSetting ps) {
836 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800838 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
839 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 if (retCode < 0) {
841 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800842 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 }
844 } else {
845 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800846 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 File dataDir = new File(pkg.applicationInfo.dataDir);
848 dataDir.delete();
849 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800850 if (ps.codePath != null) {
851 if (!ps.codePath.delete()) {
852 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
853 }
854 }
855 if (ps.resourcePath != null) {
856 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
857 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
858 }
859 }
860 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 }
862
863 void readPermissions() {
864 // Read permissions from .../etc/permission directory.
865 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
866 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
867 Log.w(TAG, "No directory " + libraryDir + ", skipping");
868 return;
869 }
870 if (!libraryDir.canRead()) {
871 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
872 return;
873 }
874
875 // Iterate over the files in the directory and scan .xml files
876 for (File f : libraryDir.listFiles()) {
877 // We'll read platform.xml last
878 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
879 continue;
880 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 if (!f.getPath().endsWith(".xml")) {
883 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
884 continue;
885 }
886 if (!f.canRead()) {
887 Log.w(TAG, "Permissions library file " + f + " cannot be read");
888 continue;
889 }
890
891 readPermissionsFromXml(f);
892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
895 final File permFile = new File(Environment.getRootDirectory(),
896 "etc/permissions/platform.xml");
897 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800898
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700899 StringBuilder sb = new StringBuilder(128);
900 sb.append("Libs:");
901 Iterator<String> it = mSharedLibraries.keySet().iterator();
902 while (it.hasNext()) {
903 sb.append(' ');
904 String name = it.next();
905 sb.append(name);
906 sb.append(':');
907 sb.append(mSharedLibraries.get(name));
908 }
909 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800910
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700911 sb.setLength(0);
912 sb.append("Features:");
913 it = mAvailableFeatures.keySet().iterator();
914 while (it.hasNext()) {
915 sb.append(' ');
916 sb.append(it.next());
917 }
918 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800920
921 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 FileReader permReader = null;
923 try {
924 permReader = new FileReader(permFile);
925 } catch (FileNotFoundException e) {
926 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
927 return;
928 }
929
930 try {
931 XmlPullParser parser = Xml.newPullParser();
932 parser.setInput(permReader);
933
934 XmlUtils.beginDocument(parser, "permissions");
935
936 while (true) {
937 XmlUtils.nextElement(parser);
938 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
939 break;
940 }
941
942 String name = parser.getName();
943 if ("group".equals(name)) {
944 String gidStr = parser.getAttributeValue(null, "gid");
945 if (gidStr != null) {
946 int gid = Integer.parseInt(gidStr);
947 mGlobalGids = appendInt(mGlobalGids, gid);
948 } else {
949 Log.w(TAG, "<group> without gid at "
950 + parser.getPositionDescription());
951 }
952
953 XmlUtils.skipCurrentTag(parser);
954 continue;
955 } else if ("permission".equals(name)) {
956 String perm = parser.getAttributeValue(null, "name");
957 if (perm == null) {
958 Log.w(TAG, "<permission> without name at "
959 + parser.getPositionDescription());
960 XmlUtils.skipCurrentTag(parser);
961 continue;
962 }
963 perm = perm.intern();
964 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 } else if ("assign-permission".equals(name)) {
967 String perm = parser.getAttributeValue(null, "name");
968 if (perm == null) {
969 Log.w(TAG, "<assign-permission> without name at "
970 + parser.getPositionDescription());
971 XmlUtils.skipCurrentTag(parser);
972 continue;
973 }
974 String uidStr = parser.getAttributeValue(null, "uid");
975 if (uidStr == null) {
976 Log.w(TAG, "<assign-permission> without uid at "
977 + parser.getPositionDescription());
978 XmlUtils.skipCurrentTag(parser);
979 continue;
980 }
981 int uid = Process.getUidForName(uidStr);
982 if (uid < 0) {
983 Log.w(TAG, "<assign-permission> with unknown uid \""
984 + uidStr + "\" at "
985 + parser.getPositionDescription());
986 XmlUtils.skipCurrentTag(parser);
987 continue;
988 }
989 perm = perm.intern();
990 HashSet<String> perms = mSystemPermissions.get(uid);
991 if (perms == null) {
992 perms = new HashSet<String>();
993 mSystemPermissions.put(uid, perms);
994 }
995 perms.add(perm);
996 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 } else if ("library".equals(name)) {
999 String lname = parser.getAttributeValue(null, "name");
1000 String lfile = parser.getAttributeValue(null, "file");
1001 if (lname == null) {
1002 Log.w(TAG, "<library> without name at "
1003 + parser.getPositionDescription());
1004 } else if (lfile == null) {
1005 Log.w(TAG, "<library> without file at "
1006 + parser.getPositionDescription());
1007 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001008 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001009 mSharedLibraries.put(lname, lfile);
1010 }
1011 XmlUtils.skipCurrentTag(parser);
1012 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001013
Dianne Hackborn49237342009-08-27 20:08:01 -07001014 } else if ("feature".equals(name)) {
1015 String fname = parser.getAttributeValue(null, "name");
1016 if (fname == null) {
1017 Log.w(TAG, "<feature> without name at "
1018 + parser.getPositionDescription());
1019 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001020 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001021 FeatureInfo fi = new FeatureInfo();
1022 fi.name = fname;
1023 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025 XmlUtils.skipCurrentTag(parser);
1026 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 } else {
1029 XmlUtils.skipCurrentTag(parser);
1030 continue;
1031 }
1032
1033 }
1034 } catch (XmlPullParserException e) {
1035 Log.w(TAG, "Got execption parsing permissions.", e);
1036 } catch (IOException e) {
1037 Log.w(TAG, "Got execption parsing permissions.", e);
1038 }
1039 }
1040
1041 void readPermission(XmlPullParser parser, String name)
1042 throws IOException, XmlPullParserException {
1043
1044 name = name.intern();
1045
1046 BasePermission bp = mSettings.mPermissions.get(name);
1047 if (bp == null) {
1048 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1049 mSettings.mPermissions.put(name, bp);
1050 }
1051 int outerDepth = parser.getDepth();
1052 int type;
1053 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1054 && (type != XmlPullParser.END_TAG
1055 || parser.getDepth() > outerDepth)) {
1056 if (type == XmlPullParser.END_TAG
1057 || type == XmlPullParser.TEXT) {
1058 continue;
1059 }
1060
1061 String tagName = parser.getName();
1062 if ("group".equals(tagName)) {
1063 String gidStr = parser.getAttributeValue(null, "gid");
1064 if (gidStr != null) {
1065 int gid = Process.getGidForName(gidStr);
1066 bp.gids = appendInt(bp.gids, gid);
1067 } else {
1068 Log.w(TAG, "<group> without gid at "
1069 + parser.getPositionDescription());
1070 }
1071 }
1072 XmlUtils.skipCurrentTag(parser);
1073 }
1074 }
1075
1076 static int[] appendInt(int[] cur, int val) {
1077 if (cur == null) {
1078 return new int[] { val };
1079 }
1080 final int N = cur.length;
1081 for (int i=0; i<N; i++) {
1082 if (cur[i] == val) {
1083 return cur;
1084 }
1085 }
1086 int[] ret = new int[N+1];
1087 System.arraycopy(cur, 0, ret, 0, N);
1088 ret[N] = val;
1089 return ret;
1090 }
1091
1092 static int[] appendInts(int[] cur, int[] add) {
1093 if (add == null) return cur;
1094 if (cur == null) return add;
1095 final int N = add.length;
1096 for (int i=0; i<N; i++) {
1097 cur = appendInt(cur, add[i]);
1098 }
1099 return cur;
1100 }
1101
1102 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001103 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1104 // The package has been uninstalled but has retained data and resources.
1105 return PackageParser.generatePackageInfo(p, null, flags);
1106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 final PackageSetting ps = (PackageSetting)p.mExtras;
1108 if (ps == null) {
1109 return null;
1110 }
1111 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1112 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1113 }
1114
1115 public PackageInfo getPackageInfo(String packageName, int flags) {
1116 synchronized (mPackages) {
1117 PackageParser.Package p = mPackages.get(packageName);
1118 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001119 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 + ": " + p);
1121 if (p != null) {
1122 return generatePackageInfo(p, flags);
1123 }
1124 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1125 return generatePackageInfoFromSettingsLP(packageName, flags);
1126 }
1127 }
1128 return null;
1129 }
1130
Dianne Hackborn47096932010-02-11 15:57:09 -08001131 public String[] currentToCanonicalPackageNames(String[] names) {
1132 String[] out = new String[names.length];
1133 synchronized (mPackages) {
1134 for (int i=names.length-1; i>=0; i--) {
1135 PackageSetting ps = mSettings.mPackages.get(names[i]);
1136 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1137 }
1138 }
1139 return out;
1140 }
1141
1142 public String[] canonicalToCurrentPackageNames(String[] names) {
1143 String[] out = new String[names.length];
1144 synchronized (mPackages) {
1145 for (int i=names.length-1; i>=0; i--) {
1146 String cur = mSettings.mRenamedPackages.get(names[i]);
1147 out[i] = cur != null ? cur : names[i];
1148 }
1149 }
1150 return out;
1151 }
1152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 public int getPackageUid(String packageName) {
1154 synchronized (mPackages) {
1155 PackageParser.Package p = mPackages.get(packageName);
1156 if(p != null) {
1157 return p.applicationInfo.uid;
1158 }
1159 PackageSetting ps = mSettings.mPackages.get(packageName);
1160 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1161 return -1;
1162 }
1163 p = ps.pkg;
1164 return p != null ? p.applicationInfo.uid : -1;
1165 }
1166 }
1167
1168 public int[] getPackageGids(String packageName) {
1169 synchronized (mPackages) {
1170 PackageParser.Package p = mPackages.get(packageName);
1171 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001172 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 + ": " + p);
1174 if (p != null) {
1175 final PackageSetting ps = (PackageSetting)p.mExtras;
1176 final SharedUserSetting suid = ps.sharedUser;
1177 return suid != null ? suid.gids : ps.gids;
1178 }
1179 }
1180 // stupid thing to indicate an error.
1181 return new int[0];
1182 }
1183
1184 public PermissionInfo getPermissionInfo(String name, int flags) {
1185 synchronized (mPackages) {
1186 final BasePermission p = mSettings.mPermissions.get(name);
1187 if (p != null && p.perm != null) {
1188 return PackageParser.generatePermissionInfo(p.perm, flags);
1189 }
1190 return null;
1191 }
1192 }
1193
1194 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1195 synchronized (mPackages) {
1196 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1197 for (BasePermission p : mSettings.mPermissions.values()) {
1198 if (group == null) {
1199 if (p.perm.info.group == null) {
1200 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1201 }
1202 } else {
1203 if (group.equals(p.perm.info.group)) {
1204 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1205 }
1206 }
1207 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 if (out.size() > 0) {
1210 return out;
1211 }
1212 return mPermissionGroups.containsKey(group) ? out : null;
1213 }
1214 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1217 synchronized (mPackages) {
1218 return PackageParser.generatePermissionGroupInfo(
1219 mPermissionGroups.get(name), flags);
1220 }
1221 }
1222
1223 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1224 synchronized (mPackages) {
1225 final int N = mPermissionGroups.size();
1226 ArrayList<PermissionGroupInfo> out
1227 = new ArrayList<PermissionGroupInfo>(N);
1228 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1229 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1230 }
1231 return out;
1232 }
1233 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1236 PackageSetting ps = mSettings.mPackages.get(packageName);
1237 if(ps != null) {
1238 if(ps.pkg == null) {
1239 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1240 if(pInfo != null) {
1241 return pInfo.applicationInfo;
1242 }
1243 return null;
1244 }
1245 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1246 }
1247 return null;
1248 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1251 PackageSetting ps = mSettings.mPackages.get(packageName);
1252 if(ps != null) {
1253 if(ps.pkg == null) {
1254 ps.pkg = new PackageParser.Package(packageName);
1255 ps.pkg.applicationInfo.packageName = packageName;
1256 }
1257 return generatePackageInfo(ps.pkg, flags);
1258 }
1259 return null;
1260 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1263 synchronized (mPackages) {
1264 PackageParser.Package p = mPackages.get(packageName);
1265 if (Config.LOGV) Log.v(
1266 TAG, "getApplicationInfo " + packageName
1267 + ": " + p);
1268 if (p != null) {
1269 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001270 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 }
1272 if ("android".equals(packageName)||"system".equals(packageName)) {
1273 return mAndroidApplication;
1274 }
1275 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1276 return generateApplicationInfoFromSettingsLP(packageName, flags);
1277 }
1278 }
1279 return null;
1280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001281
1282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1284 mContext.enforceCallingOrSelfPermission(
1285 android.Manifest.permission.CLEAR_APP_CACHE, null);
1286 // Queue up an async operation since clearing cache may take a little while.
1287 mHandler.post(new Runnable() {
1288 public void run() {
1289 mHandler.removeCallbacks(this);
1290 int retCode = -1;
1291 if (mInstaller != null) {
1292 retCode = mInstaller.freeCache(freeStorageSize);
1293 if (retCode < 0) {
1294 Log.w(TAG, "Couldn't clear application caches");
1295 }
1296 } //end if mInstaller
1297 if (observer != null) {
1298 try {
1299 observer.onRemoveCompleted(null, (retCode >= 0));
1300 } catch (RemoteException e) {
1301 Log.w(TAG, "RemoveException when invoking call back");
1302 }
1303 }
1304 }
1305 });
1306 }
1307
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001308 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001309 mContext.enforceCallingOrSelfPermission(
1310 android.Manifest.permission.CLEAR_APP_CACHE, null);
1311 // Queue up an async operation since clearing cache may take a little while.
1312 mHandler.post(new Runnable() {
1313 public void run() {
1314 mHandler.removeCallbacks(this);
1315 int retCode = -1;
1316 if (mInstaller != null) {
1317 retCode = mInstaller.freeCache(freeStorageSize);
1318 if (retCode < 0) {
1319 Log.w(TAG, "Couldn't clear application caches");
1320 }
1321 }
1322 if(pi != null) {
1323 try {
1324 // Callback via pending intent
1325 int code = (retCode >= 0) ? 1 : 0;
1326 pi.sendIntent(null, code, null,
1327 null, null);
1328 } catch (SendIntentException e1) {
1329 Log.i(TAG, "Failed to send pending intent");
1330 }
1331 }
1332 }
1333 });
1334 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1337 synchronized (mPackages) {
1338 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001339
1340 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001342 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 }
1344 if (mResolveComponentName.equals(component)) {
1345 return mResolveActivity;
1346 }
1347 }
1348 return null;
1349 }
1350
1351 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1352 synchronized (mPackages) {
1353 PackageParser.Activity a = mReceivers.mActivities.get(component);
1354 if (Config.LOGV) Log.v(
1355 TAG, "getReceiverInfo " + component + ": " + a);
1356 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1357 return PackageParser.generateActivityInfo(a, flags);
1358 }
1359 }
1360 return null;
1361 }
1362
1363 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1364 synchronized (mPackages) {
1365 PackageParser.Service s = mServices.mServices.get(component);
1366 if (Config.LOGV) Log.v(
1367 TAG, "getServiceInfo " + component + ": " + s);
1368 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1369 return PackageParser.generateServiceInfo(s, flags);
1370 }
1371 }
1372 return null;
1373 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 public String[] getSystemSharedLibraryNames() {
1376 Set<String> libSet;
1377 synchronized (mPackages) {
1378 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001379 int size = libSet.size();
1380 if (size > 0) {
1381 String[] libs = new String[size];
1382 libSet.toArray(libs);
1383 return libs;
1384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001386 return null;
1387 }
1388
1389 public FeatureInfo[] getSystemAvailableFeatures() {
1390 Collection<FeatureInfo> featSet;
1391 synchronized (mPackages) {
1392 featSet = mAvailableFeatures.values();
1393 int size = featSet.size();
1394 if (size > 0) {
1395 FeatureInfo[] features = new FeatureInfo[size+1];
1396 featSet.toArray(features);
1397 FeatureInfo fi = new FeatureInfo();
1398 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1399 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1400 features[size] = fi;
1401 return features;
1402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
1404 return null;
1405 }
1406
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001407 public boolean hasSystemFeature(String name) {
1408 synchronized (mPackages) {
1409 return mAvailableFeatures.containsKey(name);
1410 }
1411 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 public int checkPermission(String permName, String pkgName) {
1414 synchronized (mPackages) {
1415 PackageParser.Package p = mPackages.get(pkgName);
1416 if (p != null && p.mExtras != null) {
1417 PackageSetting ps = (PackageSetting)p.mExtras;
1418 if (ps.sharedUser != null) {
1419 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1420 return PackageManager.PERMISSION_GRANTED;
1421 }
1422 } else if (ps.grantedPermissions.contains(permName)) {
1423 return PackageManager.PERMISSION_GRANTED;
1424 }
1425 }
1426 }
1427 return PackageManager.PERMISSION_DENIED;
1428 }
1429
1430 public int checkUidPermission(String permName, int uid) {
1431 synchronized (mPackages) {
1432 Object obj = mSettings.getUserIdLP(uid);
1433 if (obj != null) {
1434 if (obj instanceof SharedUserSetting) {
1435 SharedUserSetting sus = (SharedUserSetting)obj;
1436 if (sus.grantedPermissions.contains(permName)) {
1437 return PackageManager.PERMISSION_GRANTED;
1438 }
1439 } else if (obj instanceof PackageSetting) {
1440 PackageSetting ps = (PackageSetting)obj;
1441 if (ps.grantedPermissions.contains(permName)) {
1442 return PackageManager.PERMISSION_GRANTED;
1443 }
1444 }
1445 } else {
1446 HashSet<String> perms = mSystemPermissions.get(uid);
1447 if (perms != null && perms.contains(permName)) {
1448 return PackageManager.PERMISSION_GRANTED;
1449 }
1450 }
1451 }
1452 return PackageManager.PERMISSION_DENIED;
1453 }
1454
1455 private BasePermission findPermissionTreeLP(String permName) {
1456 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1457 if (permName.startsWith(bp.name) &&
1458 permName.length() > bp.name.length() &&
1459 permName.charAt(bp.name.length()) == '.') {
1460 return bp;
1461 }
1462 }
1463 return null;
1464 }
1465
1466 private BasePermission checkPermissionTreeLP(String permName) {
1467 if (permName != null) {
1468 BasePermission bp = findPermissionTreeLP(permName);
1469 if (bp != null) {
1470 if (bp.uid == Binder.getCallingUid()) {
1471 return bp;
1472 }
1473 throw new SecurityException("Calling uid "
1474 + Binder.getCallingUid()
1475 + " is not allowed to add to permission tree "
1476 + bp.name + " owned by uid " + bp.uid);
1477 }
1478 }
1479 throw new SecurityException("No permission tree found for " + permName);
1480 }
1481
1482 public boolean addPermission(PermissionInfo info) {
1483 synchronized (mPackages) {
1484 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1485 throw new SecurityException("Label must be specified in permission");
1486 }
1487 BasePermission tree = checkPermissionTreeLP(info.name);
1488 BasePermission bp = mSettings.mPermissions.get(info.name);
1489 boolean added = bp == null;
1490 if (added) {
1491 bp = new BasePermission(info.name, tree.sourcePackage,
1492 BasePermission.TYPE_DYNAMIC);
1493 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1494 throw new SecurityException(
1495 "Not allowed to modify non-dynamic permission "
1496 + info.name);
1497 }
1498 bp.perm = new PackageParser.Permission(tree.perm.owner,
1499 new PermissionInfo(info));
1500 bp.perm.info.packageName = tree.perm.info.packageName;
1501 bp.uid = tree.uid;
1502 if (added) {
1503 mSettings.mPermissions.put(info.name, bp);
1504 }
1505 mSettings.writeLP();
1506 return added;
1507 }
1508 }
1509
1510 public void removePermission(String name) {
1511 synchronized (mPackages) {
1512 checkPermissionTreeLP(name);
1513 BasePermission bp = mSettings.mPermissions.get(name);
1514 if (bp != null) {
1515 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1516 throw new SecurityException(
1517 "Not allowed to modify non-dynamic permission "
1518 + name);
1519 }
1520 mSettings.mPermissions.remove(name);
1521 mSettings.writeLP();
1522 }
1523 }
1524 }
1525
Dianne Hackborn854060af2009-07-09 18:14:31 -07001526 public boolean isProtectedBroadcast(String actionName) {
1527 synchronized (mPackages) {
1528 return mProtectedBroadcasts.contains(actionName);
1529 }
1530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 public int checkSignatures(String pkg1, String pkg2) {
1533 synchronized (mPackages) {
1534 PackageParser.Package p1 = mPackages.get(pkg1);
1535 PackageParser.Package p2 = mPackages.get(pkg2);
1536 if (p1 == null || p1.mExtras == null
1537 || p2 == null || p2.mExtras == null) {
1538 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1539 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001540 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542 }
1543
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001544 public int checkUidSignatures(int uid1, int uid2) {
1545 synchronized (mPackages) {
1546 Signature[] s1;
1547 Signature[] s2;
1548 Object obj = mSettings.getUserIdLP(uid1);
1549 if (obj != null) {
1550 if (obj instanceof SharedUserSetting) {
1551 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1552 } else if (obj instanceof PackageSetting) {
1553 s1 = ((PackageSetting)obj).signatures.mSignatures;
1554 } else {
1555 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1556 }
1557 } else {
1558 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1559 }
1560 obj = mSettings.getUserIdLP(uid2);
1561 if (obj != null) {
1562 if (obj instanceof SharedUserSetting) {
1563 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1564 } else if (obj instanceof PackageSetting) {
1565 s2 = ((PackageSetting)obj).signatures.mSignatures;
1566 } else {
1567 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1568 }
1569 } else {
1570 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1571 }
1572 return checkSignaturesLP(s1, s2);
1573 }
1574 }
1575
1576 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1577 if (s1 == null) {
1578 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1580 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1581 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001582 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1584 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001585 final int N1 = s1.length;
1586 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 for (int i=0; i<N1; i++) {
1588 boolean match = false;
1589 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001590 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 match = true;
1592 break;
1593 }
1594 }
1595 if (!match) {
1596 return PackageManager.SIGNATURE_NO_MATCH;
1597 }
1598 }
1599 return PackageManager.SIGNATURE_MATCH;
1600 }
1601
1602 public String[] getPackagesForUid(int uid) {
1603 synchronized (mPackages) {
1604 Object obj = mSettings.getUserIdLP(uid);
1605 if (obj instanceof SharedUserSetting) {
1606 SharedUserSetting sus = (SharedUserSetting)obj;
1607 final int N = sus.packages.size();
1608 String[] res = new String[N];
1609 Iterator<PackageSetting> it = sus.packages.iterator();
1610 int i=0;
1611 while (it.hasNext()) {
1612 res[i++] = it.next().name;
1613 }
1614 return res;
1615 } else if (obj instanceof PackageSetting) {
1616 PackageSetting ps = (PackageSetting)obj;
1617 return new String[] { ps.name };
1618 }
1619 }
1620 return null;
1621 }
1622
1623 public String getNameForUid(int uid) {
1624 synchronized (mPackages) {
1625 Object obj = mSettings.getUserIdLP(uid);
1626 if (obj instanceof SharedUserSetting) {
1627 SharedUserSetting sus = (SharedUserSetting)obj;
1628 return sus.name + ":" + sus.userId;
1629 } else if (obj instanceof PackageSetting) {
1630 PackageSetting ps = (PackageSetting)obj;
1631 return ps.name;
1632 }
1633 }
1634 return null;
1635 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 public int getUidForSharedUser(String sharedUserName) {
1638 if(sharedUserName == null) {
1639 return -1;
1640 }
1641 synchronized (mPackages) {
1642 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1643 if(suid == null) {
1644 return -1;
1645 }
1646 return suid.userId;
1647 }
1648 }
1649
1650 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1651 int flags) {
1652 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001653 return chooseBestActivity(intent, resolvedType, flags, query);
1654 }
1655
Mihai Predaeae850c2009-05-13 10:13:48 +02001656 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1657 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 if (query != null) {
1659 final int N = query.size();
1660 if (N == 1) {
1661 return query.get(0);
1662 } else if (N > 1) {
1663 // If there is more than one activity with the same priority,
1664 // then let the user decide between them.
1665 ResolveInfo r0 = query.get(0);
1666 ResolveInfo r1 = query.get(1);
1667 if (false) {
1668 System.out.println(r0.activityInfo.name +
1669 "=" + r0.priority + " vs " +
1670 r1.activityInfo.name +
1671 "=" + r1.priority);
1672 }
1673 // If the first activity has a higher priority, or a different
1674 // default, then it is always desireable to pick it.
1675 if (r0.priority != r1.priority
1676 || r0.preferredOrder != r1.preferredOrder
1677 || r0.isDefault != r1.isDefault) {
1678 return query.get(0);
1679 }
1680 // If we have saved a preference for a preferred activity for
1681 // this Intent, use that.
1682 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1683 flags, query, r0.priority);
1684 if (ri != null) {
1685 return ri;
1686 }
1687 return mResolveInfo;
1688 }
1689 }
1690 return null;
1691 }
1692
1693 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1694 int flags, List<ResolveInfo> query, int priority) {
1695 synchronized (mPackages) {
1696 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1697 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001698 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1700 if (prefs != null && prefs.size() > 0) {
1701 // First figure out how good the original match set is.
1702 // We will only allow preferred activities that came
1703 // from the same match quality.
1704 int match = 0;
1705 final int N = query.size();
1706 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1707 for (int j=0; j<N; j++) {
1708 ResolveInfo ri = query.get(j);
1709 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1710 + ": 0x" + Integer.toHexString(match));
1711 if (ri.match > match) match = ri.match;
1712 }
1713 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1714 + Integer.toHexString(match));
1715 match &= IntentFilter.MATCH_CATEGORY_MASK;
1716 final int M = prefs.size();
1717 for (int i=0; i<M; i++) {
1718 PreferredActivity pa = prefs.get(i);
1719 if (pa.mMatch != match) {
1720 continue;
1721 }
1722 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1723 if (DEBUG_PREFERRED) {
1724 Log.v(TAG, "Got preferred activity:");
1725 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1726 }
1727 if (ai != null) {
1728 for (int j=0; j<N; j++) {
1729 ResolveInfo ri = query.get(j);
1730 if (!ri.activityInfo.applicationInfo.packageName
1731 .equals(ai.applicationInfo.packageName)) {
1732 continue;
1733 }
1734 if (!ri.activityInfo.name.equals(ai.name)) {
1735 continue;
1736 }
1737
1738 // Okay we found a previously set preferred app.
1739 // If the result set is different from when this
1740 // was created, we need to clear it and re-ask the
1741 // user their preference.
1742 if (!pa.sameSet(query, priority)) {
1743 Log.i(TAG, "Result set changed, dropping preferred activity for "
1744 + intent + " type " + resolvedType);
1745 mSettings.mPreferredActivities.removeFilter(pa);
1746 return null;
1747 }
1748
1749 // Yay!
1750 return ri;
1751 }
1752 }
1753 }
1754 }
1755 }
1756 return null;
1757 }
1758
1759 public List<ResolveInfo> queryIntentActivities(Intent intent,
1760 String resolvedType, int flags) {
1761 ComponentName comp = intent.getComponent();
1762 if (comp != null) {
1763 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1764 ActivityInfo ai = getActivityInfo(comp, flags);
1765 if (ai != null) {
1766 ResolveInfo ri = new ResolveInfo();
1767 ri.activityInfo = ai;
1768 list.add(ri);
1769 }
1770 return list;
1771 }
1772
1773 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001774 String pkgName = intent.getPackage();
1775 if (pkgName == null) {
1776 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1777 resolvedType, flags);
1778 }
1779 PackageParser.Package pkg = mPackages.get(pkgName);
1780 if (pkg != null) {
1781 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1782 resolvedType, flags, pkg.activities);
1783 }
1784 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 }
1786 }
1787
1788 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1789 Intent[] specifics, String[] specificTypes, Intent intent,
1790 String resolvedType, int flags) {
1791 final String resultsAction = intent.getAction();
1792
1793 List<ResolveInfo> results = queryIntentActivities(
1794 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1795 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1796
1797 int specificsPos = 0;
1798 int N;
1799
1800 // todo: note that the algorithm used here is O(N^2). This
1801 // isn't a problem in our current environment, but if we start running
1802 // into situations where we have more than 5 or 10 matches then this
1803 // should probably be changed to something smarter...
1804
1805 // First we go through and resolve each of the specific items
1806 // that were supplied, taking care of removing any corresponding
1807 // duplicate items in the generic resolve list.
1808 if (specifics != null) {
1809 for (int i=0; i<specifics.length; i++) {
1810 final Intent sintent = specifics[i];
1811 if (sintent == null) {
1812 continue;
1813 }
1814
1815 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1816 String action = sintent.getAction();
1817 if (resultsAction != null && resultsAction.equals(action)) {
1818 // If this action was explicitly requested, then don't
1819 // remove things that have it.
1820 action = null;
1821 }
1822 ComponentName comp = sintent.getComponent();
1823 ResolveInfo ri = null;
1824 ActivityInfo ai = null;
1825 if (comp == null) {
1826 ri = resolveIntent(
1827 sintent,
1828 specificTypes != null ? specificTypes[i] : null,
1829 flags);
1830 if (ri == null) {
1831 continue;
1832 }
1833 if (ri == mResolveInfo) {
1834 // ACK! Must do something better with this.
1835 }
1836 ai = ri.activityInfo;
1837 comp = new ComponentName(ai.applicationInfo.packageName,
1838 ai.name);
1839 } else {
1840 ai = getActivityInfo(comp, flags);
1841 if (ai == null) {
1842 continue;
1843 }
1844 }
1845
1846 // Look for any generic query activities that are duplicates
1847 // of this specific one, and remove them from the results.
1848 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1849 N = results.size();
1850 int j;
1851 for (j=specificsPos; j<N; j++) {
1852 ResolveInfo sri = results.get(j);
1853 if ((sri.activityInfo.name.equals(comp.getClassName())
1854 && sri.activityInfo.applicationInfo.packageName.equals(
1855 comp.getPackageName()))
1856 || (action != null && sri.filter.matchAction(action))) {
1857 results.remove(j);
1858 if (Config.LOGV) Log.v(
1859 TAG, "Removing duplicate item from " + j
1860 + " due to specific " + specificsPos);
1861 if (ri == null) {
1862 ri = sri;
1863 }
1864 j--;
1865 N--;
1866 }
1867 }
1868
1869 // Add this specific item to its proper place.
1870 if (ri == null) {
1871 ri = new ResolveInfo();
1872 ri.activityInfo = ai;
1873 }
1874 results.add(specificsPos, ri);
1875 ri.specificIndex = i;
1876 specificsPos++;
1877 }
1878 }
1879
1880 // Now we go through the remaining generic results and remove any
1881 // duplicate actions that are found here.
1882 N = results.size();
1883 for (int i=specificsPos; i<N-1; i++) {
1884 final ResolveInfo rii = results.get(i);
1885 if (rii.filter == null) {
1886 continue;
1887 }
1888
1889 // Iterate over all of the actions of this result's intent
1890 // filter... typically this should be just one.
1891 final Iterator<String> it = rii.filter.actionsIterator();
1892 if (it == null) {
1893 continue;
1894 }
1895 while (it.hasNext()) {
1896 final String action = it.next();
1897 if (resultsAction != null && resultsAction.equals(action)) {
1898 // If this action was explicitly requested, then don't
1899 // remove things that have it.
1900 continue;
1901 }
1902 for (int j=i+1; j<N; j++) {
1903 final ResolveInfo rij = results.get(j);
1904 if (rij.filter != null && rij.filter.hasAction(action)) {
1905 results.remove(j);
1906 if (Config.LOGV) Log.v(
1907 TAG, "Removing duplicate item from " + j
1908 + " due to action " + action + " at " + i);
1909 j--;
1910 N--;
1911 }
1912 }
1913 }
1914
1915 // If the caller didn't request filter information, drop it now
1916 // so we don't have to marshall/unmarshall it.
1917 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1918 rii.filter = null;
1919 }
1920 }
1921
1922 // Filter out the caller activity if so requested.
1923 if (caller != null) {
1924 N = results.size();
1925 for (int i=0; i<N; i++) {
1926 ActivityInfo ainfo = results.get(i).activityInfo;
1927 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1928 && caller.getClassName().equals(ainfo.name)) {
1929 results.remove(i);
1930 break;
1931 }
1932 }
1933 }
1934
1935 // If the caller didn't request filter information,
1936 // drop them now so we don't have to
1937 // marshall/unmarshall it.
1938 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1939 N = results.size();
1940 for (int i=0; i<N; i++) {
1941 results.get(i).filter = null;
1942 }
1943 }
1944
1945 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1946 return results;
1947 }
1948
1949 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1950 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001951 ComponentName comp = intent.getComponent();
1952 if (comp != null) {
1953 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1954 ActivityInfo ai = getReceiverInfo(comp, flags);
1955 if (ai != null) {
1956 ResolveInfo ri = new ResolveInfo();
1957 ri.activityInfo = ai;
1958 list.add(ri);
1959 }
1960 return list;
1961 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001964 String pkgName = intent.getPackage();
1965 if (pkgName == null) {
1966 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1967 resolvedType, flags);
1968 }
1969 PackageParser.Package pkg = mPackages.get(pkgName);
1970 if (pkg != null) {
1971 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1972 resolvedType, flags, pkg.receivers);
1973 }
1974 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 }
1976 }
1977
1978 public ResolveInfo resolveService(Intent intent, String resolvedType,
1979 int flags) {
1980 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1981 flags);
1982 if (query != null) {
1983 if (query.size() >= 1) {
1984 // If there is more than one service with the same priority,
1985 // just arbitrarily pick the first one.
1986 return query.get(0);
1987 }
1988 }
1989 return null;
1990 }
1991
1992 public List<ResolveInfo> queryIntentServices(Intent intent,
1993 String resolvedType, int flags) {
1994 ComponentName comp = intent.getComponent();
1995 if (comp != null) {
1996 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1997 ServiceInfo si = getServiceInfo(comp, flags);
1998 if (si != null) {
1999 ResolveInfo ri = new ResolveInfo();
2000 ri.serviceInfo = si;
2001 list.add(ri);
2002 }
2003 return list;
2004 }
2005
2006 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002007 String pkgName = intent.getPackage();
2008 if (pkgName == null) {
2009 return (List<ResolveInfo>)mServices.queryIntent(intent,
2010 resolvedType, flags);
2011 }
2012 PackageParser.Package pkg = mPackages.get(pkgName);
2013 if (pkg != null) {
2014 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2015 resolvedType, flags, pkg.services);
2016 }
2017 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 }
2019 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 public List<PackageInfo> getInstalledPackages(int flags) {
2022 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2023
2024 synchronized (mPackages) {
2025 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2026 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2027 while (i.hasNext()) {
2028 final PackageSetting ps = i.next();
2029 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2030 if(psPkg != null) {
2031 finalList.add(psPkg);
2032 }
2033 }
2034 }
2035 else {
2036 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2037 while (i.hasNext()) {
2038 final PackageParser.Package p = i.next();
2039 if (p.applicationInfo != null) {
2040 PackageInfo pi = generatePackageInfo(p, flags);
2041 if(pi != null) {
2042 finalList.add(pi);
2043 }
2044 }
2045 }
2046 }
2047 }
2048 return finalList;
2049 }
2050
2051 public List<ApplicationInfo> getInstalledApplications(int flags) {
2052 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2053 synchronized(mPackages) {
2054 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2055 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2056 while (i.hasNext()) {
2057 final PackageSetting ps = i.next();
2058 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2059 if(ai != null) {
2060 finalList.add(ai);
2061 }
2062 }
2063 }
2064 else {
2065 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2066 while (i.hasNext()) {
2067 final PackageParser.Package p = i.next();
2068 if (p.applicationInfo != null) {
2069 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2070 if(ai != null) {
2071 finalList.add(ai);
2072 }
2073 }
2074 }
2075 }
2076 }
2077 return finalList;
2078 }
2079
2080 public List<ApplicationInfo> getPersistentApplications(int flags) {
2081 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2082
2083 synchronized (mPackages) {
2084 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2085 while (i.hasNext()) {
2086 PackageParser.Package p = i.next();
2087 if (p.applicationInfo != null
2088 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2089 && (!mSafeMode || (p.applicationInfo.flags
2090 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2091 finalList.add(p.applicationInfo);
2092 }
2093 }
2094 }
2095
2096 return finalList;
2097 }
2098
2099 public ProviderInfo resolveContentProvider(String name, int flags) {
2100 synchronized (mPackages) {
2101 final PackageParser.Provider provider = mProviders.get(name);
2102 return provider != null
2103 && mSettings.isEnabledLP(provider.info, flags)
2104 && (!mSafeMode || (provider.info.applicationInfo.flags
2105 &ApplicationInfo.FLAG_SYSTEM) != 0)
2106 ? PackageParser.generateProviderInfo(provider, flags)
2107 : null;
2108 }
2109 }
2110
Fred Quintana718d8a22009-04-29 17:53:20 -07002111 /**
2112 * @deprecated
2113 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 public void querySyncProviders(List outNames, List outInfo) {
2115 synchronized (mPackages) {
2116 Iterator<Map.Entry<String, PackageParser.Provider>> i
2117 = mProviders.entrySet().iterator();
2118
2119 while (i.hasNext()) {
2120 Map.Entry<String, PackageParser.Provider> entry = i.next();
2121 PackageParser.Provider p = entry.getValue();
2122
2123 if (p.syncable
2124 && (!mSafeMode || (p.info.applicationInfo.flags
2125 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2126 outNames.add(entry.getKey());
2127 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2128 }
2129 }
2130 }
2131 }
2132
2133 public List<ProviderInfo> queryContentProviders(String processName,
2134 int uid, int flags) {
2135 ArrayList<ProviderInfo> finalList = null;
2136
2137 synchronized (mPackages) {
2138 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2139 while (i.hasNext()) {
2140 PackageParser.Provider p = i.next();
2141 if (p.info.authority != null
2142 && (processName == null ||
2143 (p.info.processName.equals(processName)
2144 && p.info.applicationInfo.uid == uid))
2145 && mSettings.isEnabledLP(p.info, flags)
2146 && (!mSafeMode || (p.info.applicationInfo.flags
2147 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2148 if (finalList == null) {
2149 finalList = new ArrayList<ProviderInfo>(3);
2150 }
2151 finalList.add(PackageParser.generateProviderInfo(p,
2152 flags));
2153 }
2154 }
2155 }
2156
2157 if (finalList != null) {
2158 Collections.sort(finalList, mProviderInitOrderSorter);
2159 }
2160
2161 return finalList;
2162 }
2163
2164 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2165 int flags) {
2166 synchronized (mPackages) {
2167 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2168 return PackageParser.generateInstrumentationInfo(i, flags);
2169 }
2170 }
2171
2172 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2173 int flags) {
2174 ArrayList<InstrumentationInfo> finalList =
2175 new ArrayList<InstrumentationInfo>();
2176
2177 synchronized (mPackages) {
2178 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2179 while (i.hasNext()) {
2180 PackageParser.Instrumentation p = i.next();
2181 if (targetPackage == null
2182 || targetPackage.equals(p.info.targetPackage)) {
2183 finalList.add(PackageParser.generateInstrumentationInfo(p,
2184 flags));
2185 }
2186 }
2187 }
2188
2189 return finalList;
2190 }
2191
2192 private void scanDirLI(File dir, int flags, int scanMode) {
2193 Log.d(TAG, "Scanning app dir " + dir);
2194
2195 String[] files = dir.list();
2196
2197 int i;
2198 for (i=0; i<files.length; i++) {
2199 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002200 if (!isPackageFilename(files[i])) {
2201 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002202 continue;
2203 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002204 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002206 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002207 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2208 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002209 // Delete the apk
2210 Log.w(TAG, "Cleaning up failed install of " + file);
2211 file.delete();
2212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 }
2214 }
2215
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002216 private static File getSettingsProblemFile() {
2217 File dataDir = Environment.getDataDirectory();
2218 File systemDir = new File(dataDir, "system");
2219 File fname = new File(systemDir, "uiderrors.txt");
2220 return fname;
2221 }
2222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 private static void reportSettingsProblem(int priority, String msg) {
2224 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002225 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 FileOutputStream out = new FileOutputStream(fname, true);
2227 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002228 SimpleDateFormat formatter = new SimpleDateFormat();
2229 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2230 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 pw.close();
2232 FileUtils.setPermissions(
2233 fname.toString(),
2234 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2235 -1, -1);
2236 } catch (java.io.IOException e) {
2237 }
2238 Log.println(priority, TAG, msg);
2239 }
2240
2241 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2242 PackageParser.Package pkg, File srcFile, int parseFlags) {
2243 if (GET_CERTIFICATES) {
2244 if (ps == null || !ps.codePath.equals(srcFile)
2245 || ps.getTimeStamp() != srcFile.lastModified()) {
2246 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2247 if (!pp.collectCertificates(pkg, parseFlags)) {
2248 mLastScanError = pp.getParseError();
2249 return false;
2250 }
2251 }
2252 }
2253 return true;
2254 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 /*
2257 * Scan a package and return the newly parsed package.
2258 * Returns null in case of errors and the error code is stored in mLastScanError
2259 */
2260 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002261 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002263 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002265 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002268 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 if (pkg == null) {
2270 mLastScanError = pp.getParseError();
2271 return null;
2272 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002273 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 PackageSetting updatedPkg;
2275 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002276 // Look to see if we already know about this package.
2277 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
2278 if (oldName != null && oldName.equals(pkg.mOriginalPackage)) {
2279 // This package has been renamed to its original name. Let's
2280 // use that.
2281 ps = mSettings.peekPackageLP(pkg.mOriginalPackage);
2282 }
2283 // If there was no original package, see one for the real package name.
2284 if (ps == null) {
2285 ps = mSettings.peekPackageLP(pkg.packageName);
2286 }
2287 // Check to see if this package could be hiding/updating a system
2288 // package. Must look for it either under the original or real
2289 // package name depending on our state.
2290 updatedPkg = mSettings.mDisabledSysPackages.get(
2291 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002293 // First check if this is a system package that may involve an update
2294 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2295 if (!ps.codePath.equals(scanFile)) {
2296 // The path has changed from what was last scanned... check the
2297 // version of the new path against what we have stored to determine
2298 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002299 if (pkg.mVersionCode < ps.versionCode) {
2300 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002301 // Ignore entry. Skip it.
2302 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2303 + "ignored: updated version " + ps.versionCode
2304 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002305 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2306 return null;
2307 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002308 // The current app on the system partion is better than
2309 // what we have updated to on the data partition; switch
2310 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002311 // At this point, its safely assumed that package installation for
2312 // apps in system partition will go through. If not there won't be a working
2313 // version of the app
2314 synchronized (mPackages) {
2315 // Just remove the loaded entries from package lists.
2316 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002317 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002318 Log.w(TAG, "Package " + ps.name + " at " + scanFile
2319 + "reverting from " + ps.codePathString
2320 + ": new version " + pkg.mVersionCode
2321 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002322 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2323 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002324 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 }
2327 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002328 if (updatedPkg != null) {
2329 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2330 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2331 }
2332 // Verify certificates against what was last scanned
2333 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2334 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2335 return null;
2336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 // The apk is forward locked (not public) if its code and resources
2338 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002339 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002341 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002342 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002343
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002344 String codePath = null;
2345 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002346 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2347 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002348 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002349 } else {
2350 // Should not happen at all. Just log an error.
2351 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2352 }
2353 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002354 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002355 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002356 codePath = pkg.mScanPath;
2357 // Set application objects path explicitly.
2358 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002360 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 }
2362
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002363 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2364 String destCodePath, String destResPath) {
2365 pkg.mPath = pkg.mScanPath = destCodePath;
2366 pkg.applicationInfo.sourceDir = destCodePath;
2367 pkg.applicationInfo.publicSourceDir = destResPath;
2368 }
2369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 private static String fixProcessName(String defProcessName,
2371 String processName, int uid) {
2372 if (processName == null) {
2373 return defProcessName;
2374 }
2375 return processName;
2376 }
2377
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002378 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2380 if (pkg.mSignatures != null) {
2381 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2382 updateSignature)) {
2383 Log.e(TAG, "Package " + pkg.packageName
2384 + " signatures do not match the previously installed version; ignoring!");
2385 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2386 return false;
2387 }
2388
2389 if (pkgSetting.sharedUser != null) {
2390 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2391 pkg.mSignatures, updateSignature)) {
2392 Log.e(TAG, "Package " + pkg.packageName
2393 + " has no signatures that match those in shared user "
2394 + pkgSetting.sharedUser.name + "; ignoring!");
2395 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2396 return false;
2397 }
2398 }
2399 } else {
2400 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2401 }
2402 return true;
2403 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002404
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002405 public boolean performDexOpt(String packageName) {
2406 if (!mNoDexOpt) {
2407 return false;
2408 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002409
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002410 PackageParser.Package p;
2411 synchronized (mPackages) {
2412 p = mPackages.get(packageName);
2413 if (p == null || p.mDidDexOpt) {
2414 return false;
2415 }
2416 }
2417 synchronized (mInstallLock) {
2418 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2419 }
2420 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002421
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002422 static final int DEX_OPT_SKIPPED = 0;
2423 static final int DEX_OPT_PERFORMED = 1;
2424 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002425
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002426 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2427 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002428 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002429 String path = pkg.mScanPath;
2430 int ret = 0;
2431 try {
2432 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002433 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002434 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002435 pkg.mDidDexOpt = true;
2436 performed = true;
2437 }
2438 } catch (FileNotFoundException e) {
2439 Log.w(TAG, "Apk not found for dexopt: " + path);
2440 ret = -1;
2441 } catch (IOException e) {
2442 Log.w(TAG, "Exception reading apk: " + path, e);
2443 ret = -1;
2444 }
2445 if (ret < 0) {
2446 //error from installer
2447 return DEX_OPT_FAILED;
2448 }
2449 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002450
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002451 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2452 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002453
2454 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2455 return Environment.isEncryptedFilesystemEnabled() &&
2456 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2457 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002458
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002459 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2460 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2461 Log.w(TAG, "Unable to update from " + oldPkg.name
2462 + " to " + newPkg.packageName
2463 + ": old package not in system partition");
2464 return false;
2465 } else if (mPackages.get(oldPkg.name) != null) {
2466 Log.w(TAG, "Unable to update from " + oldPkg.name
2467 + " to " + newPkg.packageName
2468 + ": old package still exists");
2469 return false;
2470 }
2471 return true;
2472 }
2473
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002474 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2475 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002476 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002477 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2478 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002479 // Bail out. The resource and code paths haven't been set.
2480 Log.w(TAG, " Code and resource paths haven't been set correctly");
2481 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2482 return null;
2483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 mScanningPath = scanFile;
2485 if (pkg == null) {
2486 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2487 return null;
2488 }
2489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2491 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2492 }
2493
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002494 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 synchronized (mPackages) {
2496 if (mAndroidApplication != null) {
2497 Log.w(TAG, "*************************************************");
2498 Log.w(TAG, "Core android package being redefined. Skipping.");
2499 Log.w(TAG, " file=" + mScanningPath);
2500 Log.w(TAG, "*************************************************");
2501 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2502 return null;
2503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 // Set up information for our fall-back user intent resolution
2506 // activity.
2507 mPlatformPackage = pkg;
2508 pkg.mVersionCode = mSdkVersion;
2509 mAndroidApplication = pkg.applicationInfo;
2510 mResolveActivity.applicationInfo = mAndroidApplication;
2511 mResolveActivity.name = ResolverActivity.class.getName();
2512 mResolveActivity.packageName = mAndroidApplication.packageName;
2513 mResolveActivity.processName = mAndroidApplication.processName;
2514 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2515 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2516 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2517 mResolveActivity.exported = true;
2518 mResolveActivity.enabled = true;
2519 mResolveInfo.activityInfo = mResolveActivity;
2520 mResolveInfo.priority = 0;
2521 mResolveInfo.preferredOrder = 0;
2522 mResolveInfo.match = 0;
2523 mResolveComponentName = new ComponentName(
2524 mAndroidApplication.packageName, mResolveActivity.name);
2525 }
2526 }
2527
2528 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002529 TAG, "Scanning package " + pkg.packageName);
2530 if (mPackages.containsKey(pkg.packageName)
2531 || mSharedLibraries.containsKey(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 Log.w(TAG, "*************************************************");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002533 Log.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 + " already installed. Skipping duplicate.");
2535 Log.w(TAG, "*************************************************");
2536 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2537 return null;
2538 }
2539
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002540 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002541 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2542 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 SharedUserSetting suid = null;
2545 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002548
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002549 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2550 // Only system apps can use these features.
2551 pkg.mOriginalPackage = null;
2552 pkg.mRealPackage = null;
2553 pkg.mAdoptPermissions = null;
2554 }
2555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 synchronized (mPackages) {
2557 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002558 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2559 if (mTmpSharedLibraries == null ||
2560 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2561 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2562 }
2563 int num = 0;
2564 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2565 for (int i=0; i<N; i++) {
2566 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 if (file == null) {
2568 Log.e(TAG, "Package " + pkg.packageName
2569 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002570 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2572 return null;
2573 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002574 mTmpSharedLibraries[num] = file;
2575 num++;
2576 }
2577 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2578 for (int i=0; i<N; i++) {
2579 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2580 if (file == null) {
2581 Log.w(TAG, "Package " + pkg.packageName
2582 + " desires unavailable shared library "
2583 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2584 } else {
2585 mTmpSharedLibraries[num] = file;
2586 num++;
2587 }
2588 }
2589 if (num > 0) {
2590 pkg.usesLibraryFiles = new String[num];
2591 System.arraycopy(mTmpSharedLibraries, 0,
2592 pkg.usesLibraryFiles, 0, num);
2593 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002594
Dianne Hackborn49237342009-08-27 20:08:01 -07002595 if (pkg.reqFeatures != null) {
2596 N = pkg.reqFeatures.size();
2597 for (int i=0; i<N; i++) {
2598 FeatureInfo fi = pkg.reqFeatures.get(i);
2599 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2600 // Don't care.
2601 continue;
2602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002603
Dianne Hackborn49237342009-08-27 20:08:01 -07002604 if (fi.name != null) {
2605 if (mAvailableFeatures.get(fi.name) == null) {
2606 Log.e(TAG, "Package " + pkg.packageName
2607 + " requires unavailable feature "
2608 + fi.name + "; failing!");
2609 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2610 return null;
2611 }
2612 }
2613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 }
2615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 if (pkg.mSharedUserId != null) {
2618 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2619 pkg.applicationInfo.flags, true);
2620 if (suid == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002621 Log.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 + " for shared user failed");
2623 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2624 return null;
2625 }
2626 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2627 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2628 + suid.userId + "): packages=" + suid.packages);
2629 }
2630 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002631
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002632 if (false) {
2633 if (pkg.mOriginalPackage != null) {
2634 Log.w(TAG, "WAITING FOR DEBUGGER");
2635 Debug.waitForDebugger();
2636 Log.i(TAG, "Package " + pkg.packageName + " from original package"
2637 + pkg.mOriginalPackage);
2638 }
2639 }
2640
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002641 // Check if we are renaming from an original package name.
2642 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002643 String realName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002644 if (pkg.mOriginalPackage != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002645 // This package may need to be renamed to a previously
2646 // installed name. Let's check on that...
2647 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
2648 if (pkg.mOriginalPackage.equals(renamed)) {
2649 // This package had originally been installed as the
2650 // original name, and we have already taken care of
2651 // transitioning to the new one. Just update the new
2652 // one to continue using the old name.
2653 realName = pkg.mRealPackage;
2654 if (!pkg.packageName.equals(renamed)) {
2655 // Callers into this function may have already taken
2656 // care of renaming the package; only do it here if
2657 // it is not already done.
2658 pkg.setPackageName(renamed);
2659 }
2660
2661 } else if ((origPackage
2662 = mSettings.peekPackageLP(pkg.mOriginalPackage)) != null) {
2663 // We do have the package already installed under its
2664 // original name... should we use it?
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002665 if (!verifyPackageUpdate(origPackage, pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002666 // New package is not compatible with original.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002667 origPackage = null;
2668 } else if (origPackage.sharedUser != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002669 // Make sure uid is compatible between packages.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002670 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2671 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2672 + " to " + pkg.packageName + ": old uid "
2673 + origPackage.sharedUser.name
2674 + " differs from " + pkg.mSharedUserId);
2675 origPackage = null;
2676 }
2677 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002678 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2679 + pkg.packageName + " to old name " + origPackage.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002680 }
2681 }
2682 }
2683
2684 if (mTransferedPackages.contains(pkg.packageName)) {
2685 Log.w(TAG, "Package " + pkg.packageName
2686 + " was transferred to another, but its .apk remains");
2687 }
2688
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002689 // Just create the setting, don't add it yet. For already existing packages
2690 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002691 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 destResourceFile, pkg.applicationInfo.flags, true, false);
2693 if (pkgSetting == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002694 Log.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2696 return null;
2697 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002698
2699 if (pkgSetting.origPackage != null) {
2700 // If we are first transitioning from an original package,
2701 // fix up the new package's name now. We need to do this after
2702 // looking up the package under its new name, so getPackageLP
2703 // can take care of fiddling things correctly.
2704 pkg.setPackageName(origPackage.name);
2705
2706 // File a report about this.
2707 String msg = "New package " + pkgSetting.realName
2708 + " renamed to replace old package " + pkgSetting.name;
2709 reportSettingsProblem(Log.WARN, msg);
2710
2711 // Make a note of it.
2712 mTransferedPackages.add(origPackage.name);
2713
2714 // No longer need to retain this.
2715 pkgSetting.origPackage = null;
2716 }
2717
2718 if (realName != null) {
2719 // Make a note of it.
2720 mTransferedPackages.add(pkg.packageName);
2721 }
2722
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002723 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 pkg.applicationInfo.uid = pkgSetting.userId;
2728 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002729
2730 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2732 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2733 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2734 return null;
2735 }
2736 // The signature has changed, but this package is in the system
2737 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002738 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 // However... if this package is part of a shared user, but it
2740 // doesn't match the signature of the shared user, let's fail.
2741 // What this means is that you can't change the signatures
2742 // associated with an overall shared user, which doesn't seem all
2743 // that unreasonable.
2744 if (pkgSetting.sharedUser != null) {
2745 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2746 pkg.mSignatures, false)) {
2747 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2748 return null;
2749 }
2750 }
2751 removeExisting = true;
2752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002753
The Android Open Source Project10592532009-03-18 17:39:46 -07002754 // Verify that this new package doesn't have any content providers
2755 // that conflict with existing packages. Only do this if the
2756 // package isn't already installed, since we don't want to break
2757 // things that are installed.
2758 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2759 int N = pkg.providers.size();
2760 int i;
2761 for (i=0; i<N; i++) {
2762 PackageParser.Provider p = pkg.providers.get(i);
2763 String names[] = p.info.authority.split(";");
2764 for (int j = 0; j < names.length; j++) {
2765 if (mProviders.containsKey(names[j])) {
2766 PackageParser.Provider other = mProviders.get(names[j]);
2767 Log.w(TAG, "Can't install because provider name " + names[j] +
2768 " (in package " + pkg.applicationInfo.packageName +
2769 ") is already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002770 + ((other != null && other.getComponentName() != null)
2771 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project10592532009-03-18 17:39:46 -07002772 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2773 return null;
2774 }
2775 }
2776 }
2777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 }
2779
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002780 final String pkgName = pkg.packageName;
2781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002783 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002785 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 if (ret != 0) {
2787 String msg = "System package " + pkg.packageName
2788 + " could not have data directory erased after signature change.";
2789 reportSettingsProblem(Log.WARN, msg);
2790 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2791 return null;
2792 }
2793 }
2794 Log.w(TAG, "System package " + pkg.packageName
2795 + " signature changed: existing data removed.");
2796 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2797 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002798
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002799 if (pkg.mAdoptPermissions != null) {
2800 // This package wants to adopt ownership of permissions from
2801 // another package.
2802 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2803 String origName = pkg.mAdoptPermissions.get(i);
2804 PackageSetting orig = mSettings.peekPackageLP(origName);
2805 if (orig != null) {
2806 if (verifyPackageUpdate(orig, pkg)) {
2807 Log.i(TAG, "Adopting permissions from "
2808 + origName + " to " + pkg.packageName);
2809 mSettings.transferPermissions(origName, pkg.packageName);
2810 }
2811 }
2812 }
2813 }
2814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 long scanFileTime = scanFile.lastModified();
2816 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2817 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2818 pkg.applicationInfo.processName = fixProcessName(
2819 pkg.applicationInfo.packageName,
2820 pkg.applicationInfo.processName,
2821 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822
2823 File dataPath;
2824 if (mPlatformPackage == pkg) {
2825 // The system package is special.
2826 dataPath = new File (Environment.getDataDirectory(), "system");
2827 pkg.applicationInfo.dataDir = dataPath.getPath();
2828 } else {
2829 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002830 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2831 if (useEncryptedFSDir) {
2832 dataPath = new File(mSecureAppDataDir, pkgName);
2833 } else {
2834 dataPath = new File(mAppDataDir, pkgName);
2835 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002836
2837 boolean uidError = false;
2838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 if (dataPath.exists()) {
2840 mOutPermissions[1] = 0;
2841 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2842 if (mOutPermissions[1] == pkg.applicationInfo.uid
2843 || !Process.supportsProcesses()) {
2844 pkg.applicationInfo.dataDir = dataPath.getPath();
2845 } else {
2846 boolean recovered = false;
2847 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2848 // If this is a system app, we can at least delete its
2849 // current data so the application will still work.
2850 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002851 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002852 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 // Old data gone!
2854 String msg = "System package " + pkg.packageName
2855 + " has changed from uid: "
2856 + mOutPermissions[1] + " to "
2857 + pkg.applicationInfo.uid + "; old data erased";
2858 reportSettingsProblem(Log.WARN, msg);
2859 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002862 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 pkg.applicationInfo.uid);
2864 if (ret == -1) {
2865 // Ack should not happen!
2866 msg = "System package " + pkg.packageName
2867 + " could not have data directory re-created after delete.";
2868 reportSettingsProblem(Log.WARN, msg);
2869 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2870 return null;
2871 }
2872 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 if (!recovered) {
2875 mHasSystemUidErrors = true;
2876 }
2877 }
2878 if (!recovered) {
2879 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2880 + pkg.applicationInfo.uid + "/fs_"
2881 + mOutPermissions[1];
2882 String msg = "Package " + pkg.packageName
2883 + " has mismatched uid: "
2884 + mOutPermissions[1] + " on disk, "
2885 + pkg.applicationInfo.uid + " in settings";
2886 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002887 mSettings.mReadMessages.append(msg);
2888 mSettings.mReadMessages.append('\n');
2889 uidError = true;
2890 if (!pkgSetting.uidError) {
2891 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 }
2894 }
2895 }
2896 pkg.applicationInfo.dataDir = dataPath.getPath();
2897 } else {
2898 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2899 Log.v(TAG, "Want this data dir: " + dataPath);
2900 //invoke installer to do the actual installation
2901 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002902 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 pkg.applicationInfo.uid);
2904 if(ret < 0) {
2905 // Error from installer
2906 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2907 return null;
2908 }
2909 } else {
2910 dataPath.mkdirs();
2911 if (dataPath.exists()) {
2912 FileUtils.setPermissions(
2913 dataPath.toString(),
2914 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2915 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2916 }
2917 }
2918 if (dataPath.exists()) {
2919 pkg.applicationInfo.dataDir = dataPath.getPath();
2920 } else {
2921 Log.w(TAG, "Unable to create data directory: " + dataPath);
2922 pkg.applicationInfo.dataDir = null;
2923 }
2924 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002925
2926 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 }
2928
2929 // Perform shared library installation and dex validation and
2930 // optimization, if this is not a system app.
2931 if (mInstaller != null) {
2932 String path = scanFile.getPath();
2933 if (scanFileNewer) {
2934 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002935 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2936 if (err != PackageManager.INSTALL_SUCCEEDED) {
2937 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 return null;
2939 }
2940 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002941 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002942
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002943 if ((scanMode&SCAN_NO_DEX) == 0) {
2944 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2946 return null;
2947 }
2948 }
2949 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 if (mFactoryTest && pkg.requestedPermissions.contains(
2952 android.Manifest.permission.FACTORY_TEST)) {
2953 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2954 }
2955
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002956 // Request the ActivityManager to kill the process(only for existing packages)
2957 // so that we do not end up in a confused state while the user is still using the older
2958 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002959 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002960 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002961 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002962 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002965 // We don't expect installation to fail beyond this point,
2966 if ((scanMode&SCAN_MONITOR) != 0) {
2967 mAppDirs.put(pkg.mPath, pkg);
2968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002970 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002972 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08002973 // Make sure we don't accidentally delete its data.
2974 mSettings.mPackagesToBeCleaned.remove(pkgName);
2975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 int N = pkg.providers.size();
2977 StringBuilder r = null;
2978 int i;
2979 for (i=0; i<N; i++) {
2980 PackageParser.Provider p = pkg.providers.get(i);
2981 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2982 p.info.processName, pkg.applicationInfo.uid);
2983 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2984 p.info.name), p);
2985 p.syncable = p.info.isSyncable;
2986 String names[] = p.info.authority.split(";");
2987 p.info.authority = null;
2988 for (int j = 0; j < names.length; j++) {
2989 if (j == 1 && p.syncable) {
2990 // We only want the first authority for a provider to possibly be
2991 // syncable, so if we already added this provider using a different
2992 // authority clear the syncable flag. We copy the provider before
2993 // changing it because the mProviders object contains a reference
2994 // to a provider that we don't want to change.
2995 // Only do this for the second authority since the resulting provider
2996 // object can be the same for all future authorities for this provider.
2997 p = new PackageParser.Provider(p);
2998 p.syncable = false;
2999 }
3000 if (!mProviders.containsKey(names[j])) {
3001 mProviders.put(names[j], p);
3002 if (p.info.authority == null) {
3003 p.info.authority = names[j];
3004 } else {
3005 p.info.authority = p.info.authority + ";" + names[j];
3006 }
3007 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3008 Log.d(TAG, "Registered content provider: " + names[j] +
3009 ", className = " + p.info.name +
3010 ", isSyncable = " + p.info.isSyncable);
3011 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07003012 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 Log.w(TAG, "Skipping provider name " + names[j] +
3014 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07003015 "): name already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003016 + ((other != null && other.getComponentName() != null)
3017 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 }
3019 }
3020 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3021 if (r == null) {
3022 r = new StringBuilder(256);
3023 } else {
3024 r.append(' ');
3025 }
3026 r.append(p.info.name);
3027 }
3028 }
3029 if (r != null) {
3030 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3031 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 N = pkg.services.size();
3034 r = null;
3035 for (i=0; i<N; i++) {
3036 PackageParser.Service s = pkg.services.get(i);
3037 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3038 s.info.processName, pkg.applicationInfo.uid);
3039 mServices.addService(s);
3040 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3041 if (r == null) {
3042 r = new StringBuilder(256);
3043 } else {
3044 r.append(' ');
3045 }
3046 r.append(s.info.name);
3047 }
3048 }
3049 if (r != null) {
3050 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 N = pkg.receivers.size();
3054 r = null;
3055 for (i=0; i<N; i++) {
3056 PackageParser.Activity a = pkg.receivers.get(i);
3057 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3058 a.info.processName, pkg.applicationInfo.uid);
3059 mReceivers.addActivity(a, "receiver");
3060 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3061 if (r == null) {
3062 r = new StringBuilder(256);
3063 } else {
3064 r.append(' ');
3065 }
3066 r.append(a.info.name);
3067 }
3068 }
3069 if (r != null) {
3070 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3071 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 N = pkg.activities.size();
3074 r = null;
3075 for (i=0; i<N; i++) {
3076 PackageParser.Activity a = pkg.activities.get(i);
3077 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3078 a.info.processName, pkg.applicationInfo.uid);
3079 mActivities.addActivity(a, "activity");
3080 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3081 if (r == null) {
3082 r = new StringBuilder(256);
3083 } else {
3084 r.append(' ');
3085 }
3086 r.append(a.info.name);
3087 }
3088 }
3089 if (r != null) {
3090 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 N = pkg.permissionGroups.size();
3094 r = null;
3095 for (i=0; i<N; i++) {
3096 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3097 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3098 if (cur == null) {
3099 mPermissionGroups.put(pg.info.name, pg);
3100 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3101 if (r == null) {
3102 r = new StringBuilder(256);
3103 } else {
3104 r.append(' ');
3105 }
3106 r.append(pg.info.name);
3107 }
3108 } else {
3109 Log.w(TAG, "Permission group " + pg.info.name + " from package "
3110 + pg.info.packageName + " ignored: original from "
3111 + cur.info.packageName);
3112 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3113 if (r == null) {
3114 r = new StringBuilder(256);
3115 } else {
3116 r.append(' ');
3117 }
3118 r.append("DUP:");
3119 r.append(pg.info.name);
3120 }
3121 }
3122 }
3123 if (r != null) {
3124 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 N = pkg.permissions.size();
3128 r = null;
3129 for (i=0; i<N; i++) {
3130 PackageParser.Permission p = pkg.permissions.get(i);
3131 HashMap<String, BasePermission> permissionMap =
3132 p.tree ? mSettings.mPermissionTrees
3133 : mSettings.mPermissions;
3134 p.group = mPermissionGroups.get(p.info.group);
3135 if (p.info.group == null || p.group != null) {
3136 BasePermission bp = permissionMap.get(p.info.name);
3137 if (bp == null) {
3138 bp = new BasePermission(p.info.name, p.info.packageName,
3139 BasePermission.TYPE_NORMAL);
3140 permissionMap.put(p.info.name, bp);
3141 }
3142 if (bp.perm == null) {
3143 if (bp.sourcePackage == null
3144 || bp.sourcePackage.equals(p.info.packageName)) {
3145 BasePermission tree = findPermissionTreeLP(p.info.name);
3146 if (tree == null
3147 || tree.sourcePackage.equals(p.info.packageName)) {
3148 bp.perm = p;
3149 bp.uid = pkg.applicationInfo.uid;
3150 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3151 if (r == null) {
3152 r = new StringBuilder(256);
3153 } else {
3154 r.append(' ');
3155 }
3156 r.append(p.info.name);
3157 }
3158 } else {
3159 Log.w(TAG, "Permission " + p.info.name + " from package "
3160 + p.info.packageName + " ignored: base tree "
3161 + tree.name + " is from package "
3162 + tree.sourcePackage);
3163 }
3164 } else {
3165 Log.w(TAG, "Permission " + p.info.name + " from package "
3166 + p.info.packageName + " ignored: original from "
3167 + bp.sourcePackage);
3168 }
3169 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3170 if (r == null) {
3171 r = new StringBuilder(256);
3172 } else {
3173 r.append(' ');
3174 }
3175 r.append("DUP:");
3176 r.append(p.info.name);
3177 }
3178 } else {
3179 Log.w(TAG, "Permission " + p.info.name + " from package "
3180 + p.info.packageName + " ignored: no group "
3181 + p.group);
3182 }
3183 }
3184 if (r != null) {
3185 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3186 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 N = pkg.instrumentation.size();
3189 r = null;
3190 for (i=0; i<N; i++) {
3191 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3192 a.info.packageName = pkg.applicationInfo.packageName;
3193 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3194 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3195 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003196 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3198 if (r == null) {
3199 r = new StringBuilder(256);
3200 } else {
3201 r.append(' ');
3202 }
3203 r.append(a.info.name);
3204 }
3205 }
3206 if (r != null) {
3207 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3208 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003209
Dianne Hackborn854060af2009-07-09 18:14:31 -07003210 if (pkg.protectedBroadcasts != null) {
3211 N = pkg.protectedBroadcasts.size();
3212 for (i=0; i<N; i++) {
3213 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3214 }
3215 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 pkgSetting.setTimeStamp(scanFileTime);
3218 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 return pkg;
3221 }
3222
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003223 private void killApplication(String pkgName, int uid) {
3224 // Request the ActivityManager to kill the process(only for existing packages)
3225 // so that we do not end up in a confused state while the user is still using the older
3226 // version of the application while the new one gets installed.
3227 IActivityManager am = ActivityManagerNative.getDefault();
3228 if (am != null) {
3229 try {
3230 am.killApplicationWithUid(pkgName, uid);
3231 } catch (RemoteException e) {
3232 }
3233 }
3234 }
3235
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003236 // The following constants are returned by cachePackageSharedLibsForAbiLI
3237 // to indicate if native shared libraries were found in the package.
3238 // Values are:
3239 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3240 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3241 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3242 // in package (and not installed)
3243 //
3244 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3245 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3246 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003248 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3249 // and automatically copy them to /data/data/<appname>/lib if present.
3250 //
3251 // NOTE: this method may throw an IOException if the library cannot
3252 // be copied to its final destination, e.g. if there isn't enough
3253 // room left on the data partition, or a ZipException if the package
3254 // file is malformed.
3255 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003256 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3257 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003258 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3259 final String apkLib = "lib/";
3260 final int apkLibLen = apkLib.length();
3261 final int cpuAbiLen = cpuAbi.length();
3262 final String libPrefix = "lib";
3263 final int libPrefixLen = libPrefix.length();
3264 final String libSuffix = ".so";
3265 final int libSuffixLen = libSuffix.length();
3266 boolean hasNativeLibraries = false;
3267 boolean installedNativeLibraries = false;
3268
3269 // the minimum length of a valid native shared library of the form
3270 // lib/<something>/lib<name>.so.
3271 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3272
3273 ZipFile zipFile = new ZipFile(scanFile);
3274 Enumeration<ZipEntry> entries =
3275 (Enumeration<ZipEntry>) zipFile.entries();
3276
3277 while (entries.hasMoreElements()) {
3278 ZipEntry entry = entries.nextElement();
3279 // skip directories
3280 if (entry.isDirectory()) {
3281 continue;
3282 }
3283 String entryName = entry.getName();
3284
3285 // check that the entry looks like lib/<something>/lib<name>.so
3286 // here, but don't check the ABI just yet.
3287 //
3288 // - must be sufficiently long
3289 // - must end with libSuffix, i.e. ".so"
3290 // - must start with apkLib, i.e. "lib/"
3291 if (entryName.length() < minEntryLen ||
3292 !entryName.endsWith(libSuffix) ||
3293 !entryName.startsWith(apkLib) ) {
3294 continue;
3295 }
3296
3297 // file name must start with libPrefix, i.e. "lib"
3298 int lastSlash = entryName.lastIndexOf('/');
3299
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003300 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003301 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3302 continue;
3303 }
3304
3305 hasNativeLibraries = true;
3306
3307 // check the cpuAbi now, between lib/ and /lib<name>.so
3308 //
3309 if (lastSlash != apkLibLen + cpuAbiLen ||
3310 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3311 continue;
3312
3313 // extract the library file name, ensure it doesn't contain
3314 // weird characters. we're guaranteed here that it doesn't contain
3315 // a directory separator though.
3316 String libFileName = entryName.substring(lastSlash+1);
3317 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3318 continue;
3319 }
3320
3321 installedNativeLibraries = true;
3322
3323 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3324 File.separator + libFileName;
3325 File sharedLibraryFile = new File(sharedLibraryFilePath);
3326 if (! sharedLibraryFile.exists() ||
3327 sharedLibraryFile.length() != entry.getSize() ||
3328 sharedLibraryFile.lastModified() != entry.getTime()) {
3329 if (Config.LOGD) {
3330 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003332 if (mInstaller == null) {
3333 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003334 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003335 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003336 sharedLibraryFile);
3337 }
3338 }
3339 if (!hasNativeLibraries)
3340 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3341
3342 if (!installedNativeLibraries)
3343 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3344
3345 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3346 }
3347
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003348 // Find the gdbserver executable program in a package at
3349 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3350 //
3351 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3352 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3353 //
3354 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3355 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3356 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3357 final String GDBSERVER = "gdbserver";
3358 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3359
3360 ZipFile zipFile = new ZipFile(scanFile);
3361 Enumeration<ZipEntry> entries =
3362 (Enumeration<ZipEntry>) zipFile.entries();
3363
3364 while (entries.hasMoreElements()) {
3365 ZipEntry entry = entries.nextElement();
3366 // skip directories
3367 if (entry.isDirectory()) {
3368 continue;
3369 }
3370 String entryName = entry.getName();
3371
3372 if (!entryName.equals(apkGdbServerPath)) {
3373 continue;
3374 }
3375
3376 String installGdbServerPath = installGdbServerDir.getPath() +
3377 "/" + GDBSERVER;
3378 File installGdbServerFile = new File(installGdbServerPath);
3379 if (! installGdbServerFile.exists() ||
3380 installGdbServerFile.length() != entry.getSize() ||
3381 installGdbServerFile.lastModified() != entry.getTime()) {
3382 if (Config.LOGD) {
3383 Log.d(TAG, "Caching gdbserver " + entry.getName());
3384 }
3385 if (mInstaller == null) {
3386 installGdbServerDir.mkdir();
3387 }
3388 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3389 installGdbServerFile);
3390 }
3391 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3392 }
3393 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3394 }
3395
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003396 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3397 // and copy them to /data/data/<appname>/lib.
3398 //
3399 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3400 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3401 // one if ro.product.cpu.abi2 is defined.
3402 //
3403 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3404 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003405 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003406 try {
3407 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3408
3409 // some architectures are capable of supporting several CPU ABIs
3410 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3411 // this is indicated by the definition of the ro.product.cpu.abi2
3412 // system property.
3413 //
3414 // only scan the package twice in case of ABI mismatch
3415 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003416 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003417 if (cpuAbi2 != null) {
3418 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003420
3421 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3422 Log.w(TAG,"Native ABI mismatch from package file");
3423 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003425
3426 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3427 cpuAbi = cpuAbi2;
3428 }
3429 }
3430
3431 // for debuggable packages, also extract gdbserver from lib/<abi>
3432 // into /data/data/<appname>/lib too.
3433 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3434 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3435 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3436 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3437 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003440 } catch (ZipException e) {
3441 Log.w(TAG, "Failed to extract data from package file", e);
3442 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003444 Log.w(TAG, "Failed to cache package shared libs", e);
3445 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003447 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 }
3449
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003450 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003452 File binaryDir,
3453 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 InputStream inputStream = zipFile.getInputStream(entry);
3455 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003456 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003458 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 // now need to be left as world readable and owned by the system.
3460 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3461 ! tempFile.setLastModified(entry.getTime()) ||
3462 FileUtils.setPermissions(tempFilePath,
3463 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003464 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003466 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 // Failed to properly write file.
3468 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003469 throw new IOException("Couldn't create cached binary "
3470 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 }
3472 } finally {
3473 inputStream.close();
3474 }
3475 }
3476
3477 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3478 if (chatty && Config.LOGD) Log.d(
3479 TAG, "Removing package " + pkg.applicationInfo.packageName );
3480
3481 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 mPackages.remove(pkg.applicationInfo.packageName);
3485 if (pkg.mPath != null) {
3486 mAppDirs.remove(pkg.mPath);
3487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 PackageSetting ps = (PackageSetting)pkg.mExtras;
3490 if (ps != null && ps.sharedUser != null) {
3491 // XXX don't do this until the data is removed.
3492 if (false) {
3493 ps.sharedUser.packages.remove(ps);
3494 if (ps.sharedUser.packages.size() == 0) {
3495 // Remove.
3496 }
3497 }
3498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 int N = pkg.providers.size();
3501 StringBuilder r = null;
3502 int i;
3503 for (i=0; i<N; i++) {
3504 PackageParser.Provider p = pkg.providers.get(i);
3505 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3506 p.info.name));
3507 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 /* The is another ContentProvider with this authority when
3510 * this app was installed so this authority is null,
3511 * Ignore it as we don't have to unregister the provider.
3512 */
3513 continue;
3514 }
3515 String names[] = p.info.authority.split(";");
3516 for (int j = 0; j < names.length; j++) {
3517 if (mProviders.get(names[j]) == p) {
3518 mProviders.remove(names[j]);
3519 if (chatty && Config.LOGD) Log.d(
3520 TAG, "Unregistered content provider: " + names[j] +
3521 ", className = " + p.info.name +
3522 ", isSyncable = " + p.info.isSyncable);
3523 }
3524 }
3525 if (chatty) {
3526 if (r == null) {
3527 r = new StringBuilder(256);
3528 } else {
3529 r.append(' ');
3530 }
3531 r.append(p.info.name);
3532 }
3533 }
3534 if (r != null) {
3535 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 N = pkg.services.size();
3539 r = null;
3540 for (i=0; i<N; i++) {
3541 PackageParser.Service s = pkg.services.get(i);
3542 mServices.removeService(s);
3543 if (chatty) {
3544 if (r == null) {
3545 r = new StringBuilder(256);
3546 } else {
3547 r.append(' ');
3548 }
3549 r.append(s.info.name);
3550 }
3551 }
3552 if (r != null) {
3553 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3554 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 N = pkg.receivers.size();
3557 r = null;
3558 for (i=0; i<N; i++) {
3559 PackageParser.Activity a = pkg.receivers.get(i);
3560 mReceivers.removeActivity(a, "receiver");
3561 if (chatty) {
3562 if (r == null) {
3563 r = new StringBuilder(256);
3564 } else {
3565 r.append(' ');
3566 }
3567 r.append(a.info.name);
3568 }
3569 }
3570 if (r != null) {
3571 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 N = pkg.activities.size();
3575 r = null;
3576 for (i=0; i<N; i++) {
3577 PackageParser.Activity a = pkg.activities.get(i);
3578 mActivities.removeActivity(a, "activity");
3579 if (chatty) {
3580 if (r == null) {
3581 r = new StringBuilder(256);
3582 } else {
3583 r.append(' ');
3584 }
3585 r.append(a.info.name);
3586 }
3587 }
3588 if (r != null) {
3589 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 N = pkg.permissions.size();
3593 r = null;
3594 for (i=0; i<N; i++) {
3595 PackageParser.Permission p = pkg.permissions.get(i);
3596 boolean tree = false;
3597 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3598 if (bp == null) {
3599 tree = true;
3600 bp = mSettings.mPermissionTrees.get(p.info.name);
3601 }
3602 if (bp != null && bp.perm == p) {
3603 if (bp.type != BasePermission.TYPE_BUILTIN) {
3604 if (tree) {
3605 mSettings.mPermissionTrees.remove(p.info.name);
3606 } else {
3607 mSettings.mPermissions.remove(p.info.name);
3608 }
3609 } else {
3610 bp.perm = null;
3611 }
3612 if (chatty) {
3613 if (r == null) {
3614 r = new StringBuilder(256);
3615 } else {
3616 r.append(' ');
3617 }
3618 r.append(p.info.name);
3619 }
3620 }
3621 }
3622 if (r != null) {
3623 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3624 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 N = pkg.instrumentation.size();
3627 r = null;
3628 for (i=0; i<N; i++) {
3629 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003630 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 if (chatty) {
3632 if (r == null) {
3633 r = new StringBuilder(256);
3634 } else {
3635 r.append(' ');
3636 }
3637 r.append(a.info.name);
3638 }
3639 }
3640 if (r != null) {
3641 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3642 }
3643 }
3644 }
3645
3646 private static final boolean isPackageFilename(String name) {
3647 return name != null && name.endsWith(".apk");
3648 }
3649
3650 private void updatePermissionsLP() {
3651 // Make sure there are no dangling permission trees.
3652 Iterator<BasePermission> it = mSettings.mPermissionTrees
3653 .values().iterator();
3654 while (it.hasNext()) {
3655 BasePermission bp = it.next();
3656 if (bp.perm == null) {
3657 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3658 + " from package " + bp.sourcePackage);
3659 it.remove();
3660 }
3661 }
3662
3663 // Make sure all dynamic permissions have been assigned to a package,
3664 // and make sure there are no dangling permissions.
3665 it = mSettings.mPermissions.values().iterator();
3666 while (it.hasNext()) {
3667 BasePermission bp = it.next();
3668 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3669 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3670 + bp.name + " pkg=" + bp.sourcePackage
3671 + " info=" + bp.pendingInfo);
3672 if (bp.perm == null && bp.pendingInfo != null) {
3673 BasePermission tree = findPermissionTreeLP(bp.name);
3674 if (tree != null) {
3675 bp.perm = new PackageParser.Permission(tree.perm.owner,
3676 new PermissionInfo(bp.pendingInfo));
3677 bp.perm.info.packageName = tree.perm.info.packageName;
3678 bp.perm.info.name = bp.name;
3679 bp.uid = tree.uid;
3680 }
3681 }
3682 }
3683 if (bp.perm == null) {
3684 Log.w(TAG, "Removing dangling permission: " + bp.name
3685 + " from package " + bp.sourcePackage);
3686 it.remove();
3687 }
3688 }
3689
3690 // Now update the permissions for all packages, in particular
3691 // replace the granted permissions of the system packages.
3692 for (PackageParser.Package pkg : mPackages.values()) {
3693 grantPermissionsLP(pkg, false);
3694 }
3695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3698 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3699 if (ps == null) {
3700 return;
3701 }
3702 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3703 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 if (replace) {
3706 ps.permissionsFixed = false;
3707 if (gp == ps) {
3708 gp.grantedPermissions.clear();
3709 gp.gids = mGlobalGids;
3710 }
3711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003713 if (gp.gids == null) {
3714 gp.gids = mGlobalGids;
3715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 final int N = pkg.requestedPermissions.size();
3718 for (int i=0; i<N; i++) {
3719 String name = pkg.requestedPermissions.get(i);
3720 BasePermission bp = mSettings.mPermissions.get(name);
3721 PackageParser.Permission p = bp != null ? bp.perm : null;
3722 if (false) {
3723 if (gp != ps) {
3724 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3725 + ": " + p);
3726 }
3727 }
3728 if (p != null) {
3729 final String perm = p.info.name;
3730 boolean allowed;
3731 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3732 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3733 allowed = true;
3734 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3735 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003736 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003738 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 == PackageManager.SIGNATURE_MATCH);
3740 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3741 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3742 // For updated system applications, the signatureOrSystem permission
3743 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003744 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3746 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3747 if(sysPs.grantedPermissions.contains(perm)) {
3748 allowed = true;
3749 } else {
3750 allowed = false;
3751 }
3752 } else {
3753 allowed = true;
3754 }
3755 }
3756 }
3757 } else {
3758 allowed = false;
3759 }
3760 if (false) {
3761 if (gp != ps) {
3762 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3763 }
3764 }
3765 if (allowed) {
3766 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3767 && ps.permissionsFixed) {
3768 // If this is an existing, non-system package, then
3769 // we can't add any new permissions to it.
3770 if (!gp.loadedPermissions.contains(perm)) {
3771 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003772 // Except... if this is a permission that was added
3773 // to the platform (note: need to only do this when
3774 // updating the platform).
3775 final int NP = PackageParser.NEW_PERMISSIONS.length;
3776 for (int ip=0; ip<NP; ip++) {
3777 final PackageParser.NewPermissionInfo npi
3778 = PackageParser.NEW_PERMISSIONS[ip];
3779 if (npi.name.equals(perm)
3780 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3781 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003782 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003783 + pkg.packageName);
3784 break;
3785 }
3786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 }
3788 }
3789 if (allowed) {
3790 if (!gp.grantedPermissions.contains(perm)) {
3791 addedPermission = true;
3792 gp.grantedPermissions.add(perm);
3793 gp.gids = appendInts(gp.gids, bp.gids);
3794 }
3795 } else {
3796 Log.w(TAG, "Not granting permission " + perm
3797 + " to package " + pkg.packageName
3798 + " because it was previously installed without");
3799 }
3800 } else {
3801 Log.w(TAG, "Not granting permission " + perm
3802 + " to package " + pkg.packageName
3803 + " (protectionLevel=" + p.info.protectionLevel
3804 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3805 + ")");
3806 }
3807 } else {
3808 Log.w(TAG, "Unknown permission " + name
3809 + " in package " + pkg.packageName);
3810 }
3811 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003814 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3815 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 // This is the first that we have heard about this package, so the
3817 // permissions we have now selected are fixed until explicitly
3818 // changed.
3819 ps.permissionsFixed = true;
3820 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3821 }
3822 }
3823
3824 private final class ActivityIntentResolver
3825 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003826 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003828 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 }
3830
Mihai Preda074edef2009-05-18 17:13:31 +02003831 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003833 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3835 }
3836
Mihai Predaeae850c2009-05-13 10:13:48 +02003837 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3838 ArrayList<PackageParser.Activity> packageActivities) {
3839 if (packageActivities == null) {
3840 return null;
3841 }
3842 mFlags = flags;
3843 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3844 int N = packageActivities.size();
3845 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3846 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003847
3848 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003849 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003850 intentFilters = packageActivities.get(i).intents;
3851 if (intentFilters != null && intentFilters.size() > 0) {
3852 listCut.add(intentFilters);
3853 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003854 }
3855 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3856 }
3857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003859 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 if (SHOW_INFO || Config.LOGV) Log.v(
3861 TAG, " " + type + " " +
3862 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3863 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3864 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003865 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3867 if (SHOW_INFO || Config.LOGV) {
3868 Log.v(TAG, " IntentFilter:");
3869 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3870 }
3871 if (!intent.debugCheck()) {
3872 Log.w(TAG, "==> For Activity " + a.info.name);
3873 }
3874 addFilter(intent);
3875 }
3876 }
3877
3878 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003879 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 if (SHOW_INFO || Config.LOGV) Log.v(
3881 TAG, " " + type + " " +
3882 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3883 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3884 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003885 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3887 if (SHOW_INFO || Config.LOGV) {
3888 Log.v(TAG, " IntentFilter:");
3889 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3890 }
3891 removeFilter(intent);
3892 }
3893 }
3894
3895 @Override
3896 protected boolean allowFilterResult(
3897 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3898 ActivityInfo filterAi = filter.activity.info;
3899 for (int i=dest.size()-1; i>=0; i--) {
3900 ActivityInfo destAi = dest.get(i).activityInfo;
3901 if (destAi.name == filterAi.name
3902 && destAi.packageName == filterAi.packageName) {
3903 return false;
3904 }
3905 }
3906 return true;
3907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 @Override
3910 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3911 int match) {
3912 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3913 return null;
3914 }
3915 final PackageParser.Activity activity = info.activity;
3916 if (mSafeMode && (activity.info.applicationInfo.flags
3917 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3918 return null;
3919 }
3920 final ResolveInfo res = new ResolveInfo();
3921 res.activityInfo = PackageParser.generateActivityInfo(activity,
3922 mFlags);
3923 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3924 res.filter = info;
3925 }
3926 res.priority = info.getPriority();
3927 res.preferredOrder = activity.owner.mPreferredOrder;
3928 //System.out.println("Result: " + res.activityInfo.className +
3929 // " = " + res.priority);
3930 res.match = match;
3931 res.isDefault = info.hasDefault;
3932 res.labelRes = info.labelRes;
3933 res.nonLocalizedLabel = info.nonLocalizedLabel;
3934 res.icon = info.icon;
3935 return res;
3936 }
3937
3938 @Override
3939 protected void sortResults(List<ResolveInfo> results) {
3940 Collections.sort(results, mResolvePrioritySorter);
3941 }
3942
3943 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003944 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003946 out.print(prefix); out.print(
3947 Integer.toHexString(System.identityHashCode(filter.activity)));
3948 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003949 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 }
3951
3952// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3953// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3954// final List<ResolveInfo> retList = Lists.newArrayList();
3955// while (i.hasNext()) {
3956// final ResolveInfo resolveInfo = i.next();
3957// if (isEnabledLP(resolveInfo.activityInfo)) {
3958// retList.add(resolveInfo);
3959// }
3960// }
3961// return retList;
3962// }
3963
3964 // Keys are String (activity class name), values are Activity.
3965 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3966 = new HashMap<ComponentName, PackageParser.Activity>();
3967 private int mFlags;
3968 }
3969
3970 private final class ServiceIntentResolver
3971 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003972 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003974 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 }
3976
Mihai Preda074edef2009-05-18 17:13:31 +02003977 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003979 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3981 }
3982
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003983 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3984 ArrayList<PackageParser.Service> packageServices) {
3985 if (packageServices == null) {
3986 return null;
3987 }
3988 mFlags = flags;
3989 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3990 int N = packageServices.size();
3991 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3992 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3993
3994 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3995 for (int i = 0; i < N; ++i) {
3996 intentFilters = packageServices.get(i).intents;
3997 if (intentFilters != null && intentFilters.size() > 0) {
3998 listCut.add(intentFilters);
3999 }
4000 }
4001 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4002 }
4003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004005 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 if (SHOW_INFO || Config.LOGV) Log.v(
4007 TAG, " " + (s.info.nonLocalizedLabel != null
4008 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4009 if (SHOW_INFO || Config.LOGV) Log.v(
4010 TAG, " Class=" + s.info.name);
4011 int NI = s.intents.size();
4012 int j;
4013 for (j=0; j<NI; j++) {
4014 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4015 if (SHOW_INFO || Config.LOGV) {
4016 Log.v(TAG, " IntentFilter:");
4017 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4018 }
4019 if (!intent.debugCheck()) {
4020 Log.w(TAG, "==> For Service " + s.info.name);
4021 }
4022 addFilter(intent);
4023 }
4024 }
4025
4026 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004027 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 if (SHOW_INFO || Config.LOGV) Log.v(
4029 TAG, " " + (s.info.nonLocalizedLabel != null
4030 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4031 if (SHOW_INFO || Config.LOGV) Log.v(
4032 TAG, " Class=" + s.info.name);
4033 int NI = s.intents.size();
4034 int j;
4035 for (j=0; j<NI; j++) {
4036 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4037 if (SHOW_INFO || Config.LOGV) {
4038 Log.v(TAG, " IntentFilter:");
4039 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4040 }
4041 removeFilter(intent);
4042 }
4043 }
4044
4045 @Override
4046 protected boolean allowFilterResult(
4047 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4048 ServiceInfo filterSi = filter.service.info;
4049 for (int i=dest.size()-1; i>=0; i--) {
4050 ServiceInfo destAi = dest.get(i).serviceInfo;
4051 if (destAi.name == filterSi.name
4052 && destAi.packageName == filterSi.packageName) {
4053 return false;
4054 }
4055 }
4056 return true;
4057 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 @Override
4060 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4061 int match) {
4062 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4063 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4064 return null;
4065 }
4066 final PackageParser.Service service = info.service;
4067 if (mSafeMode && (service.info.applicationInfo.flags
4068 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4069 return null;
4070 }
4071 final ResolveInfo res = new ResolveInfo();
4072 res.serviceInfo = PackageParser.generateServiceInfo(service,
4073 mFlags);
4074 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4075 res.filter = filter;
4076 }
4077 res.priority = info.getPriority();
4078 res.preferredOrder = service.owner.mPreferredOrder;
4079 //System.out.println("Result: " + res.activityInfo.className +
4080 // " = " + res.priority);
4081 res.match = match;
4082 res.isDefault = info.hasDefault;
4083 res.labelRes = info.labelRes;
4084 res.nonLocalizedLabel = info.nonLocalizedLabel;
4085 res.icon = info.icon;
4086 return res;
4087 }
4088
4089 @Override
4090 protected void sortResults(List<ResolveInfo> results) {
4091 Collections.sort(results, mResolvePrioritySorter);
4092 }
4093
4094 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004095 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004097 out.print(prefix); out.print(
4098 Integer.toHexString(System.identityHashCode(filter.service)));
4099 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004100 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 }
4102
4103// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4104// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4105// final List<ResolveInfo> retList = Lists.newArrayList();
4106// while (i.hasNext()) {
4107// final ResolveInfo resolveInfo = (ResolveInfo) i;
4108// if (isEnabledLP(resolveInfo.serviceInfo)) {
4109// retList.add(resolveInfo);
4110// }
4111// }
4112// return retList;
4113// }
4114
4115 // Keys are String (activity class name), values are Activity.
4116 private final HashMap<ComponentName, PackageParser.Service> mServices
4117 = new HashMap<ComponentName, PackageParser.Service>();
4118 private int mFlags;
4119 };
4120
4121 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4122 new Comparator<ResolveInfo>() {
4123 public int compare(ResolveInfo r1, ResolveInfo r2) {
4124 int v1 = r1.priority;
4125 int v2 = r2.priority;
4126 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4127 if (v1 != v2) {
4128 return (v1 > v2) ? -1 : 1;
4129 }
4130 v1 = r1.preferredOrder;
4131 v2 = r2.preferredOrder;
4132 if (v1 != v2) {
4133 return (v1 > v2) ? -1 : 1;
4134 }
4135 if (r1.isDefault != r2.isDefault) {
4136 return r1.isDefault ? -1 : 1;
4137 }
4138 v1 = r1.match;
4139 v2 = r2.match;
4140 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4141 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4142 }
4143 };
4144
4145 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4146 new Comparator<ProviderInfo>() {
4147 public int compare(ProviderInfo p1, ProviderInfo p2) {
4148 final int v1 = p1.initOrder;
4149 final int v2 = p2.initOrder;
4150 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4151 }
4152 };
4153
4154 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4155 IActivityManager am = ActivityManagerNative.getDefault();
4156 if (am != null) {
4157 try {
4158 final Intent intent = new Intent(action,
4159 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4160 if (extras != null) {
4161 intent.putExtras(extras);
4162 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004163 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 am.broadcastIntent(
4165 null, intent,
4166 null, null, 0, null, null, null, false, false);
4167 } catch (RemoteException ex) {
4168 }
4169 }
4170 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004171
4172 public String nextPackageToClean(String lastPackage) {
4173 synchronized (mPackages) {
4174 if (!mMediaMounted) {
4175 // If the external storage is no longer mounted at this point,
4176 // the caller may not have been able to delete all of this
4177 // packages files and can not delete any more. Bail.
4178 return null;
4179 }
4180 if (lastPackage != null) {
4181 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4182 }
4183 return mSettings.mPackagesToBeCleaned.size() > 0
4184 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4185 }
4186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004188 void schedulePackageCleaning(String packageName) {
4189 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4190 }
4191
4192 void startCleaningPackages() {
4193 synchronized (mPackages) {
4194 if (!mMediaMounted) {
4195 return;
4196 }
4197 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4198 return;
4199 }
4200 }
4201 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4202 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4203 IActivityManager am = ActivityManagerNative.getDefault();
4204 if (am != null) {
4205 try {
4206 am.startService(null, intent, null);
4207 } catch (RemoteException e) {
4208 }
4209 }
4210 }
4211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 private final class AppDirObserver extends FileObserver {
4213 public AppDirObserver(String path, int mask, boolean isrom) {
4214 super(path, mask);
4215 mRootDir = path;
4216 mIsRom = isrom;
4217 }
4218
4219 public void onEvent(int event, String path) {
4220 String removedPackage = null;
4221 int removedUid = -1;
4222 String addedPackage = null;
4223 int addedUid = -1;
4224
4225 synchronized (mInstallLock) {
4226 String fullPathStr = null;
4227 File fullPath = null;
4228 if (path != null) {
4229 fullPath = new File(mRootDir, path);
4230 fullPathStr = fullPath.getPath();
4231 }
4232
4233 if (Config.LOGV) Log.v(
4234 TAG, "File " + fullPathStr + " changed: "
4235 + Integer.toHexString(event));
4236
4237 if (!isPackageFilename(path)) {
4238 if (Config.LOGV) Log.v(
4239 TAG, "Ignoring change of non-package file: " + fullPathStr);
4240 return;
4241 }
4242
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004243 // Ignore packages that are being installed or
4244 // have just been installed.
4245 if (ignoreCodePath(fullPathStr)) {
4246 return;
4247 }
4248 PackageParser.Package p = null;
4249 synchronized (mPackages) {
4250 p = mAppDirs.get(fullPathStr);
4251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004253 if (p != null) {
4254 removePackageLI(p, true);
4255 removedPackage = p.applicationInfo.packageName;
4256 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004257 }
4258 }
4259
4260 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004262 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004263 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4264 PackageParser.PARSE_CHATTY |
4265 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004266 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 if (p != null) {
4268 synchronized (mPackages) {
4269 grantPermissionsLP(p, false);
4270 }
4271 addedPackage = p.applicationInfo.packageName;
4272 addedUid = p.applicationInfo.uid;
4273 }
4274 }
4275 }
4276
4277 synchronized (mPackages) {
4278 mSettings.writeLP();
4279 }
4280 }
4281
4282 if (removedPackage != null) {
4283 Bundle extras = new Bundle(1);
4284 extras.putInt(Intent.EXTRA_UID, removedUid);
4285 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4286 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4287 }
4288 if (addedPackage != null) {
4289 Bundle extras = new Bundle(1);
4290 extras.putInt(Intent.EXTRA_UID, addedUid);
4291 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4292 }
4293 }
4294
4295 private final String mRootDir;
4296 private final boolean mIsRom;
4297 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 /* Called when a downloaded package installation has been confirmed by the user */
4300 public void installPackage(
4301 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004302 installPackage(packageURI, observer, flags, null);
4303 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004304
Jacek Surazski65e13172009-04-28 15:26:38 +02004305 /* Called when a downloaded package installation has been confirmed by the user */
4306 public void installPackage(
4307 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4308 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 mContext.enforceCallingOrSelfPermission(
4310 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004311
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004312 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004313 msg.obj = new InstallParams(packageURI, observer, flags,
4314 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004315 mHandler.sendMessage(msg);
4316 }
4317
Christopher Tate1bb69062010-02-19 17:02:12 -08004318 public void finishPackageInstall(int token) {
4319 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4320 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4321 mHandler.sendMessage(msg);
4322 }
4323
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004324 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 // Queue up an async operation since the package installation may take a little while.
4326 mHandler.post(new Runnable() {
4327 public void run() {
4328 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004329 // Result object to be returned
4330 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004331 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004332 res.uid = -1;
4333 res.pkg = null;
4334 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004335 args.doPreInstall(res.returnCode);
4336 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004337 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004338 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004339 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004340 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004342
4343 // A restore should be performed at this point if (a) the install
4344 // succeeded, (b) the operation is not an update, and (c) the new
4345 // package has a backupAgent defined.
4346 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004347 boolean doRestore = (!update
4348 && res.pkg != null
4349 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004350
4351 // Set up the post-install work request bookkeeping. This will be used
4352 // and cleaned up by the post-install event handling regardless of whether
4353 // there's a restore pass performed. Token values are >= 1.
4354 int token;
4355 if (mNextInstallToken < 0) mNextInstallToken = 1;
4356 token = mNextInstallToken++;
4357
4358 PostInstallData data = new PostInstallData(args, res);
4359 mRunningInstalls.put(token, data);
4360 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4361
4362 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4363 // Pass responsibility to the Backup Manager. It will perform a
4364 // restore if appropriate, then pass responsibility back to the
4365 // Package Manager to run the post-install observer callbacks
4366 // and broadcasts.
4367 IBackupManager bm = IBackupManager.Stub.asInterface(
4368 ServiceManager.getService(Context.BACKUP_SERVICE));
4369 if (bm != null) {
4370 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4371 + " to BM for possible restore");
4372 try {
4373 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4374 } catch (RemoteException e) {
4375 // can't happen; the backup manager is local
4376 } catch (Exception e) {
4377 Log.e(TAG, "Exception trying to enqueue restore", e);
4378 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004379 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004380 } else {
4381 Log.e(TAG, "Backup Manager not found!");
4382 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004384 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004385
4386 if (!doRestore) {
4387 // No restore possible, or the Backup Manager was mysteriously not
4388 // available -- just fire the post-install work request directly.
4389 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4390 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4391 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 }
4394 });
4395 }
4396
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004397 interface HandlerParams {
4398 void handleStartCopy(IMediaContainerService imcs);
4399 void handleServiceError();
4400 }
4401
4402 class InstallParams implements HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004403 final IPackageInstallObserver observer;
4404 int flags;
4405 final Uri packageURI;
4406 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004407 private InstallArgs mArgs;
4408 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004409 InstallParams(Uri packageURI,
4410 IPackageInstallObserver observer, int flags,
4411 String installerPackageName) {
4412 this.packageURI = packageURI;
4413 this.flags = flags;
4414 this.observer = observer;
4415 this.installerPackageName = installerPackageName;
4416 }
4417
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004418 private int getInstallLocation(IMediaContainerService imcs) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004419 try {
4420 return imcs.getRecommendedInstallLocation(packageURI);
4421 } catch (RemoteException e) {
4422 }
4423 return -1;
4424 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004425
4426 public void handleStartCopy(IMediaContainerService imcs) {
4427 int ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4428 if (imcs != null) {
4429 // Remote call to find out default install location
4430 int loc = getInstallLocation(imcs);
4431 // Use install location to create InstallArgs and temporary
4432 // install location
4433 if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
4434 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4435 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4436 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
4437 } else {
4438 if ((flags & PackageManager.INSTALL_EXTERNAL) == 0){
4439 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4440 // Set the flag to install on external media.
4441 flags |= PackageManager.INSTALL_EXTERNAL;
4442 } else {
4443 // Make sure the flag for installing on external
4444 // media is unset
4445 flags &= ~PackageManager.INSTALL_EXTERNAL;
4446 }
4447 }
4448 // Disable forward locked apps on sdcard.
4449 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0 &&
4450 (flags & PackageManager.INSTALL_EXTERNAL) != 0) {
4451 // Make sure forward locked apps can only be installed
4452 // on internal storage
4453 Log.w(TAG, "Cannot install protected apps on sdcard");
4454 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4455 } else {
4456 ret = PackageManager.INSTALL_SUCCEEDED;
4457 }
4458 }
4459 }
4460 // Create the file args now.
4461 mArgs = createInstallArgs(this);
4462 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4463 // Create copy only if we are not in an erroneous state.
4464 // Remote call to initiate copy using temporary file
4465 ret = mArgs.copyApk(imcs, true);
4466 }
4467 mRet = ret;
4468 mHandler.sendEmptyMessage(MCS_UNBIND);
4469 handleReturnCode();
4470 }
4471
4472 void handleReturnCode() {
4473 processPendingInstall(mArgs, mRet);
4474 }
4475
4476 public void handleServiceError() {
4477 mArgs = createInstallArgs(this);
4478 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4479 handleReturnCode();
4480 }
4481 };
4482
4483 /*
4484 * Utility class used in movePackage api.
4485 * srcArgs and targetArgs are not set for invalid flags and make
4486 * sure to do null checks when invoking methods on them.
4487 * We probably want to return ErrorPrams for both failed installs
4488 * and moves.
4489 */
4490 class MoveParams implements HandlerParams {
4491 final IPackageMoveObserver observer;
4492 final int flags;
4493 final String packageName;
4494 final InstallArgs srcArgs;
4495 final InstallArgs targetArgs;
4496 int mRet;
4497 MoveParams(InstallArgs srcArgs,
4498 IPackageMoveObserver observer,
4499 int flags, String packageName) {
4500 this.srcArgs = srcArgs;
4501 this.observer = observer;
4502 this.flags = flags;
4503 this.packageName = packageName;
4504 if (srcArgs != null) {
4505 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4506 targetArgs = createInstallArgs(packageUri, flags, packageName);
4507 } else {
4508 targetArgs = null;
4509 }
4510 }
4511
4512 public void handleStartCopy(IMediaContainerService imcs) {
4513 // Create the file args now.
4514 mRet = targetArgs.copyApk(imcs, false);
4515 targetArgs.doPreInstall(mRet);
4516 mHandler.sendEmptyMessage(MCS_UNBIND);
4517 handleReturnCode();
4518 }
4519
4520 void handleReturnCode() {
4521 targetArgs.doPostInstall(mRet);
4522 // TODO invoke pending move
4523 processPendingMove(this, mRet);
4524 }
4525
4526 public void handleServiceError() {
4527 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4528 handleReturnCode();
4529 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004530 };
4531
4532 private InstallArgs createInstallArgs(InstallParams params) {
4533 if (installOnSd(params.flags)) {
4534 return new SdInstallArgs(params);
4535 } else {
4536 return new FileInstallArgs(params);
4537 }
4538 }
4539
4540 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4541 if (installOnSd(flags)) {
4542 return new SdInstallArgs(fullCodePath, fullResourcePath);
4543 } else {
4544 return new FileInstallArgs(fullCodePath, fullResourcePath);
4545 }
4546 }
4547
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004548 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4549 if (installOnSd(flags)) {
4550 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4551 return new SdInstallArgs(packageURI, cid);
4552 } else {
4553 return new FileInstallArgs(packageURI, pkgName);
4554 }
4555 }
4556
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004557 static abstract class InstallArgs {
4558 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004559 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004560 final int flags;
4561 final Uri packageURI;
4562 final String installerPackageName;
4563
4564 InstallArgs(Uri packageURI,
4565 IPackageInstallObserver observer, int flags,
4566 String installerPackageName) {
4567 this.packageURI = packageURI;
4568 this.flags = flags;
4569 this.observer = observer;
4570 this.installerPackageName = installerPackageName;
4571 }
4572
4573 abstract void createCopyFile();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004574 abstract int copyApk(IMediaContainerService imcs, boolean temp);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004575 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004576 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004577 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004578 abstract String getCodePath();
4579 abstract String getResourcePath();
4580 // Need installer lock especially for dex file removal.
4581 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004582 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004583 }
4584
4585 class FileInstallArgs extends InstallArgs {
4586 File installDir;
4587 String codeFileName;
4588 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004589 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004590
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004591 FileInstallArgs(InstallParams params) {
4592 super(params.packageURI, params.observer,
4593 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004594 }
4595
4596 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4597 super(null, null, 0, null);
4598 File codeFile = new File(fullCodePath);
4599 installDir = codeFile.getParentFile();
4600 codeFileName = fullCodePath;
4601 resourceFileName = fullResourcePath;
4602 }
4603
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004604 FileInstallArgs(Uri packageURI, String pkgName) {
4605 super(packageURI, null, 0, null);
4606 boolean fwdLocked = isFwdLocked(flags);
4607 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4608 String apkName = getNextCodePath(null, pkgName, ".apk");
4609 codeFileName = new File(installDir, apkName + ".apk").getPath();
4610 resourceFileName = getResourcePathFromCodePath();
4611 }
4612
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004613 String getCodePath() {
4614 return codeFileName;
4615 }
4616
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004617 void createCopyFile() {
4618 boolean fwdLocked = isFwdLocked(flags);
4619 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4620 codeFileName = createTempPackageFile(installDir).getPath();
4621 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004622 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004623 }
4624
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004625 int copyApk(IMediaContainerService imcs, boolean temp) {
4626 if (temp) {
4627 // Generate temp file name
4628 createCopyFile();
4629 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004630 // Get a ParcelFileDescriptor to write to the output file
4631 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004632 if (!created) {
4633 try {
4634 codeFile.createNewFile();
4635 // Set permissions
4636 if (!setPermissions()) {
4637 // Failed setting permissions.
4638 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4639 }
4640 } catch (IOException e) {
4641 Log.w(TAG, "Failed to create file " + codeFile);
4642 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4643 }
4644 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004645 ParcelFileDescriptor out = null;
4646 try {
4647 out = ParcelFileDescriptor.open(codeFile,
4648 ParcelFileDescriptor.MODE_READ_WRITE);
4649 } catch (FileNotFoundException e) {
4650 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4651 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4652 }
4653 // Copy the resource now
4654 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4655 try {
4656 if (imcs.copyResource(packageURI, out)) {
4657 ret = PackageManager.INSTALL_SUCCEEDED;
4658 }
4659 } catch (RemoteException e) {
4660 } finally {
4661 try { if (out != null) out.close(); } catch (IOException e) {}
4662 }
4663 return ret;
4664 }
4665
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004666 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004667 if (status != PackageManager.INSTALL_SUCCEEDED) {
4668 cleanUp();
4669 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004670 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004671 }
4672
4673 boolean doRename(int status, final String pkgName, String oldCodePath) {
4674 if (status != PackageManager.INSTALL_SUCCEEDED) {
4675 cleanUp();
4676 return false;
4677 } else {
4678 // Rename based on packageName
4679 File codeFile = new File(getCodePath());
4680 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4681 File desFile = new File(installDir, apkName + ".apk");
4682 if (!codeFile.renameTo(desFile)) {
4683 return false;
4684 }
4685 // Reset paths since the file has been renamed.
4686 codeFileName = desFile.getPath();
4687 resourceFileName = getResourcePathFromCodePath();
4688 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004689 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004690 // Failed setting permissions.
4691 return false;
4692 }
4693 return true;
4694 }
4695 }
4696
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004697 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004698 if (status != PackageManager.INSTALL_SUCCEEDED) {
4699 cleanUp();
4700 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004701 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004702 }
4703
4704 String getResourcePath() {
4705 return resourceFileName;
4706 }
4707
4708 String getResourcePathFromCodePath() {
4709 String codePath = getCodePath();
4710 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4711 String apkNameOnly = getApkName(codePath);
4712 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4713 } else {
4714 return codePath;
4715 }
4716 }
4717
4718 private boolean cleanUp() {
4719 boolean ret = true;
4720 String sourceDir = getCodePath();
4721 String publicSourceDir = getResourcePath();
4722 if (sourceDir != null) {
4723 File sourceFile = new File(sourceDir);
4724 if (!sourceFile.exists()) {
4725 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4726 ret = false;
4727 }
4728 // Delete application's code and resources
4729 sourceFile.delete();
4730 }
4731 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4732 final File publicSourceFile = new File(publicSourceDir);
4733 if (!publicSourceFile.exists()) {
4734 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4735 }
4736 if (publicSourceFile.exists()) {
4737 publicSourceFile.delete();
4738 }
4739 }
4740 return ret;
4741 }
4742
4743 void cleanUpResourcesLI() {
4744 String sourceDir = getCodePath();
4745 if (cleanUp() && mInstaller != null) {
4746 int retCode = mInstaller.rmdex(sourceDir);
4747 if (retCode < 0) {
4748 Log.w(TAG, "Couldn't remove dex file for package: "
4749 + " at location "
4750 + sourceDir + ", retcode=" + retCode);
4751 // we don't consider this to be a failure of the core package deletion
4752 }
4753 }
4754 }
4755
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004756 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004757 // TODO Do this in a more elegant way later on. for now just a hack
4758 if (!isFwdLocked(flags)) {
4759 final int filePermissions =
4760 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4761 |FileUtils.S_IROTH;
4762 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4763 if (retCode != 0) {
4764 Log.e(TAG, "Couldn't set new package file permissions for " +
4765 getCodePath()
4766 + ". The return code was: " + retCode);
4767 // TODO Define new internal error
4768 return false;
4769 }
4770 return true;
4771 }
4772 return true;
4773 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004774
4775 boolean doPostDeleteLI(boolean delete) {
4776 cleanUpResourcesLI();
4777 return true;
4778 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004779 }
4780
4781 class SdInstallArgs extends InstallArgs {
4782 String cid;
4783 String cachePath;
4784 static final String RES_FILE_NAME = "pkg.apk";
4785
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004786 SdInstallArgs(InstallParams params) {
4787 super(params.packageURI, params.observer,
4788 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004789 }
4790
4791 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004792 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004793 // Extract cid from fullCodePath
4794 int eidx = fullCodePath.lastIndexOf("/");
4795 String subStr1 = fullCodePath.substring(0, eidx);
4796 int sidx = subStr1.lastIndexOf("/");
4797 cid = subStr1.substring(sidx+1, eidx);
4798 cachePath = subStr1;
4799 }
4800
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004801 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004802 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
4803 this.cid = cid;
4804 }
4805
4806 SdInstallArgs(Uri packageURI, String cid) {
4807 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004808 this.cid = cid;
4809 }
4810
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004811 void createCopyFile() {
4812 cid = getTempContainerId();
4813 }
4814
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004815 int copyApk(IMediaContainerService imcs, boolean temp) {
4816 if (temp) {
4817 createCopyFile();
4818 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004819 try {
4820 cachePath = imcs.copyResourceToContainer(
4821 packageURI, cid,
4822 getEncryptKey(), RES_FILE_NAME);
4823 } catch (RemoteException e) {
4824 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004825 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4826 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004827 }
4828
4829 @Override
4830 String getCodePath() {
4831 return cachePath + "/" + RES_FILE_NAME;
4832 }
4833
4834 @Override
4835 String getResourcePath() {
4836 return cachePath + "/" + RES_FILE_NAME;
4837 }
4838
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004839 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004840 if (status != PackageManager.INSTALL_SUCCEEDED) {
4841 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004842 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004843 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004844 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004845 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004846 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004847 if (cachePath == null) {
4848 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4849 }
4850 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004851 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004852 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004853 }
4854
4855 boolean doRename(int status, final String pkgName,
4856 String oldCodePath) {
4857 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004858 String newCachePath = null;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004859 final int RENAME_FAILED = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004860 final int MOUNT_FAILED = 2;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004861 final int PASS = 4;
4862 int errCode = RENAME_FAILED;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004863 String errMsg = "RENAME_FAILED";
4864 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004865 if (mounted) {
4866 // Unmount the container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004867 if (!PackageHelper.unMountSdDir(cid)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004868 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
4869 return false;
4870 }
4871 mounted = false;
4872 }
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004873 if (PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004874 errCode = MOUNT_FAILED;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004875 errMsg = "MOUNT_FAILED";
4876 if ((newCachePath = PackageHelper.mountSdDir(newCacheId,
4877 getEncryptKey(), Process.SYSTEM_UID)) != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004878 errCode = PASS;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004879 errMsg = "PASS";
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004880 }
4881 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004882 if (errCode != PASS) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004883 Log.i(TAG, "Failed to rename " + cid + " to " + newCacheId +
4884 " at path: " + cachePath + " to new path: " + newCachePath +
4885 "err = " + errMsg);
4886 // Mount old container?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004887 return false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004888 } else {
4889 Log.i(TAG, "Succesfully renamed " + cid + " to " + newCacheId +
4890 " at path: " + cachePath + " to new path: " + newCachePath);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004891 }
4892 cid = newCacheId;
4893 cachePath = newCachePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004894 return true;
4895 }
4896
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004897 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004898 if (status != PackageManager.INSTALL_SUCCEEDED) {
4899 cleanUp();
4900 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004901 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004902 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004903 PackageHelper.mountSdDir(cid,
4904 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004905 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004906 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004907 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004908 }
4909
4910 private void cleanUp() {
4911 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004912 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004913 }
4914
4915 void cleanUpResourcesLI() {
4916 String sourceFile = getCodePath();
4917 // Remove dex file
4918 if (mInstaller != null) {
4919 int retCode = mInstaller.rmdex(sourceFile.toString());
4920 if (retCode < 0) {
4921 Log.w(TAG, "Couldn't remove dex file for package: "
4922 + " at location "
4923 + sourceFile.toString() + ", retcode=" + retCode);
4924 // we don't consider this to be a failure of the core package deletion
4925 }
4926 }
4927 cleanUp();
4928 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004929
4930 boolean matchContainer(String app) {
4931 if (cid.startsWith(app)) {
4932 return true;
4933 }
4934 return false;
4935 }
4936
4937 String getPackageName() {
4938 int idx = cid.lastIndexOf("-");
4939 if (idx == -1) {
4940 return cid;
4941 }
4942 return cid.substring(0, idx);
4943 }
4944
4945 boolean doPostDeleteLI(boolean delete) {
4946 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004947 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004948 if (mounted) {
4949 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004950 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004951 }
4952 if (ret && delete) {
4953 cleanUpResourcesLI();
4954 }
4955 return ret;
4956 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004957 };
4958
4959 // Utility method used to create code paths based on package name and available index.
4960 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4961 String idxStr = "";
4962 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004963 // Fall back to default value of idx=1 if prefix is not
4964 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004965 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004966 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004967 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004968 if (subStr.endsWith(suffix)) {
4969 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004970 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004971 // If oldCodePath already contains prefix find out the
4972 // ending index to either increment or decrement.
4973 int sidx = subStr.lastIndexOf(prefix);
4974 if (sidx != -1) {
4975 subStr = subStr.substring(sidx + prefix.length());
4976 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004977 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
4978 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004979 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004980 try {
4981 idx = Integer.parseInt(subStr);
4982 if (idx <= 1) {
4983 idx++;
4984 } else {
4985 idx--;
4986 }
4987 } catch(NumberFormatException e) {
4988 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004989 }
4990 }
4991 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004992 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004993 return prefix + idxStr;
4994 }
4995
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004996 // Utility method used to ignore ADD/REMOVE events
4997 // by directory observer.
4998 private static boolean ignoreCodePath(String fullPathStr) {
4999 String apkName = getApkName(fullPathStr);
5000 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5001 if (idx != -1 && ((idx+1) < apkName.length())) {
5002 // Make sure the package ends with a numeral
5003 String version = apkName.substring(idx+1);
5004 try {
5005 Integer.parseInt(version);
5006 return true;
5007 } catch (NumberFormatException e) {}
5008 }
5009 return false;
5010 }
5011
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005012 // Utility method that returns the relative package path with respect
5013 // to the installation directory. Like say for /data/data/com.test-1.apk
5014 // string com.test-1 is returned.
5015 static String getApkName(String codePath) {
5016 if (codePath == null) {
5017 return null;
5018 }
5019 int sidx = codePath.lastIndexOf("/");
5020 int eidx = codePath.lastIndexOf(".");
5021 if (eidx == -1) {
5022 eidx = codePath.length();
5023 } else if (eidx == 0) {
5024 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
5025 return null;
5026 }
5027 return codePath.substring(sidx+1, eidx);
5028 }
5029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005030 class PackageInstalledInfo {
5031 String name;
5032 int uid;
5033 PackageParser.Package pkg;
5034 int returnCode;
5035 PackageRemovedInfo removedInfo;
5036 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 /*
5039 * Install a non-existing package.
5040 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005041 private void installNewPackageLI(PackageParser.Package pkg,
5042 int parseFlags,
5043 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005044 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005045 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08005046 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005047 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005048
5049 if (useEncryptedFilesystemForPackage(pkg)) {
5050 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
5051 } else {
5052 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
5053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005054 res.name = pkgName;
5055 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005056 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005058 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 + " without first uninstalling.");
5060 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5061 return;
5062 }
5063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005065 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005066 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005067 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005068 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5069 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5070 }
5071 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005072 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005073 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 res);
5075 // delete the partially installed application. the data directory will have to be
5076 // restored if it was already existing
5077 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5078 // remove package from internal structures. Note that we want deletePackageX to
5079 // delete the package data and cache directories that it created in
5080 // scanPackageLocked, unless those directories existed before we even tried to
5081 // install.
5082 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005083 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5085 res.removedInfo);
5086 }
5087 }
5088 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005089
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005090 private void replacePackageLI(PackageParser.Package pkg,
5091 int parseFlags,
5092 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005093 String installerPackageName, PackageInstalledInfo res) {
5094
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005095 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005096 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 // First find the old package info and check signatures
5098 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005099 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005100 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005101 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005102 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5103 return;
5104 }
5105 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005106 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005107 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005108 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005110 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 }
5112 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005115 PackageParser.Package pkg,
5116 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005117 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 PackageParser.Package newPackage = null;
5119 String pkgName = deletedPackage.packageName;
5120 boolean deletedPkg = true;
5121 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005122
Jacek Surazski65e13172009-04-28 15:26:38 +02005123 String oldInstallerPackageName = null;
5124 synchronized (mPackages) {
5125 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5126 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005127
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005128 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005130 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005131 res.removedInfo)) {
5132 // If the existing package was'nt successfully deleted
5133 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5134 deletedPkg = false;
5135 } else {
5136 // Successfully deleted the old package. Now proceed with re-installation
5137 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005138 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005140 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005141 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5142 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005143 }
5144 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005145 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005146 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005147 res);
5148 updatedSettings = true;
5149 }
5150 }
5151
5152 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5153 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005154 // were keeping around in case we needed them (see below) can now be deleted.
5155 // This info will be set on the res.removedInfo to clean up later on as post
5156 // install action.
5157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005158 //update signature on the new package setting
5159 //this should always succeed, since we checked the
5160 //signature earlier.
5161 synchronized(mPackages) {
5162 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5163 parseFlags, true);
5164 }
5165 } else {
5166 // remove package from internal structures. Note that we want deletePackageX to
5167 // delete the package data and cache directories that it created in
5168 // scanPackageLocked, unless those directories existed before we even tried to
5169 // install.
5170 if(updatedSettings) {
5171 deletePackageLI(
5172 pkgName, true,
5173 PackageManager.DONT_DELETE_DATA,
5174 res.removedInfo);
5175 }
5176 // Since we failed to install the new package we need to restore the old
5177 // package that we deleted.
5178 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005179 File restoreFile = new File(deletedPackage.mPath);
5180 if (restoreFile == null) {
5181 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
5182 return;
5183 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005184 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5185 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005186 // Parse old package
5187 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5188 scanPackageLI(restoreFile, parseFlags, scanMode);
5189 synchronized (mPackages) {
5190 grantPermissionsLP(deletedPackage, false);
5191 mSettings.writeLP();
5192 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005193 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5194 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
5195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 }
5197 }
5198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005201 PackageParser.Package pkg,
5202 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005203 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005204 PackageParser.Package newPackage = null;
5205 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005206 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005207 PackageParser.PARSE_IS_SYSTEM;
5208 String packageName = deletedPackage.packageName;
5209 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5210 if (packageName == null) {
5211 Log.w(TAG, "Attempt to delete null packageName.");
5212 return;
5213 }
5214 PackageParser.Package oldPkg;
5215 PackageSetting oldPkgSetting;
5216 synchronized (mPackages) {
5217 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005218 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5220 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005221 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 return;
5223 }
5224 }
5225 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5226 res.removedInfo.removedPackage = packageName;
5227 // Remove existing system package
5228 removePackageLI(oldPkg, true);
5229 synchronized (mPackages) {
5230 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5231 }
5232
5233 // Successfully disabled the old package. Now proceed with re-installation
5234 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5235 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005236 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005238 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005239 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5240 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5241 }
5242 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005243 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 updatedSettings = true;
5245 }
5246
5247 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5248 //update signature on the new package setting
5249 //this should always succeed, since we checked the
5250 //signature earlier.
5251 synchronized(mPackages) {
5252 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5253 parseFlags, true);
5254 }
5255 } else {
5256 // Re installation failed. Restore old information
5257 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005258 if (newPackage != null) {
5259 removePackageLI(newPackage, true);
5260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005261 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005262 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005264 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005265 // Restore the old system information in Settings
5266 synchronized(mPackages) {
5267 if(updatedSettings) {
5268 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005269 mSettings.setInstallerPackageName(packageName,
5270 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005271 }
5272 mSettings.writeLP();
5273 }
5274 }
5275 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005276
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005277 // Utility method used to move dex files during install.
5278 private int moveDexFiles(PackageParser.Package newPackage) {
5279 int retCode;
5280 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5281 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5282 if (retCode != 0) {
5283 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5284 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5285 }
5286 }
5287 return PackageManager.INSTALL_SUCCEEDED;
5288 }
5289
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005290 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005291 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005292 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005293 synchronized (mPackages) {
5294 //write settings. the installStatus will be incomplete at this stage.
5295 //note that the new package setting would have already been
5296 //added to mPackages. It hasn't been persisted yet.
5297 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5298 mSettings.writeLP();
5299 }
5300
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005301 if ((res.returnCode = moveDexFiles(newPackage))
5302 != PackageManager.INSTALL_SUCCEEDED) {
5303 // Discontinue if moving dex files failed.
5304 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005305 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005306 if((res.returnCode = setPermissionsLI(newPackage))
5307 != PackageManager.INSTALL_SUCCEEDED) {
5308 if (mInstaller != null) {
5309 mInstaller.rmdex(newPackage.mScanPath);
5310 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005311 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005313 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315 synchronized (mPackages) {
5316 grantPermissionsLP(newPackage, true);
5317 res.name = pkgName;
5318 res.uid = newPackage.applicationInfo.uid;
5319 res.pkg = newPackage;
5320 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005321 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5323 //to update install status
5324 mSettings.writeLP();
5325 }
5326 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005327
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005328 private void installPackageLI(InstallArgs args,
5329 boolean newInstall, PackageInstalledInfo res) {
5330 int pFlags = args.flags;
5331 String installerPackageName = args.installerPackageName;
5332 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005333 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005334 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005335 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005336 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5337 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005338 // Result object to be returned
5339 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5340
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005341 // Retrieve PackageSettings and parse package
5342 int parseFlags = PackageParser.PARSE_CHATTY |
5343 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5344 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5345 parseFlags |= mDefParseFlags;
5346 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5347 pp.setSeparateProcesses(mSeparateProcesses);
5348 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5349 null, mMetrics, parseFlags);
5350 if (pkg == null) {
5351 res.returnCode = pp.getParseError();
5352 return;
5353 }
5354 String pkgName = res.name = pkg.packageName;
5355 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5356 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5357 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5358 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005359 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005360 }
5361 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5362 res.returnCode = pp.getParseError();
5363 return;
5364 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005365 // Get rid of all references to package scan path via parser.
5366 pp = null;
5367 String oldCodePath = null;
5368 boolean systemApp = false;
5369 synchronized (mPackages) {
5370 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005371 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5372 String oldName = mSettings.mRenamedPackages.get(pkgName);
5373 if (oldName != null && oldName.equals(pkg.mOriginalPackage)
5374 && mPackages.containsKey(oldName)) {
5375 // This package is derived from an original package,
5376 // and this device has been updating from that original
5377 // name. We must continue using the original name, so
5378 // rename the new package here.
5379 pkg.setPackageName(pkg.mOriginalPackage);
5380 pkgName = pkg.packageName;
5381 replace = true;
5382 } else if (mPackages.containsKey(pkgName)) {
5383 // This package, under its official name, already exists
5384 // on the device; we should replace it.
5385 replace = true;
5386 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005387 }
5388 PackageSetting ps = mSettings.mPackages.get(pkgName);
5389 if (ps != null) {
5390 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5391 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5392 systemApp = (ps.pkg.applicationInfo.flags &
5393 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005394 }
5395 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005396 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005397
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005398 if (systemApp && onSd) {
5399 // Disable updates to system apps on sdcard
5400 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5401 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5402 return;
5403 }
5404 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5405 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5406 return;
5407 }
5408 // Set application objects path explicitly after the rename
5409 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005410 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005411 replacePackageLI(pkg, parseFlags, scanMode,
5412 installerPackageName, res);
5413 } else {
5414 installNewPackageLI(pkg, parseFlags, scanMode,
5415 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005416 }
5417 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005418
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005419 private int setPermissionsLI(PackageParser.Package newPackage) {
5420 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005421 int retCode = 0;
5422 // TODO Gross hack but fix later. Ideally move this to be a post installation
5423 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005424 if ((newPackage.applicationInfo.flags
5425 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5426 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427 try {
5428 extractPublicFiles(newPackage, destResourceFile);
5429 } catch (IOException e) {
5430 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5431 " forward-locked app.");
5432 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5433 } finally {
5434 //TODO clean up the extracted public files
5435 }
5436 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005437 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 newPackage.applicationInfo.uid);
5439 } else {
5440 final int filePermissions =
5441 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005442 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 newPackage.applicationInfo.uid);
5444 }
5445 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005446 // The permissions on the resource file was set when it was copied for
5447 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005451 Log.e(TAG, "Couldn't set new package file permissions for " +
5452 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005454 // TODO Define new internal error
5455 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456 }
5457 return PackageManager.INSTALL_SUCCEEDED;
5458 }
5459
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005460 private boolean isForwardLocked(PackageParser.Package pkg) {
5461 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462 }
5463
5464 private void extractPublicFiles(PackageParser.Package newPackage,
5465 File publicZipFile) throws IOException {
5466 final ZipOutputStream publicZipOutStream =
5467 new ZipOutputStream(new FileOutputStream(publicZipFile));
5468 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5469
5470 // Copy manifest, resources.arsc and res directory to public zip
5471
5472 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5473 while (privateZipEntries.hasMoreElements()) {
5474 final ZipEntry zipEntry = privateZipEntries.nextElement();
5475 final String zipEntryName = zipEntry.getName();
5476 if ("AndroidManifest.xml".equals(zipEntryName)
5477 || "resources.arsc".equals(zipEntryName)
5478 || zipEntryName.startsWith("res/")) {
5479 try {
5480 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5481 } catch (IOException e) {
5482 try {
5483 publicZipOutStream.close();
5484 throw e;
5485 } finally {
5486 publicZipFile.delete();
5487 }
5488 }
5489 }
5490 }
5491
5492 publicZipOutStream.close();
5493 FileUtils.setPermissions(
5494 publicZipFile.getAbsolutePath(),
5495 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5496 -1, -1);
5497 }
5498
5499 private static void copyZipEntry(ZipEntry zipEntry,
5500 ZipFile inZipFile,
5501 ZipOutputStream outZipStream) throws IOException {
5502 byte[] buffer = new byte[4096];
5503 int num;
5504
5505 ZipEntry newEntry;
5506 if (zipEntry.getMethod() == ZipEntry.STORED) {
5507 // Preserve the STORED method of the input entry.
5508 newEntry = new ZipEntry(zipEntry);
5509 } else {
5510 // Create a new entry so that the compressed len is recomputed.
5511 newEntry = new ZipEntry(zipEntry.getName());
5512 }
5513 outZipStream.putNextEntry(newEntry);
5514
5515 InputStream data = inZipFile.getInputStream(zipEntry);
5516 while ((num = data.read(buffer)) > 0) {
5517 outZipStream.write(buffer, 0, num);
5518 }
5519 outZipStream.flush();
5520 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 private void deleteTempPackageFiles() {
5523 FilenameFilter filter = new FilenameFilter() {
5524 public boolean accept(File dir, String name) {
5525 return name.startsWith("vmdl") && name.endsWith(".tmp");
5526 }
5527 };
5528 String tmpFilesList[] = mAppInstallDir.list(filter);
5529 if(tmpFilesList == null) {
5530 return;
5531 }
5532 for(int i = 0; i < tmpFilesList.length; i++) {
5533 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5534 tmpFile.delete();
5535 }
5536 }
5537
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005538 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 File tmpPackageFile;
5540 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005541 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 } catch (IOException e) {
5543 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5544 return null;
5545 }
5546 try {
5547 FileUtils.setPermissions(
5548 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5549 -1, -1);
5550 } catch (IOException e) {
5551 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5552 return null;
5553 }
5554 return tmpPackageFile;
5555 }
5556
5557 public void deletePackage(final String packageName,
5558 final IPackageDeleteObserver observer,
5559 final int flags) {
5560 mContext.enforceCallingOrSelfPermission(
5561 android.Manifest.permission.DELETE_PACKAGES, null);
5562 // Queue up an async operation since the package deletion may take a little while.
5563 mHandler.post(new Runnable() {
5564 public void run() {
5565 mHandler.removeCallbacks(this);
5566 final boolean succeded = deletePackageX(packageName, true, true, flags);
5567 if (observer != null) {
5568 try {
5569 observer.packageDeleted(succeded);
5570 } catch (RemoteException e) {
5571 Log.i(TAG, "Observer no longer exists.");
5572 } //end catch
5573 } //end if
5574 } //end run
5575 });
5576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005578 /**
5579 * This method is an internal method that could be get invoked either
5580 * to delete an installed package or to clean up a failed installation.
5581 * After deleting an installed package, a broadcast is sent to notify any
5582 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005583 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584 * installation wouldn't have sent the initial broadcast either
5585 * The key steps in deleting a package are
5586 * deleting the package information in internal structures like mPackages,
5587 * deleting the packages base directories through installd
5588 * updating mSettings to reflect current status
5589 * persisting settings for later use
5590 * sending a broadcast if necessary
5591 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5593 boolean deleteCodeAndResources, int flags) {
5594 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005595 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596
5597 synchronized (mInstallLock) {
5598 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5599 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005602 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5603 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5604
5605 // If the removed package was a system update, the old system packaged
5606 // was re-enabled; we need to broadcast this information
5607 if (systemUpdate) {
5608 Bundle extras = new Bundle(1);
5609 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5610 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5611
5612 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5613 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005616 // Delete the resources here after sending the broadcast to let
5617 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005618 if (info.args != null) {
5619 synchronized (mInstallLock) {
5620 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005621 }
5622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 return res;
5624 }
5625
5626 static class PackageRemovedInfo {
5627 String removedPackage;
5628 int uid = -1;
5629 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005630 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005631 // Clean up resources deleted packages.
5632 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 void sendBroadcast(boolean fullRemove, boolean replacing) {
5635 Bundle extras = new Bundle(1);
5636 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5637 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5638 if (replacing) {
5639 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5640 }
5641 if (removedPackage != null) {
5642 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5643 }
5644 if (removedUid >= 0) {
5645 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5646 }
5647 }
5648 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 /*
5651 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5652 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005653 * 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 -08005654 * delete a partially installed application.
5655 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005656 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 int flags) {
5658 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005659 if (outInfo != null) {
5660 outInfo.removedPackage = packageName;
5661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 removePackageLI(p, true);
5663 // Retrieve object to delete permissions for shared user later on
5664 PackageSetting deletedPs;
5665 synchronized (mPackages) {
5666 deletedPs = mSettings.mPackages.get(packageName);
5667 }
5668 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005669 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005671 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 if (retCode < 0) {
5673 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5674 + packageName + ", retcode=" + retCode);
5675 // we don't consider this to be a failure of the core package deletion
5676 }
5677 } else {
5678 //for emulator
5679 PackageParser.Package pkg = mPackages.get(packageName);
5680 File dataDir = new File(pkg.applicationInfo.dataDir);
5681 dataDir.delete();
5682 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005683 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005685 if (outInfo != null) {
5686 outInfo.removedUid = mSettings.removePackageLP(packageName);
5687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 }
5689 }
5690 synchronized (mPackages) {
5691 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5692 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005693 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 }
5695 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005696 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 }
5698 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700 /*
5701 * Tries to delete system package.
5702 */
5703 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005704 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 ApplicationInfo applicationInfo = p.applicationInfo;
5706 //applicable for non-partially installed applications only
5707 if (applicationInfo == null) {
5708 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5709 return false;
5710 }
5711 PackageSetting ps = null;
5712 // Confirm if the system package has been updated
5713 // An updated system app can be deleted. This will also have to restore
5714 // the system pkg from system partition
5715 synchronized (mPackages) {
5716 ps = mSettings.getDisabledSystemPkg(p.packageName);
5717 }
5718 if (ps == null) {
5719 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5720 return false;
5721 } else {
5722 Log.i(TAG, "Deleting system pkg from data partition");
5723 }
5724 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005725 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005726 boolean deleteCodeAndResources = false;
5727 if (ps.versionCode < p.mVersionCode) {
5728 // Delete code and resources for downgrades
5729 deleteCodeAndResources = true;
5730 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5731 flags &= ~PackageManager.DONT_DELETE_DATA;
5732 }
5733 } else {
5734 // Preserve data by setting flag
5735 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5736 flags |= PackageManager.DONT_DELETE_DATA;
5737 }
5738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5740 if (!ret) {
5741 return false;
5742 }
5743 synchronized (mPackages) {
5744 // Reinstate the old system package
5745 mSettings.enableSystemPackageLP(p.packageName);
5746 }
5747 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005748 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005750 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 if (newPkg == null) {
5753 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5754 return false;
5755 }
5756 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005757 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 mSettings.writeLP();
5759 }
5760 return true;
5761 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5764 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5765 ApplicationInfo applicationInfo = p.applicationInfo;
5766 if (applicationInfo == null) {
5767 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5768 return false;
5769 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005770 if (outInfo != null) {
5771 outInfo.uid = applicationInfo.uid;
5772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773
5774 // Delete package data from internal structures and also remove data if flag is set
5775 removePackageDataLI(p, outInfo, flags);
5776
5777 // Delete application code and resources
5778 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005779 // TODO can pick up from PackageSettings as well
5780 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005781 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005782 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5783 PackageManager.INSTALL_FORWARD_LOCK : 0;
5784 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005785 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 }
5787 return true;
5788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 /*
5791 * This method handles package deletion in general
5792 */
5793 private boolean deletePackageLI(String packageName,
5794 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5795 if (packageName == null) {
5796 Log.w(TAG, "Attempt to delete null packageName.");
5797 return false;
5798 }
5799 PackageParser.Package p;
5800 boolean dataOnly = false;
5801 synchronized (mPackages) {
5802 p = mPackages.get(packageName);
5803 if (p == null) {
5804 //this retrieves partially installed apps
5805 dataOnly = true;
5806 PackageSetting ps = mSettings.mPackages.get(packageName);
5807 if (ps == null) {
5808 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5809 return false;
5810 }
5811 p = ps.pkg;
5812 }
5813 }
5814 if (p == null) {
5815 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5816 return false;
5817 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 if (dataOnly) {
5820 // Delete application data first
5821 removePackageDataLI(p, outInfo, flags);
5822 return true;
5823 }
5824 // At this point the package should have ApplicationInfo associated with it
5825 if (p.applicationInfo == null) {
5826 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5827 return false;
5828 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005829 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005830 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5831 Log.i(TAG, "Removing system package:"+p.packageName);
5832 // When an updated system application is deleted we delete the existing resources as well and
5833 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005834 ret = deleteSystemPackageLI(p, flags, outInfo);
5835 } else {
5836 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005837 // Kill application pre-emptively especially for apps on sd.
5838 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005839 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005841 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 public void clearApplicationUserData(final String packageName,
5845 final IPackageDataObserver observer) {
5846 mContext.enforceCallingOrSelfPermission(
5847 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5848 // Queue up an async operation since the package deletion may take a little while.
5849 mHandler.post(new Runnable() {
5850 public void run() {
5851 mHandler.removeCallbacks(this);
5852 final boolean succeeded;
5853 synchronized (mInstallLock) {
5854 succeeded = clearApplicationUserDataLI(packageName);
5855 }
5856 if (succeeded) {
5857 // invoke DeviceStorageMonitor's update method to clear any notifications
5858 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5859 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5860 if (dsm != null) {
5861 dsm.updateMemory();
5862 }
5863 }
5864 if(observer != null) {
5865 try {
5866 observer.onRemoveCompleted(packageName, succeeded);
5867 } catch (RemoteException e) {
5868 Log.i(TAG, "Observer no longer exists.");
5869 }
5870 } //end if observer
5871 } //end run
5872 });
5873 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 private boolean clearApplicationUserDataLI(String packageName) {
5876 if (packageName == null) {
5877 Log.w(TAG, "Attempt to delete null packageName.");
5878 return false;
5879 }
5880 PackageParser.Package p;
5881 boolean dataOnly = false;
5882 synchronized (mPackages) {
5883 p = mPackages.get(packageName);
5884 if(p == null) {
5885 dataOnly = true;
5886 PackageSetting ps = mSettings.mPackages.get(packageName);
5887 if((ps == null) || (ps.pkg == null)) {
5888 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5889 return false;
5890 }
5891 p = ps.pkg;
5892 }
5893 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005894 boolean useEncryptedFSDir = false;
5895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005896 if(!dataOnly) {
5897 //need to check this only for fully installed applications
5898 if (p == null) {
5899 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5900 return false;
5901 }
5902 final ApplicationInfo applicationInfo = p.applicationInfo;
5903 if (applicationInfo == null) {
5904 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5905 return false;
5906 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005907 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005908 }
5909 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005910 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005911 if (retCode < 0) {
5912 Log.w(TAG, "Couldn't remove cache files for package: "
5913 + packageName);
5914 return false;
5915 }
5916 }
5917 return true;
5918 }
5919
5920 public void deleteApplicationCacheFiles(final String packageName,
5921 final IPackageDataObserver observer) {
5922 mContext.enforceCallingOrSelfPermission(
5923 android.Manifest.permission.DELETE_CACHE_FILES, null);
5924 // Queue up an async operation since the package deletion may take a little while.
5925 mHandler.post(new Runnable() {
5926 public void run() {
5927 mHandler.removeCallbacks(this);
5928 final boolean succeded;
5929 synchronized (mInstallLock) {
5930 succeded = deleteApplicationCacheFilesLI(packageName);
5931 }
5932 if(observer != null) {
5933 try {
5934 observer.onRemoveCompleted(packageName, succeded);
5935 } catch (RemoteException e) {
5936 Log.i(TAG, "Observer no longer exists.");
5937 }
5938 } //end if observer
5939 } //end run
5940 });
5941 }
5942
5943 private boolean deleteApplicationCacheFilesLI(String packageName) {
5944 if (packageName == null) {
5945 Log.w(TAG, "Attempt to delete null packageName.");
5946 return false;
5947 }
5948 PackageParser.Package p;
5949 synchronized (mPackages) {
5950 p = mPackages.get(packageName);
5951 }
5952 if (p == null) {
5953 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5954 return false;
5955 }
5956 final ApplicationInfo applicationInfo = p.applicationInfo;
5957 if (applicationInfo == null) {
5958 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5959 return false;
5960 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005961 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005963 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005964 if (retCode < 0) {
5965 Log.w(TAG, "Couldn't remove cache files for package: "
5966 + packageName);
5967 return false;
5968 }
5969 }
5970 return true;
5971 }
5972
5973 public void getPackageSizeInfo(final String packageName,
5974 final IPackageStatsObserver observer) {
5975 mContext.enforceCallingOrSelfPermission(
5976 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5977 // Queue up an async operation since the package deletion may take a little while.
5978 mHandler.post(new Runnable() {
5979 public void run() {
5980 mHandler.removeCallbacks(this);
5981 PackageStats lStats = new PackageStats(packageName);
5982 final boolean succeded;
5983 synchronized (mInstallLock) {
5984 succeded = getPackageSizeInfoLI(packageName, lStats);
5985 }
5986 if(observer != null) {
5987 try {
5988 observer.onGetStatsCompleted(lStats, succeded);
5989 } catch (RemoteException e) {
5990 Log.i(TAG, "Observer no longer exists.");
5991 }
5992 } //end if observer
5993 } //end run
5994 });
5995 }
5996
5997 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5998 if (packageName == null) {
5999 Log.w(TAG, "Attempt to get size of null packageName.");
6000 return false;
6001 }
6002 PackageParser.Package p;
6003 boolean dataOnly = false;
6004 synchronized (mPackages) {
6005 p = mPackages.get(packageName);
6006 if(p == null) {
6007 dataOnly = true;
6008 PackageSetting ps = mSettings.mPackages.get(packageName);
6009 if((ps == null) || (ps.pkg == null)) {
6010 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6011 return false;
6012 }
6013 p = ps.pkg;
6014 }
6015 }
6016 String publicSrcDir = null;
6017 if(!dataOnly) {
6018 final ApplicationInfo applicationInfo = p.applicationInfo;
6019 if (applicationInfo == null) {
6020 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6021 return false;
6022 }
6023 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6024 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006025 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 if (mInstaller != null) {
6027 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006028 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 if (res < 0) {
6030 return false;
6031 } else {
6032 return true;
6033 }
6034 }
6035 return true;
6036 }
6037
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 public void addPackageToPreferred(String packageName) {
6040 mContext.enforceCallingOrSelfPermission(
6041 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006042 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 }
6044
6045 public void removePackageFromPreferred(String packageName) {
6046 mContext.enforceCallingOrSelfPermission(
6047 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006048 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 }
6050
6051 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006052 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 }
6054
6055 public void addPreferredActivity(IntentFilter filter, int match,
6056 ComponentName[] set, ComponentName activity) {
6057 mContext.enforceCallingOrSelfPermission(
6058 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6059
6060 synchronized (mPackages) {
6061 Log.i(TAG, "Adding preferred activity " + activity + ":");
6062 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6063 mSettings.mPreferredActivities.addFilter(
6064 new PreferredActivity(filter, match, set, activity));
6065 mSettings.writeLP();
6066 }
6067 }
6068
Satish Sampath8dbe6122009-06-02 23:35:54 +01006069 public void replacePreferredActivity(IntentFilter filter, int match,
6070 ComponentName[] set, ComponentName activity) {
6071 mContext.enforceCallingOrSelfPermission(
6072 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6073 if (filter.countActions() != 1) {
6074 throw new IllegalArgumentException(
6075 "replacePreferredActivity expects filter to have only 1 action.");
6076 }
6077 if (filter.countCategories() != 1) {
6078 throw new IllegalArgumentException(
6079 "replacePreferredActivity expects filter to have only 1 category.");
6080 }
6081 if (filter.countDataAuthorities() != 0
6082 || filter.countDataPaths() != 0
6083 || filter.countDataSchemes() != 0
6084 || filter.countDataTypes() != 0) {
6085 throw new IllegalArgumentException(
6086 "replacePreferredActivity expects filter to have no data authorities, " +
6087 "paths, schemes or types.");
6088 }
6089 synchronized (mPackages) {
6090 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6091 String action = filter.getAction(0);
6092 String category = filter.getCategory(0);
6093 while (it.hasNext()) {
6094 PreferredActivity pa = it.next();
6095 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6096 it.remove();
6097 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6098 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6099 }
6100 }
6101 addPreferredActivity(filter, match, set, activity);
6102 }
6103 }
6104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 public void clearPackagePreferredActivities(String packageName) {
6106 mContext.enforceCallingOrSelfPermission(
6107 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6108
6109 synchronized (mPackages) {
6110 if (clearPackagePreferredActivitiesLP(packageName)) {
6111 mSettings.writeLP();
6112 }
6113 }
6114 }
6115
6116 boolean clearPackagePreferredActivitiesLP(String packageName) {
6117 boolean changed = false;
6118 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6119 while (it.hasNext()) {
6120 PreferredActivity pa = it.next();
6121 if (pa.mActivity.getPackageName().equals(packageName)) {
6122 it.remove();
6123 changed = true;
6124 }
6125 }
6126 return changed;
6127 }
6128
6129 public int getPreferredActivities(List<IntentFilter> outFilters,
6130 List<ComponentName> outActivities, String packageName) {
6131
6132 int num = 0;
6133 synchronized (mPackages) {
6134 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6135 while (it.hasNext()) {
6136 PreferredActivity pa = it.next();
6137 if (packageName == null
6138 || pa.mActivity.getPackageName().equals(packageName)) {
6139 if (outFilters != null) {
6140 outFilters.add(new IntentFilter(pa));
6141 }
6142 if (outActivities != null) {
6143 outActivities.add(pa.mActivity);
6144 }
6145 }
6146 }
6147 }
6148
6149 return num;
6150 }
6151
6152 public void setApplicationEnabledSetting(String appPackageName,
6153 int newState, int flags) {
6154 setEnabledSetting(appPackageName, null, newState, flags);
6155 }
6156
6157 public void setComponentEnabledSetting(ComponentName componentName,
6158 int newState, int flags) {
6159 setEnabledSetting(componentName.getPackageName(),
6160 componentName.getClassName(), newState, flags);
6161 }
6162
6163 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006164 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006165 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6166 || newState == COMPONENT_ENABLED_STATE_ENABLED
6167 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6168 throw new IllegalArgumentException("Invalid new component state: "
6169 + newState);
6170 }
6171 PackageSetting pkgSetting;
6172 final int uid = Binder.getCallingUid();
6173 final int permission = mContext.checkCallingPermission(
6174 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6175 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006176 boolean sendNow = false;
6177 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006178 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006180 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006182 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006184 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006186 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 }
6188 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006189 "Unknown component: " + packageName
6190 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 }
6192 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6193 throw new SecurityException(
6194 "Permission Denial: attempt to change component state from pid="
6195 + Binder.getCallingPid()
6196 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6197 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006198 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 // We're dealing with an application/package level state change
6200 pkgSetting.enabled = newState;
6201 } else {
6202 // We're dealing with a component level state change
6203 switch (newState) {
6204 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006205 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 break;
6207 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006208 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 break;
6210 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006211 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 break;
6213 default:
6214 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006215 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 }
6217 }
6218 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006219 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006220 components = mPendingBroadcasts.get(packageName);
6221 boolean newPackage = components == null;
6222 if (newPackage) {
6223 components = new ArrayList<String>();
6224 }
6225 if (!components.contains(componentName)) {
6226 components.add(componentName);
6227 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006228 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6229 sendNow = true;
6230 // Purge entry from pending broadcast list if another one exists already
6231 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006232 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006233 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006234 if (newPackage) {
6235 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006236 }
6237 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6238 // Schedule a message
6239 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6240 }
6241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 long callingId = Binder.clearCallingIdentity();
6245 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006246 if (sendNow) {
6247 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006248 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 } finally {
6251 Binder.restoreCallingIdentity(callingId);
6252 }
6253 }
6254
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006255 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006256 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6257 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6258 + " components=" + componentNames);
6259 Bundle extras = new Bundle(4);
6260 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6261 String nameList[] = new String[componentNames.size()];
6262 componentNames.toArray(nameList);
6263 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006264 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6265 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006266 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006267 }
6268
Jacek Surazski65e13172009-04-28 15:26:38 +02006269 public String getInstallerPackageName(String packageName) {
6270 synchronized (mPackages) {
6271 PackageSetting pkg = mSettings.mPackages.get(packageName);
6272 if (pkg == null) {
6273 throw new IllegalArgumentException("Unknown package: " + packageName);
6274 }
6275 return pkg.installerPackageName;
6276 }
6277 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 public int getApplicationEnabledSetting(String appPackageName) {
6280 synchronized (mPackages) {
6281 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6282 if (pkg == null) {
6283 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6284 }
6285 return pkg.enabled;
6286 }
6287 }
6288
6289 public int getComponentEnabledSetting(ComponentName componentName) {
6290 synchronized (mPackages) {
6291 final String packageNameStr = componentName.getPackageName();
6292 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6293 if (pkg == null) {
6294 throw new IllegalArgumentException("Unknown component: " + componentName);
6295 }
6296 final String classNameStr = componentName.getClassName();
6297 return pkg.currentEnabledStateLP(classNameStr);
6298 }
6299 }
6300
6301 public void enterSafeMode() {
6302 if (!mSystemReady) {
6303 mSafeMode = true;
6304 }
6305 }
6306
6307 public void systemReady() {
6308 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006309
6310 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006311 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006312 mContext.getContentResolver(),
6313 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006314 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006315 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006316 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 }
6319
6320 public boolean isSafeMode() {
6321 return mSafeMode;
6322 }
6323
6324 public boolean hasSystemUidErrors() {
6325 return mHasSystemUidErrors;
6326 }
6327
6328 static String arrayToString(int[] array) {
6329 StringBuffer buf = new StringBuffer(128);
6330 buf.append('[');
6331 if (array != null) {
6332 for (int i=0; i<array.length; i++) {
6333 if (i > 0) buf.append(", ");
6334 buf.append(array[i]);
6335 }
6336 }
6337 buf.append(']');
6338 return buf.toString();
6339 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 @Override
6342 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6343 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6344 != PackageManager.PERMISSION_GRANTED) {
6345 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6346 + Binder.getCallingPid()
6347 + ", uid=" + Binder.getCallingUid()
6348 + " without permission "
6349 + android.Manifest.permission.DUMP);
6350 return;
6351 }
6352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 synchronized (mPackages) {
6354 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006355 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 pw.println(" ");
6357 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006358 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 pw.println(" ");
6360 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006361 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 pw.println(" ");
6363 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006364 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 pw.println("Permissions:");
6367 {
6368 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006369 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6370 pw.print(Integer.toHexString(System.identityHashCode(p)));
6371 pw.println("):");
6372 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6373 pw.print(" uid="); pw.print(p.uid);
6374 pw.print(" gids="); pw.print(arrayToString(p.gids));
6375 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 }
6377 }
6378 pw.println(" ");
6379 pw.println("Packages:");
6380 {
6381 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006382 pw.print(" Package [");
6383 pw.print(ps.realName != null ? ps.realName : ps.name);
6384 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006385 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6386 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006387 if (ps.realName != null) {
6388 pw.print(" compat name="); pw.println(ps.name);
6389 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006390 pw.print(" userId="); pw.print(ps.userId);
6391 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6392 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6393 pw.print(" pkg="); pw.println(ps.pkg);
6394 pw.print(" codePath="); pw.println(ps.codePathString);
6395 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006397 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006398 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006399 pw.print(" supportsScreens=[");
6400 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006401 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006402 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006403 if (!first) pw.print(", ");
6404 first = false;
6405 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006406 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006407 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006408 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006409 if (!first) pw.print(", ");
6410 first = false;
6411 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006413 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006414 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006415 if (!first) pw.print(", ");
6416 first = false;
6417 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006418 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006419 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006420 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006421 if (!first) pw.print(", ");
6422 first = false;
6423 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006424 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006425 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006426 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6427 if (!first) pw.print(", ");
6428 first = false;
6429 pw.print("anyDensity");
6430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006432 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006433 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6434 pw.print(" signatures="); pw.println(ps.signatures);
6435 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6436 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6437 pw.print(" installStatus="); pw.print(ps.installStatus);
6438 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 if (ps.disabledComponents.size() > 0) {
6440 pw.println(" disabledComponents:");
6441 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006442 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 }
6444 }
6445 if (ps.enabledComponents.size() > 0) {
6446 pw.println(" enabledComponents:");
6447 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006448 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 }
6450 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006451 if (ps.grantedPermissions.size() > 0) {
6452 pw.println(" grantedPermissions:");
6453 for (String s : ps.grantedPermissions) {
6454 pw.print(" "); pw.println(s);
6455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006457 if (ps.loadedPermissions.size() > 0) {
6458 pw.println(" loadedPermissions:");
6459 for (String s : ps.loadedPermissions) {
6460 pw.print(" "); pw.println(s);
6461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 }
6463 }
6464 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006465 if (mSettings.mRenamedPackages.size() > 0) {
6466 pw.println(" ");
6467 pw.println("Renamed packages:");
6468 for (HashMap.Entry<String, String> e
6469 : mSettings.mRenamedPackages.entrySet()) {
6470 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6471 pw.println(e.getValue());
6472 }
6473 }
6474 if (mSettings.mDisabledSysPackages.size() > 0) {
6475 pw.println(" ");
6476 pw.println("Hidden system packages:");
6477 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6478 pw.print(" Package [");
6479 pw.print(ps.realName != null ? ps.realName : ps.name);
6480 pw.print("] (");
6481 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6482 pw.println("):");
6483 if (ps.realName != null) {
6484 pw.print(" compat name="); pw.println(ps.name);
6485 }
6486 pw.print(" userId="); pw.println(ps.userId);
6487 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6488 pw.print(" codePath="); pw.println(ps.codePathString);
6489 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6490 }
6491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 pw.println(" ");
6493 pw.println("Shared Users:");
6494 {
6495 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006496 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6497 pw.print(Integer.toHexString(System.identityHashCode(su)));
6498 pw.println("):");
6499 pw.print(" userId="); pw.print(su.userId);
6500 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 pw.println(" grantedPermissions:");
6502 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006503 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 }
6505 pw.println(" loadedPermissions:");
6506 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006507 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 }
6509 }
6510 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 pw.println(" ");
6513 pw.println("Settings parse messages:");
6514 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006515
6516 pw.println(" ");
6517 pw.println("Package warning messages:");
6518 File fname = getSettingsProblemFile();
6519 FileInputStream in;
6520 try {
6521 in = new FileInputStream(fname);
6522 int avail = in.available();
6523 byte[] data = new byte[avail];
6524 in.read(data);
6525 pw.println(new String(data));
6526 } catch (FileNotFoundException e) {
6527 } catch (IOException e) {
6528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006530
6531 synchronized (mProviders) {
6532 pw.println(" ");
6533 pw.println("Registered ContentProviders:");
6534 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006535 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006536 pw.println(p.toString());
6537 }
6538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 }
6540
6541 static final class BasePermission {
6542 final static int TYPE_NORMAL = 0;
6543 final static int TYPE_BUILTIN = 1;
6544 final static int TYPE_DYNAMIC = 2;
6545
6546 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006547 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 final int type;
6549 PackageParser.Permission perm;
6550 PermissionInfo pendingInfo;
6551 int uid;
6552 int[] gids;
6553
6554 BasePermission(String _name, String _sourcePackage, int _type) {
6555 name = _name;
6556 sourcePackage = _sourcePackage;
6557 type = _type;
6558 }
6559 }
6560
6561 static class PackageSignatures {
6562 private Signature[] mSignatures;
6563
6564 PackageSignatures(Signature[] sigs) {
6565 assignSignatures(sigs);
6566 }
6567
6568 PackageSignatures() {
6569 }
6570
6571 void writeXml(XmlSerializer serializer, String tagName,
6572 ArrayList<Signature> pastSignatures) throws IOException {
6573 if (mSignatures == null) {
6574 return;
6575 }
6576 serializer.startTag(null, tagName);
6577 serializer.attribute(null, "count",
6578 Integer.toString(mSignatures.length));
6579 for (int i=0; i<mSignatures.length; i++) {
6580 serializer.startTag(null, "cert");
6581 final Signature sig = mSignatures[i];
6582 final int sigHash = sig.hashCode();
6583 final int numPast = pastSignatures.size();
6584 int j;
6585 for (j=0; j<numPast; j++) {
6586 Signature pastSig = pastSignatures.get(j);
6587 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6588 serializer.attribute(null, "index", Integer.toString(j));
6589 break;
6590 }
6591 }
6592 if (j >= numPast) {
6593 pastSignatures.add(sig);
6594 serializer.attribute(null, "index", Integer.toString(numPast));
6595 serializer.attribute(null, "key", sig.toCharsString());
6596 }
6597 serializer.endTag(null, "cert");
6598 }
6599 serializer.endTag(null, tagName);
6600 }
6601
6602 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6603 throws IOException, XmlPullParserException {
6604 String countStr = parser.getAttributeValue(null, "count");
6605 if (countStr == null) {
6606 reportSettingsProblem(Log.WARN,
6607 "Error in package manager settings: <signatures> has"
6608 + " no count at " + parser.getPositionDescription());
6609 XmlUtils.skipCurrentTag(parser);
6610 }
6611 final int count = Integer.parseInt(countStr);
6612 mSignatures = new Signature[count];
6613 int pos = 0;
6614
6615 int outerDepth = parser.getDepth();
6616 int type;
6617 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6618 && (type != XmlPullParser.END_TAG
6619 || parser.getDepth() > outerDepth)) {
6620 if (type == XmlPullParser.END_TAG
6621 || type == XmlPullParser.TEXT) {
6622 continue;
6623 }
6624
6625 String tagName = parser.getName();
6626 if (tagName.equals("cert")) {
6627 if (pos < count) {
6628 String index = parser.getAttributeValue(null, "index");
6629 if (index != null) {
6630 try {
6631 int idx = Integer.parseInt(index);
6632 String key = parser.getAttributeValue(null, "key");
6633 if (key == null) {
6634 if (idx >= 0 && idx < pastSignatures.size()) {
6635 Signature sig = pastSignatures.get(idx);
6636 if (sig != null) {
6637 mSignatures[pos] = pastSignatures.get(idx);
6638 pos++;
6639 } else {
6640 reportSettingsProblem(Log.WARN,
6641 "Error in package manager settings: <cert> "
6642 + "index " + index + " is not defined at "
6643 + parser.getPositionDescription());
6644 }
6645 } else {
6646 reportSettingsProblem(Log.WARN,
6647 "Error in package manager settings: <cert> "
6648 + "index " + index + " is out of bounds at "
6649 + parser.getPositionDescription());
6650 }
6651 } else {
6652 while (pastSignatures.size() <= idx) {
6653 pastSignatures.add(null);
6654 }
6655 Signature sig = new Signature(key);
6656 pastSignatures.set(idx, sig);
6657 mSignatures[pos] = sig;
6658 pos++;
6659 }
6660 } catch (NumberFormatException e) {
6661 reportSettingsProblem(Log.WARN,
6662 "Error in package manager settings: <cert> "
6663 + "index " + index + " is not a number at "
6664 + parser.getPositionDescription());
6665 }
6666 } else {
6667 reportSettingsProblem(Log.WARN,
6668 "Error in package manager settings: <cert> has"
6669 + " no index at " + parser.getPositionDescription());
6670 }
6671 } else {
6672 reportSettingsProblem(Log.WARN,
6673 "Error in package manager settings: too "
6674 + "many <cert> tags, expected " + count
6675 + " at " + parser.getPositionDescription());
6676 }
6677 } else {
6678 reportSettingsProblem(Log.WARN,
6679 "Unknown element under <cert>: "
6680 + parser.getName());
6681 }
6682 XmlUtils.skipCurrentTag(parser);
6683 }
6684
6685 if (pos < count) {
6686 // Should never happen -- there is an error in the written
6687 // settings -- but if it does we don't want to generate
6688 // a bad array.
6689 Signature[] newSigs = new Signature[pos];
6690 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6691 mSignatures = newSigs;
6692 }
6693 }
6694
6695 /**
6696 * If any of the given 'sigs' is contained in the existing signatures,
6697 * then completely replace the current signatures with the ones in
6698 * 'sigs'. This is used for updating an existing package to a newly
6699 * installed version.
6700 */
6701 boolean updateSignatures(Signature[] sigs, boolean update) {
6702 if (mSignatures == null) {
6703 if (update) {
6704 assignSignatures(sigs);
6705 }
6706 return true;
6707 }
6708 if (sigs == null) {
6709 return false;
6710 }
6711
6712 for (int i=0; i<sigs.length; i++) {
6713 Signature sig = sigs[i];
6714 for (int j=0; j<mSignatures.length; j++) {
6715 if (mSignatures[j].equals(sig)) {
6716 if (update) {
6717 assignSignatures(sigs);
6718 }
6719 return true;
6720 }
6721 }
6722 }
6723 return false;
6724 }
6725
6726 /**
6727 * If any of the given 'sigs' is contained in the existing signatures,
6728 * then add in any new signatures found in 'sigs'. This is used for
6729 * including a new package into an existing shared user id.
6730 */
6731 boolean mergeSignatures(Signature[] sigs, boolean update) {
6732 if (mSignatures == null) {
6733 if (update) {
6734 assignSignatures(sigs);
6735 }
6736 return true;
6737 }
6738 if (sigs == null) {
6739 return false;
6740 }
6741
6742 Signature[] added = null;
6743 int addedCount = 0;
6744 boolean haveMatch = false;
6745 for (int i=0; i<sigs.length; i++) {
6746 Signature sig = sigs[i];
6747 boolean found = false;
6748 for (int j=0; j<mSignatures.length; j++) {
6749 if (mSignatures[j].equals(sig)) {
6750 found = true;
6751 haveMatch = true;
6752 break;
6753 }
6754 }
6755
6756 if (!found) {
6757 if (added == null) {
6758 added = new Signature[sigs.length];
6759 }
6760 added[i] = sig;
6761 addedCount++;
6762 }
6763 }
6764
6765 if (!haveMatch) {
6766 // Nothing matched -- reject the new signatures.
6767 return false;
6768 }
6769 if (added == null) {
6770 // Completely matched -- nothing else to do.
6771 return true;
6772 }
6773
6774 // Add additional signatures in.
6775 if (update) {
6776 Signature[] total = new Signature[addedCount+mSignatures.length];
6777 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6778 int j = mSignatures.length;
6779 for (int i=0; i<added.length; i++) {
6780 if (added[i] != null) {
6781 total[j] = added[i];
6782 j++;
6783 }
6784 }
6785 mSignatures = total;
6786 }
6787 return true;
6788 }
6789
6790 private void assignSignatures(Signature[] sigs) {
6791 if (sigs == null) {
6792 mSignatures = null;
6793 return;
6794 }
6795 mSignatures = new Signature[sigs.length];
6796 for (int i=0; i<sigs.length; i++) {
6797 mSignatures[i] = sigs[i];
6798 }
6799 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 @Override
6802 public String toString() {
6803 StringBuffer buf = new StringBuffer(128);
6804 buf.append("PackageSignatures{");
6805 buf.append(Integer.toHexString(System.identityHashCode(this)));
6806 buf.append(" [");
6807 if (mSignatures != null) {
6808 for (int i=0; i<mSignatures.length; i++) {
6809 if (i > 0) buf.append(", ");
6810 buf.append(Integer.toHexString(
6811 System.identityHashCode(mSignatures[i])));
6812 }
6813 }
6814 buf.append("]}");
6815 return buf.toString();
6816 }
6817 }
6818
6819 static class PreferredActivity extends IntentFilter {
6820 final int mMatch;
6821 final String[] mSetPackages;
6822 final String[] mSetClasses;
6823 final String[] mSetComponents;
6824 final ComponentName mActivity;
6825 final String mShortActivity;
6826 String mParseError;
6827
6828 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6829 ComponentName activity) {
6830 super(filter);
6831 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6832 mActivity = activity;
6833 mShortActivity = activity.flattenToShortString();
6834 mParseError = null;
6835 if (set != null) {
6836 final int N = set.length;
6837 String[] myPackages = new String[N];
6838 String[] myClasses = new String[N];
6839 String[] myComponents = new String[N];
6840 for (int i=0; i<N; i++) {
6841 ComponentName cn = set[i];
6842 if (cn == null) {
6843 mSetPackages = null;
6844 mSetClasses = null;
6845 mSetComponents = null;
6846 return;
6847 }
6848 myPackages[i] = cn.getPackageName().intern();
6849 myClasses[i] = cn.getClassName().intern();
6850 myComponents[i] = cn.flattenToShortString().intern();
6851 }
6852 mSetPackages = myPackages;
6853 mSetClasses = myClasses;
6854 mSetComponents = myComponents;
6855 } else {
6856 mSetPackages = null;
6857 mSetClasses = null;
6858 mSetComponents = null;
6859 }
6860 }
6861
6862 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6863 IOException {
6864 mShortActivity = parser.getAttributeValue(null, "name");
6865 mActivity = ComponentName.unflattenFromString(mShortActivity);
6866 if (mActivity == null) {
6867 mParseError = "Bad activity name " + mShortActivity;
6868 }
6869 String matchStr = parser.getAttributeValue(null, "match");
6870 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6871 String setCountStr = parser.getAttributeValue(null, "set");
6872 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6873
6874 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6875 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6876 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6877
6878 int setPos = 0;
6879
6880 int outerDepth = parser.getDepth();
6881 int type;
6882 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6883 && (type != XmlPullParser.END_TAG
6884 || parser.getDepth() > outerDepth)) {
6885 if (type == XmlPullParser.END_TAG
6886 || type == XmlPullParser.TEXT) {
6887 continue;
6888 }
6889
6890 String tagName = parser.getName();
6891 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6892 // + parser.getDepth() + " tag=" + tagName);
6893 if (tagName.equals("set")) {
6894 String name = parser.getAttributeValue(null, "name");
6895 if (name == null) {
6896 if (mParseError == null) {
6897 mParseError = "No name in set tag in preferred activity "
6898 + mShortActivity;
6899 }
6900 } else if (setPos >= setCount) {
6901 if (mParseError == null) {
6902 mParseError = "Too many set tags in preferred activity "
6903 + mShortActivity;
6904 }
6905 } else {
6906 ComponentName cn = ComponentName.unflattenFromString(name);
6907 if (cn == null) {
6908 if (mParseError == null) {
6909 mParseError = "Bad set name " + name + " in preferred activity "
6910 + mShortActivity;
6911 }
6912 } else {
6913 myPackages[setPos] = cn.getPackageName();
6914 myClasses[setPos] = cn.getClassName();
6915 myComponents[setPos] = name;
6916 setPos++;
6917 }
6918 }
6919 XmlUtils.skipCurrentTag(parser);
6920 } else if (tagName.equals("filter")) {
6921 //Log.i(TAG, "Starting to parse filter...");
6922 readFromXml(parser);
6923 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6924 // + parser.getDepth() + " tag=" + parser.getName());
6925 } else {
6926 reportSettingsProblem(Log.WARN,
6927 "Unknown element under <preferred-activities>: "
6928 + parser.getName());
6929 XmlUtils.skipCurrentTag(parser);
6930 }
6931 }
6932
6933 if (setPos != setCount) {
6934 if (mParseError == null) {
6935 mParseError = "Not enough set tags (expected " + setCount
6936 + " but found " + setPos + ") in " + mShortActivity;
6937 }
6938 }
6939
6940 mSetPackages = myPackages;
6941 mSetClasses = myClasses;
6942 mSetComponents = myComponents;
6943 }
6944
6945 public void writeToXml(XmlSerializer serializer) throws IOException {
6946 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6947 serializer.attribute(null, "name", mShortActivity);
6948 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6949 serializer.attribute(null, "set", Integer.toString(NS));
6950 for (int s=0; s<NS; s++) {
6951 serializer.startTag(null, "set");
6952 serializer.attribute(null, "name", mSetComponents[s]);
6953 serializer.endTag(null, "set");
6954 }
6955 serializer.startTag(null, "filter");
6956 super.writeToXml(serializer);
6957 serializer.endTag(null, "filter");
6958 }
6959
6960 boolean sameSet(List<ResolveInfo> query, int priority) {
6961 if (mSetPackages == null) return false;
6962 final int NQ = query.size();
6963 final int NS = mSetPackages.length;
6964 int numMatch = 0;
6965 for (int i=0; i<NQ; i++) {
6966 ResolveInfo ri = query.get(i);
6967 if (ri.priority != priority) continue;
6968 ActivityInfo ai = ri.activityInfo;
6969 boolean good = false;
6970 for (int j=0; j<NS; j++) {
6971 if (mSetPackages[j].equals(ai.packageName)
6972 && mSetClasses[j].equals(ai.name)) {
6973 numMatch++;
6974 good = true;
6975 break;
6976 }
6977 }
6978 if (!good) return false;
6979 }
6980 return numMatch == NS;
6981 }
6982 }
6983
6984 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006985 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006987 HashSet<String> grantedPermissions = new HashSet<String>();
6988 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006990 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006992 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006993 setFlags(pkgFlags);
6994 }
6995
6996 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006997 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006998 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6999 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007000 }
7001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007003 /**
7004 * Settings base class for pending and resolved classes.
7005 */
7006 static class PackageSettingBase extends GrantedPermissions {
7007 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007008 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007009 File codePath;
7010 String codePathString;
7011 File resourcePath;
7012 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007013 private long timeStamp;
7014 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007015 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007016
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007017 boolean uidError;
7018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 PackageSignatures signatures = new PackageSignatures();
7020
7021 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007023 /* Explicitly disabled components */
7024 HashSet<String> disabledComponents = new HashSet<String>(0);
7025 /* Explicitly enabled components */
7026 HashSet<String> enabledComponents = new HashSet<String>(0);
7027 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7028 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007029
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007030 PackageSettingBase origPackage;
7031
Jacek Surazski65e13172009-04-28 15:26:38 +02007032 /* package name of the app that installed this package */
7033 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007035 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007036 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 super(pkgFlags);
7038 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007039 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007040 init(codePath, resourcePath, pVersionCode);
7041 }
7042
7043 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 this.codePath = codePath;
7045 this.codePathString = codePath.toString();
7046 this.resourcePath = resourcePath;
7047 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007048 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007049 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007050
Jacek Surazski65e13172009-04-28 15:26:38 +02007051 public void setInstallerPackageName(String packageName) {
7052 installerPackageName = packageName;
7053 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007054
Jacek Surazski65e13172009-04-28 15:26:38 +02007055 String getInstallerPackageName() {
7056 return installerPackageName;
7057 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007059 public void setInstallStatus(int newStatus) {
7060 installStatus = newStatus;
7061 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063 public int getInstallStatus() {
7064 return installStatus;
7065 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007067 public void setTimeStamp(long newStamp) {
7068 if (newStamp != timeStamp) {
7069 timeStamp = newStamp;
7070 timeStampString = Long.toString(newStamp);
7071 }
7072 }
7073
7074 public void setTimeStamp(long newStamp, String newStampStr) {
7075 timeStamp = newStamp;
7076 timeStampString = newStampStr;
7077 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007079 public long getTimeStamp() {
7080 return timeStamp;
7081 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 public String getTimeStampStr() {
7084 return timeStampString;
7085 }
7086
7087 public void copyFrom(PackageSettingBase base) {
7088 grantedPermissions = base.grantedPermissions;
7089 gids = base.gids;
7090 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 timeStamp = base.timeStamp;
7093 timeStampString = base.timeStampString;
7094 signatures = base.signatures;
7095 permissionsFixed = base.permissionsFixed;
7096 disabledComponents = base.disabledComponents;
7097 enabledComponents = base.enabledComponents;
7098 enabled = base.enabled;
7099 installStatus = base.installStatus;
7100 }
7101
7102 void enableComponentLP(String componentClassName) {
7103 disabledComponents.remove(componentClassName);
7104 enabledComponents.add(componentClassName);
7105 }
7106
7107 void disableComponentLP(String componentClassName) {
7108 enabledComponents.remove(componentClassName);
7109 disabledComponents.add(componentClassName);
7110 }
7111
7112 void restoreComponentLP(String componentClassName) {
7113 enabledComponents.remove(componentClassName);
7114 disabledComponents.remove(componentClassName);
7115 }
7116
7117 int currentEnabledStateLP(String componentName) {
7118 if (enabledComponents.contains(componentName)) {
7119 return COMPONENT_ENABLED_STATE_ENABLED;
7120 } else if (disabledComponents.contains(componentName)) {
7121 return COMPONENT_ENABLED_STATE_DISABLED;
7122 } else {
7123 return COMPONENT_ENABLED_STATE_DEFAULT;
7124 }
7125 }
7126 }
7127
7128 /**
7129 * Settings data for a particular package we know about.
7130 */
7131 static final class PackageSetting extends PackageSettingBase {
7132 int userId;
7133 PackageParser.Package pkg;
7134 SharedUserSetting sharedUser;
7135
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007136 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007137 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007138 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007139 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007141 @Override
7142 public String toString() {
7143 return "PackageSetting{"
7144 + Integer.toHexString(System.identityHashCode(this))
7145 + " " + name + "/" + userId + "}";
7146 }
7147 }
7148
7149 /**
7150 * Settings data for a particular shared user ID we know about.
7151 */
7152 static final class SharedUserSetting extends GrantedPermissions {
7153 final String name;
7154 int userId;
7155 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7156 final PackageSignatures signatures = new PackageSignatures();
7157
7158 SharedUserSetting(String _name, int _pkgFlags) {
7159 super(_pkgFlags);
7160 name = _name;
7161 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007163 @Override
7164 public String toString() {
7165 return "SharedUserSetting{"
7166 + Integer.toHexString(System.identityHashCode(this))
7167 + " " + name + "/" + userId + "}";
7168 }
7169 }
7170
7171 /**
7172 * Holds information about dynamic settings.
7173 */
7174 private static final class Settings {
7175 private final File mSettingsFilename;
7176 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007177 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 private final HashMap<String, PackageSetting> mPackages =
7179 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007180 // List of replaced system applications
7181 final HashMap<String, PackageSetting> mDisabledSysPackages =
7182 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 // The user's preferred activities associated with particular intent
7185 // filters.
7186 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7187 new IntentResolver<PreferredActivity, PreferredActivity>() {
7188 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007189 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007191 out.print(prefix); out.print(
7192 Integer.toHexString(System.identityHashCode(filter)));
7193 out.print(' ');
7194 out.print(filter.mActivity.flattenToShortString());
7195 out.print(" match=0x");
7196 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007198 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007199 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007200 out.print(prefix); out.print(" ");
7201 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007202 }
7203 }
7204 }
7205 };
7206 private final HashMap<String, SharedUserSetting> mSharedUsers =
7207 new HashMap<String, SharedUserSetting>();
7208 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7209 private final SparseArray<Object> mOtherUserIds =
7210 new SparseArray<Object>();
7211
7212 // For reading/writing settings file.
7213 private final ArrayList<Signature> mPastSignatures =
7214 new ArrayList<Signature>();
7215
7216 // Mapping from permission names to info about them.
7217 final HashMap<String, BasePermission> mPermissions =
7218 new HashMap<String, BasePermission>();
7219
7220 // Mapping from permission tree names to info about them.
7221 final HashMap<String, BasePermission> mPermissionTrees =
7222 new HashMap<String, BasePermission>();
7223
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007224 // Packages that have been uninstalled and still need their external
7225 // storage data deleted.
7226 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7227
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007228 // Packages that have been renamed since they were first installed.
7229 // Keys are the new names of the packages, values are the original
7230 // names. The packages appear everwhere else under their original
7231 // names.
7232 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 private final StringBuilder mReadMessages = new StringBuilder();
7235
7236 private static final class PendingPackage extends PackageSettingBase {
7237 final int sharedId;
7238
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007239 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007240 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007241 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007242 this.sharedId = sharedId;
7243 }
7244 }
7245 private final ArrayList<PendingPackage> mPendingPackages
7246 = new ArrayList<PendingPackage>();
7247
7248 Settings() {
7249 File dataDir = Environment.getDataDirectory();
7250 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007251 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7252 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007253 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007254 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 FileUtils.setPermissions(systemDir.toString(),
7256 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7257 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7258 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007259 FileUtils.setPermissions(systemSecureDir.toString(),
7260 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7261 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7262 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007263 mSettingsFilename = new File(systemDir, "packages.xml");
7264 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007265 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 }
7267
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007268 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007269 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007270 int pkgFlags, boolean create, boolean add) {
7271 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007272 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007273 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007274 return p;
7275 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007276
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007277 PackageSetting peekPackageLP(String name) {
7278 return mPackages.get(name);
7279 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007280 PackageSetting p = mPackages.get(name);
7281 if (p != null && p.codePath.getPath().equals(codePath)) {
7282 return p;
7283 }
7284 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007285 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 void setInstallStatus(String pkgName, int status) {
7289 PackageSetting p = mPackages.get(pkgName);
7290 if(p != null) {
7291 if(p.getInstallStatus() != status) {
7292 p.setInstallStatus(status);
7293 }
7294 }
7295 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007296
Jacek Surazski65e13172009-04-28 15:26:38 +02007297 void setInstallerPackageName(String pkgName,
7298 String installerPkgName) {
7299 PackageSetting p = mPackages.get(pkgName);
7300 if(p != null) {
7301 p.setInstallerPackageName(installerPkgName);
7302 }
7303 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007304
Jacek Surazski65e13172009-04-28 15:26:38 +02007305 String getInstallerPackageName(String pkgName) {
7306 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007307 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007308 }
7309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 int getInstallStatus(String pkgName) {
7311 PackageSetting p = mPackages.get(pkgName);
7312 if(p != null) {
7313 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007315 return -1;
7316 }
7317
7318 SharedUserSetting getSharedUserLP(String name,
7319 int pkgFlags, boolean create) {
7320 SharedUserSetting s = mSharedUsers.get(name);
7321 if (s == null) {
7322 if (!create) {
7323 return null;
7324 }
7325 s = new SharedUserSetting(name, pkgFlags);
7326 if (MULTIPLE_APPLICATION_UIDS) {
7327 s.userId = newUserIdLP(s);
7328 } else {
7329 s.userId = FIRST_APPLICATION_UID;
7330 }
7331 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7332 // < 0 means we couldn't assign a userid; fall out and return
7333 // s, which is currently null
7334 if (s.userId >= 0) {
7335 mSharedUsers.put(name, s);
7336 }
7337 }
7338
7339 return s;
7340 }
7341
7342 int disableSystemPackageLP(String name) {
7343 PackageSetting p = mPackages.get(name);
7344 if(p == null) {
7345 Log.w(TAG, "Package:"+name+" is not an installed package");
7346 return -1;
7347 }
7348 PackageSetting dp = mDisabledSysPackages.get(name);
7349 // always make sure the system package code and resource paths dont change
7350 if(dp == null) {
7351 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7352 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7353 }
7354 mDisabledSysPackages.put(name, p);
7355 }
7356 return removePackageLP(name);
7357 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007359 PackageSetting enableSystemPackageLP(String name) {
7360 PackageSetting p = mDisabledSysPackages.get(name);
7361 if(p == null) {
7362 Log.w(TAG, "Package:"+name+" is not disabled");
7363 return null;
7364 }
7365 // Reset flag in ApplicationInfo object
7366 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7367 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7368 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007369 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007370 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 mDisabledSysPackages.remove(name);
7372 return ret;
7373 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007374
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007375 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007376 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007377 PackageSetting p = mPackages.get(name);
7378 if (p != null) {
7379 if (p.userId == uid) {
7380 return p;
7381 }
7382 reportSettingsProblem(Log.ERROR,
7383 "Adding duplicate package, keeping first: " + name);
7384 return null;
7385 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007386 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007387 p.userId = uid;
7388 if (addUserIdLP(uid, p, name)) {
7389 mPackages.put(name, p);
7390 return p;
7391 }
7392 return null;
7393 }
7394
7395 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7396 SharedUserSetting s = mSharedUsers.get(name);
7397 if (s != null) {
7398 if (s.userId == uid) {
7399 return s;
7400 }
7401 reportSettingsProblem(Log.ERROR,
7402 "Adding duplicate shared user, keeping first: " + name);
7403 return null;
7404 }
7405 s = new SharedUserSetting(name, pkgFlags);
7406 s.userId = uid;
7407 if (addUserIdLP(uid, s, name)) {
7408 mSharedUsers.put(name, s);
7409 return s;
7410 }
7411 return null;
7412 }
7413
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007414 // Transfer ownership of permissions from one package to another.
7415 private void transferPermissions(String origPkg, String newPkg) {
7416 // Transfer ownership of permissions to the new package.
7417 for (int i=0; i<2; i++) {
7418 HashMap<String, BasePermission> permissions =
7419 i == 0 ? mPermissionTrees : mPermissions;
7420 for (BasePermission bp : permissions.values()) {
7421 if (origPkg.equals(bp.sourcePackage)) {
7422 if (DEBUG_UPGRADE) Log.v(TAG,
7423 "Moving permission " + bp.name
7424 + " from pkg " + bp.sourcePackage
7425 + " to " + newPkg);
7426 bp.sourcePackage = newPkg;
7427 bp.perm = null;
7428 if (bp.pendingInfo != null) {
7429 bp.sourcePackage = newPkg;
7430 }
7431 bp.uid = 0;
7432 bp.gids = null;
7433 }
7434 }
7435 }
7436 }
7437
7438 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007439 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007440 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 PackageSetting p = mPackages.get(name);
7442 if (p != null) {
7443 if (!p.codePath.equals(codePath)) {
7444 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007445 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007446 // This is an updated system app with versions in both system
7447 // and data partition. Just let the most recent version
7448 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007449 Log.w(TAG, "Trying to update system app code path from " +
7450 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007451 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007452 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07007453 reportSettingsProblem(Log.WARN,
7454 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007455 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007456 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007457 }
7458 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007459 reportSettingsProblem(Log.WARN,
7460 "Package " + name + " shared user changed from "
7461 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7462 + " to "
7463 + (sharedUser != null ? sharedUser.name : "<nothing>")
7464 + "; replacing with new");
7465 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007466 } else {
7467 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7468 // If what we are scanning is a system package, then
7469 // make it so, regardless of whether it was previously
7470 // installed only in the data partition.
7471 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473 }
7474 }
7475 if (p == null) {
7476 // Create a new PackageSettings entry. this can end up here because
7477 // of code path mismatch or user id mismatch of an updated system partition
7478 if (!create) {
7479 return null;
7480 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007481 if (origPackage != null) {
7482 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007483 p = new PackageSetting(origPackage.name, name, codePath,
7484 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007485 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7486 + " is adopting original package " + origPackage.name);
7487 p.copyFrom(origPackage);
7488 p.sharedUser = origPackage.sharedUser;
7489 p.userId = origPackage.userId;
7490 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007491 mRenamedPackages.put(name, origPackage.name);
7492 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007493 // Update new package state.
7494 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007495 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007496 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007497 p.setTimeStamp(codePath.lastModified());
7498 p.sharedUser = sharedUser;
7499 if (sharedUser != null) {
7500 p.userId = sharedUser.userId;
7501 } else if (MULTIPLE_APPLICATION_UIDS) {
7502 // Clone the setting here for disabled system packages
7503 PackageSetting dis = mDisabledSysPackages.get(name);
7504 if (dis != null) {
7505 // For disabled packages a new setting is created
7506 // from the existing user id. This still has to be
7507 // added to list of user id's
7508 // Copy signatures from previous setting
7509 if (dis.signatures.mSignatures != null) {
7510 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7511 }
7512 p.userId = dis.userId;
7513 // Clone permissions
7514 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7515 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7516 // Clone component info
7517 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7518 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7519 // Add new setting to list of user ids
7520 addUserIdLP(p.userId, p, name);
7521 } else {
7522 // Assign new user id
7523 p.userId = newUserIdLP(p);
7524 }
7525 } else {
7526 p.userId = FIRST_APPLICATION_UID;
7527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007528 }
7529 if (p.userId < 0) {
7530 reportSettingsProblem(Log.WARN,
7531 "Package " + name + " could not be assigned a valid uid");
7532 return null;
7533 }
7534 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007535 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007537 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 }
7539 }
7540 return p;
7541 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007542
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007543 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007544 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007545 String codePath = pkg.applicationInfo.sourceDir;
7546 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007547 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007548 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007549 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007550 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007551 p.codePath = new File(codePath);
7552 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007553 }
7554 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007555 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007556 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007557 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007558 p.resourcePath = new File(resourcePath);
7559 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007560 }
7561 // Update version code if needed
7562 if (pkg.mVersionCode != p.versionCode) {
7563 p.versionCode = pkg.mVersionCode;
7564 }
7565 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7566 }
7567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568 // Utility method that adds a PackageSetting to mPackages and
7569 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007570 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007571 SharedUserSetting sharedUser) {
7572 mPackages.put(name, p);
7573 if (sharedUser != null) {
7574 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7575 reportSettingsProblem(Log.ERROR,
7576 "Package " + p.name + " was user "
7577 + p.sharedUser + " but is now " + sharedUser
7578 + "; I am not changing its files so it will probably fail!");
7579 p.sharedUser.packages.remove(p);
7580 } else if (p.userId != sharedUser.userId) {
7581 reportSettingsProblem(Log.ERROR,
7582 "Package " + p.name + " was user id " + p.userId
7583 + " but is now user " + sharedUser
7584 + " with id " + sharedUser.userId
7585 + "; I am not changing its files so it will probably fail!");
7586 }
7587
7588 sharedUser.packages.add(p);
7589 p.sharedUser = sharedUser;
7590 p.userId = sharedUser.userId;
7591 }
7592 }
7593
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007594 /*
7595 * Update the shared user setting when a package using
7596 * specifying the shared user id is removed. The gids
7597 * associated with each permission of the deleted package
7598 * are removed from the shared user's gid list only if its
7599 * not in use by other permissions of packages in the
7600 * shared user setting.
7601 */
7602 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7604 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7605 return;
7606 }
7607 // No sharedUserId
7608 if (deletedPs.sharedUser == null) {
7609 return;
7610 }
7611 SharedUserSetting sus = deletedPs.sharedUser;
7612 // Update permissions
7613 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7614 boolean used = false;
7615 if (!sus.grantedPermissions.contains (eachPerm)) {
7616 continue;
7617 }
7618 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007619 if (pkg.pkg != null &&
7620 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7621 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622 used = true;
7623 break;
7624 }
7625 }
7626 if (!used) {
7627 // can safely delete this permission from list
7628 sus.grantedPermissions.remove(eachPerm);
7629 sus.loadedPermissions.remove(eachPerm);
7630 }
7631 }
7632 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007633 int newGids[] = globalGids;
7634 for (String eachPerm : sus.grantedPermissions) {
7635 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007636 if (bp != null) {
7637 newGids = appendInts(newGids, bp.gids);
7638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007639 }
7640 sus.gids = newGids;
7641 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643 private int removePackageLP(String name) {
7644 PackageSetting p = mPackages.get(name);
7645 if (p != null) {
7646 mPackages.remove(name);
7647 if (p.sharedUser != null) {
7648 p.sharedUser.packages.remove(p);
7649 if (p.sharedUser.packages.size() == 0) {
7650 mSharedUsers.remove(p.sharedUser.name);
7651 removeUserIdLP(p.sharedUser.userId);
7652 return p.sharedUser.userId;
7653 }
7654 } else {
7655 removeUserIdLP(p.userId);
7656 return p.userId;
7657 }
7658 }
7659 return -1;
7660 }
7661
7662 private boolean addUserIdLP(int uid, Object obj, Object name) {
7663 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7664 return false;
7665 }
7666
7667 if (uid >= FIRST_APPLICATION_UID) {
7668 int N = mUserIds.size();
7669 final int index = uid - FIRST_APPLICATION_UID;
7670 while (index >= N) {
7671 mUserIds.add(null);
7672 N++;
7673 }
7674 if (mUserIds.get(index) != null) {
7675 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007676 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 + " name=" + name);
7678 return false;
7679 }
7680 mUserIds.set(index, obj);
7681 } else {
7682 if (mOtherUserIds.get(uid) != null) {
7683 reportSettingsProblem(Log.ERROR,
7684 "Adding duplicate shared id: " + uid
7685 + " name=" + name);
7686 return false;
7687 }
7688 mOtherUserIds.put(uid, obj);
7689 }
7690 return true;
7691 }
7692
7693 public Object getUserIdLP(int uid) {
7694 if (uid >= FIRST_APPLICATION_UID) {
7695 int N = mUserIds.size();
7696 final int index = uid - FIRST_APPLICATION_UID;
7697 return index < N ? mUserIds.get(index) : null;
7698 } else {
7699 return mOtherUserIds.get(uid);
7700 }
7701 }
7702
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007703 private Set<String> findPackagesWithFlag(int flag) {
7704 Set<String> ret = new HashSet<String>();
7705 for (PackageSetting ps : mPackages.values()) {
7706 // Has to match atleast all the flag bits set on flag
7707 if ((ps.pkgFlags & flag) == flag) {
7708 ret.add(ps.name);
7709 }
7710 }
7711 return ret;
7712 }
7713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 private void removeUserIdLP(int uid) {
7715 if (uid >= FIRST_APPLICATION_UID) {
7716 int N = mUserIds.size();
7717 final int index = uid - FIRST_APPLICATION_UID;
7718 if (index < N) mUserIds.set(index, null);
7719 } else {
7720 mOtherUserIds.remove(uid);
7721 }
7722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007724 void writeLP() {
7725 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7726
7727 // Keep the old settings around until we know the new ones have
7728 // been successfully written.
7729 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007730 // Presence of backup settings file indicates that we failed
7731 // to persist settings earlier. So preserve the older
7732 // backup for future reference since the current settings
7733 // might have been corrupted.
7734 if (!mBackupSettingsFilename.exists()) {
7735 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7736 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7737 return;
7738 }
7739 } else {
7740 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742 }
7743
7744 mPastSignatures.clear();
7745
7746 try {
7747 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7748
7749 //XmlSerializer serializer = XmlUtils.serializerInstance();
7750 XmlSerializer serializer = new FastXmlSerializer();
7751 serializer.setOutput(str, "utf-8");
7752 serializer.startDocument(null, true);
7753 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7754
7755 serializer.startTag(null, "packages");
7756
7757 serializer.startTag(null, "permission-trees");
7758 for (BasePermission bp : mPermissionTrees.values()) {
7759 writePermission(serializer, bp);
7760 }
7761 serializer.endTag(null, "permission-trees");
7762
7763 serializer.startTag(null, "permissions");
7764 for (BasePermission bp : mPermissions.values()) {
7765 writePermission(serializer, bp);
7766 }
7767 serializer.endTag(null, "permissions");
7768
7769 for (PackageSetting pkg : mPackages.values()) {
7770 writePackage(serializer, pkg);
7771 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7774 writeDisabledSysPackage(serializer, pkg);
7775 }
7776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007777 serializer.startTag(null, "preferred-activities");
7778 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7779 serializer.startTag(null, "item");
7780 pa.writeToXml(serializer);
7781 serializer.endTag(null, "item");
7782 }
7783 serializer.endTag(null, "preferred-activities");
7784
7785 for (SharedUserSetting usr : mSharedUsers.values()) {
7786 serializer.startTag(null, "shared-user");
7787 serializer.attribute(null, "name", usr.name);
7788 serializer.attribute(null, "userId",
7789 Integer.toString(usr.userId));
7790 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7791 serializer.startTag(null, "perms");
7792 for (String name : usr.grantedPermissions) {
7793 serializer.startTag(null, "item");
7794 serializer.attribute(null, "name", name);
7795 serializer.endTag(null, "item");
7796 }
7797 serializer.endTag(null, "perms");
7798 serializer.endTag(null, "shared-user");
7799 }
7800
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007801 if (mPackagesToBeCleaned.size() > 0) {
7802 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7803 serializer.startTag(null, "cleaning-package");
7804 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7805 serializer.endTag(null, "cleaning-package");
7806 }
7807 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007808
7809 if (mRenamedPackages.size() > 0) {
7810 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
7811 serializer.startTag(null, "renamed-package");
7812 serializer.attribute(null, "new", e.getKey());
7813 serializer.attribute(null, "old", e.getValue());
7814 serializer.endTag(null, "renamed-package");
7815 }
7816 }
7817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 serializer.endTag(null, "packages");
7819
7820 serializer.endDocument();
7821
7822 str.flush();
7823 str.close();
7824
7825 // New settings successfully written, old ones are no longer
7826 // needed.
7827 mBackupSettingsFilename.delete();
7828 FileUtils.setPermissions(mSettingsFilename.toString(),
7829 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7830 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7831 |FileUtils.S_IROTH,
7832 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007833
7834 // Write package list file now, use a JournaledFile.
7835 //
7836 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
7837 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
7838
7839 str = new FileOutputStream(journal.chooseForWrite());
7840 try {
7841 StringBuilder sb = new StringBuilder();
7842 for (PackageSetting pkg : mPackages.values()) {
7843 ApplicationInfo ai = pkg.pkg.applicationInfo;
7844 String dataPath = ai.dataDir;
7845 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7846
7847 // Avoid any application that has a space in its path
7848 // or that is handled by the system.
7849 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
7850 continue;
7851
7852 // we store on each line the following information for now:
7853 //
7854 // pkgName - package name
7855 // userId - application-specific user id
7856 // debugFlag - 0 or 1 if the package is debuggable.
7857 // dataPath - path to package's data path
7858 //
7859 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
7860 //
7861 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
7862 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
7863 // system/core/run-as/run-as.c
7864 //
7865 sb.setLength(0);
7866 sb.append(ai.packageName);
7867 sb.append(" ");
7868 sb.append((int)ai.uid);
7869 sb.append(isDebug ? " 1 " : " 0 ");
7870 sb.append(dataPath);
7871 sb.append("\n");
7872 str.write(sb.toString().getBytes());
7873 }
7874 str.flush();
7875 str.close();
7876 journal.commit();
7877 }
7878 catch (Exception e) {
7879 journal.rollback();
7880 }
7881
7882 FileUtils.setPermissions(mPackageListFilename.toString(),
7883 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7884 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7885 |FileUtils.S_IROTH,
7886 -1, -1);
7887
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007888 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889
7890 } catch(XmlPullParserException e) {
7891 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 -08007892 } catch(java.io.IOException e) {
7893 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 -08007894 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007895 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007896 if (mSettingsFilename.exists()) {
7897 if (!mSettingsFilename.delete()) {
7898 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7899 }
7900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007901 //Debug.stopMethodTracing();
7902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007903
7904 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007905 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 serializer.startTag(null, "updated-package");
7907 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007908 if (pkg.realName != null) {
7909 serializer.attribute(null, "realName", pkg.realName);
7910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007911 serializer.attribute(null, "codePath", pkg.codePathString);
7912 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007913 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007914 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7915 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7916 }
7917 if (pkg.sharedUser == null) {
7918 serializer.attribute(null, "userId",
7919 Integer.toString(pkg.userId));
7920 } else {
7921 serializer.attribute(null, "sharedUserId",
7922 Integer.toString(pkg.userId));
7923 }
7924 serializer.startTag(null, "perms");
7925 if (pkg.sharedUser == null) {
7926 // If this is a shared user, the permissions will
7927 // be written there. We still need to write an
7928 // empty permissions list so permissionsFixed will
7929 // be set.
7930 for (final String name : pkg.grantedPermissions) {
7931 BasePermission bp = mPermissions.get(name);
7932 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7933 // We only need to write signature or system permissions but this wont
7934 // match the semantics of grantedPermissions. So write all permissions.
7935 serializer.startTag(null, "item");
7936 serializer.attribute(null, "name", name);
7937 serializer.endTag(null, "item");
7938 }
7939 }
7940 }
7941 serializer.endTag(null, "perms");
7942 serializer.endTag(null, "updated-package");
7943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007944
7945 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007946 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007947 serializer.startTag(null, "package");
7948 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007949 if (pkg.realName != null) {
7950 serializer.attribute(null, "realName", pkg.realName);
7951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007952 serializer.attribute(null, "codePath", pkg.codePathString);
7953 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7954 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7955 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007956 serializer.attribute(null, "flags",
7957 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007959 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 if (pkg.sharedUser == null) {
7961 serializer.attribute(null, "userId",
7962 Integer.toString(pkg.userId));
7963 } else {
7964 serializer.attribute(null, "sharedUserId",
7965 Integer.toString(pkg.userId));
7966 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007967 if (pkg.uidError) {
7968 serializer.attribute(null, "uidError", "true");
7969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7971 serializer.attribute(null, "enabled",
7972 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7973 ? "true" : "false");
7974 }
7975 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7976 serializer.attribute(null, "installStatus", "false");
7977 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007978 if (pkg.installerPackageName != null) {
7979 serializer.attribute(null, "installer", pkg.installerPackageName);
7980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7982 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7983 serializer.startTag(null, "perms");
7984 if (pkg.sharedUser == null) {
7985 // If this is a shared user, the permissions will
7986 // be written there. We still need to write an
7987 // empty permissions list so permissionsFixed will
7988 // be set.
7989 for (final String name : pkg.grantedPermissions) {
7990 serializer.startTag(null, "item");
7991 serializer.attribute(null, "name", name);
7992 serializer.endTag(null, "item");
7993 }
7994 }
7995 serializer.endTag(null, "perms");
7996 }
7997 if (pkg.disabledComponents.size() > 0) {
7998 serializer.startTag(null, "disabled-components");
7999 for (final String name : pkg.disabledComponents) {
8000 serializer.startTag(null, "item");
8001 serializer.attribute(null, "name", name);
8002 serializer.endTag(null, "item");
8003 }
8004 serializer.endTag(null, "disabled-components");
8005 }
8006 if (pkg.enabledComponents.size() > 0) {
8007 serializer.startTag(null, "enabled-components");
8008 for (final String name : pkg.enabledComponents) {
8009 serializer.startTag(null, "item");
8010 serializer.attribute(null, "name", name);
8011 serializer.endTag(null, "item");
8012 }
8013 serializer.endTag(null, "enabled-components");
8014 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008016 serializer.endTag(null, "package");
8017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008019 void writePermission(XmlSerializer serializer, BasePermission bp)
8020 throws XmlPullParserException, java.io.IOException {
8021 if (bp.type != BasePermission.TYPE_BUILTIN
8022 && bp.sourcePackage != null) {
8023 serializer.startTag(null, "item");
8024 serializer.attribute(null, "name", bp.name);
8025 serializer.attribute(null, "package", bp.sourcePackage);
8026 if (DEBUG_SETTINGS) Log.v(TAG,
8027 "Writing perm: name=" + bp.name + " type=" + bp.type);
8028 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8029 PermissionInfo pi = bp.perm != null ? bp.perm.info
8030 : bp.pendingInfo;
8031 if (pi != null) {
8032 serializer.attribute(null, "type", "dynamic");
8033 if (pi.icon != 0) {
8034 serializer.attribute(null, "icon",
8035 Integer.toString(pi.icon));
8036 }
8037 if (pi.nonLocalizedLabel != null) {
8038 serializer.attribute(null, "label",
8039 pi.nonLocalizedLabel.toString());
8040 }
8041 if (pi.protectionLevel !=
8042 PermissionInfo.PROTECTION_NORMAL) {
8043 serializer.attribute(null, "protection",
8044 Integer.toString(pi.protectionLevel));
8045 }
8046 }
8047 }
8048 serializer.endTag(null, "item");
8049 }
8050 }
8051
8052 String getReadMessagesLP() {
8053 return mReadMessages.toString();
8054 }
8055
Oscar Montemayora8529f62009-11-18 10:14:20 -08008056 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8058 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008059 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 while(its.hasNext()) {
8061 String key = its.next();
8062 PackageSetting ps = mPackages.get(key);
8063 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008064 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008065 }
8066 }
8067 return ret;
8068 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 boolean readLP() {
8071 FileInputStream str = null;
8072 if (mBackupSettingsFilename.exists()) {
8073 try {
8074 str = new FileInputStream(mBackupSettingsFilename);
8075 mReadMessages.append("Reading from backup settings file\n");
8076 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008077 if (mSettingsFilename.exists()) {
8078 // If both the backup and settings file exist, we
8079 // ignore the settings since it might have been
8080 // corrupted.
8081 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
8082 mSettingsFilename.delete();
8083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 } catch (java.io.IOException e) {
8085 // We'll try for the normal settings file.
8086 }
8087 }
8088
8089 mPastSignatures.clear();
8090
8091 try {
8092 if (str == null) {
8093 if (!mSettingsFilename.exists()) {
8094 mReadMessages.append("No settings file found\n");
8095 Log.i(TAG, "No current settings file!");
8096 return false;
8097 }
8098 str = new FileInputStream(mSettingsFilename);
8099 }
8100 XmlPullParser parser = Xml.newPullParser();
8101 parser.setInput(str, null);
8102
8103 int type;
8104 while ((type=parser.next()) != XmlPullParser.START_TAG
8105 && type != XmlPullParser.END_DOCUMENT) {
8106 ;
8107 }
8108
8109 if (type != XmlPullParser.START_TAG) {
8110 mReadMessages.append("No start tag found in settings file\n");
8111 Log.e(TAG, "No start tag found in package manager settings");
8112 return false;
8113 }
8114
8115 int outerDepth = parser.getDepth();
8116 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8117 && (type != XmlPullParser.END_TAG
8118 || parser.getDepth() > outerDepth)) {
8119 if (type == XmlPullParser.END_TAG
8120 || type == XmlPullParser.TEXT) {
8121 continue;
8122 }
8123
8124 String tagName = parser.getName();
8125 if (tagName.equals("package")) {
8126 readPackageLP(parser);
8127 } else if (tagName.equals("permissions")) {
8128 readPermissionsLP(mPermissions, parser);
8129 } else if (tagName.equals("permission-trees")) {
8130 readPermissionsLP(mPermissionTrees, parser);
8131 } else if (tagName.equals("shared-user")) {
8132 readSharedUserLP(parser);
8133 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008134 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 } else if (tagName.equals("preferred-activities")) {
8136 readPreferredActivitiesLP(parser);
8137 } else if(tagName.equals("updated-package")) {
8138 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008139 } else if (tagName.equals("cleaning-package")) {
8140 String name = parser.getAttributeValue(null, "name");
8141 if (name != null) {
8142 mPackagesToBeCleaned.add(name);
8143 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008144 } else if (tagName.equals("renamed-package")) {
8145 String nname = parser.getAttributeValue(null, "new");
8146 String oname = parser.getAttributeValue(null, "old");
8147 if (nname != null && oname != null) {
8148 mRenamedPackages.put(nname, oname);
8149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 } else {
8151 Log.w(TAG, "Unknown element under <packages>: "
8152 + parser.getName());
8153 XmlUtils.skipCurrentTag(parser);
8154 }
8155 }
8156
8157 str.close();
8158
8159 } catch(XmlPullParserException e) {
8160 mReadMessages.append("Error reading: " + e.toString());
8161 Log.e(TAG, "Error reading package manager settings", e);
8162
8163 } catch(java.io.IOException e) {
8164 mReadMessages.append("Error reading: " + e.toString());
8165 Log.e(TAG, "Error reading package manager settings", e);
8166
8167 }
8168
8169 int N = mPendingPackages.size();
8170 for (int i=0; i<N; i++) {
8171 final PendingPackage pp = mPendingPackages.get(i);
8172 Object idObj = getUserIdLP(pp.sharedId);
8173 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008174 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008176 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 if (p == null) {
8178 Log.w(TAG, "Unable to create application package for "
8179 + pp.name);
8180 continue;
8181 }
8182 p.copyFrom(pp);
8183 } else if (idObj != null) {
8184 String msg = "Bad package setting: package " + pp.name
8185 + " has shared uid " + pp.sharedId
8186 + " that is not a shared uid\n";
8187 mReadMessages.append(msg);
8188 Log.e(TAG, msg);
8189 } else {
8190 String msg = "Bad package setting: package " + pp.name
8191 + " has shared uid " + pp.sharedId
8192 + " that is not defined\n";
8193 mReadMessages.append(msg);
8194 Log.e(TAG, msg);
8195 }
8196 }
8197 mPendingPackages.clear();
8198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008199 mReadMessages.append("Read completed successfully: "
8200 + mPackages.size() + " packages, "
8201 + mSharedUsers.size() + " shared uids\n");
8202
8203 return true;
8204 }
8205
8206 private int readInt(XmlPullParser parser, String ns, String name,
8207 int defValue) {
8208 String v = parser.getAttributeValue(ns, name);
8209 try {
8210 if (v == null) {
8211 return defValue;
8212 }
8213 return Integer.parseInt(v);
8214 } catch (NumberFormatException e) {
8215 reportSettingsProblem(Log.WARN,
8216 "Error in package manager settings: attribute " +
8217 name + " has bad integer value " + v + " at "
8218 + parser.getPositionDescription());
8219 }
8220 return defValue;
8221 }
8222
8223 private void readPermissionsLP(HashMap<String, BasePermission> out,
8224 XmlPullParser parser)
8225 throws IOException, XmlPullParserException {
8226 int outerDepth = parser.getDepth();
8227 int type;
8228 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8229 && (type != XmlPullParser.END_TAG
8230 || parser.getDepth() > outerDepth)) {
8231 if (type == XmlPullParser.END_TAG
8232 || type == XmlPullParser.TEXT) {
8233 continue;
8234 }
8235
8236 String tagName = parser.getName();
8237 if (tagName.equals("item")) {
8238 String name = parser.getAttributeValue(null, "name");
8239 String sourcePackage = parser.getAttributeValue(null, "package");
8240 String ptype = parser.getAttributeValue(null, "type");
8241 if (name != null && sourcePackage != null) {
8242 boolean dynamic = "dynamic".equals(ptype);
8243 BasePermission bp = new BasePermission(name, sourcePackage,
8244 dynamic
8245 ? BasePermission.TYPE_DYNAMIC
8246 : BasePermission.TYPE_NORMAL);
8247 if (dynamic) {
8248 PermissionInfo pi = new PermissionInfo();
8249 pi.packageName = sourcePackage.intern();
8250 pi.name = name.intern();
8251 pi.icon = readInt(parser, null, "icon", 0);
8252 pi.nonLocalizedLabel = parser.getAttributeValue(
8253 null, "label");
8254 pi.protectionLevel = readInt(parser, null, "protection",
8255 PermissionInfo.PROTECTION_NORMAL);
8256 bp.pendingInfo = pi;
8257 }
8258 out.put(bp.name, bp);
8259 } else {
8260 reportSettingsProblem(Log.WARN,
8261 "Error in package manager settings: permissions has"
8262 + " no name at " + parser.getPositionDescription());
8263 }
8264 } else {
8265 reportSettingsProblem(Log.WARN,
8266 "Unknown element reading permissions: "
8267 + parser.getName() + " at "
8268 + parser.getPositionDescription());
8269 }
8270 XmlUtils.skipCurrentTag(parser);
8271 }
8272 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008274 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008275 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008277 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008278 String codePathStr = parser.getAttributeValue(null, "codePath");
8279 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008280 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008281 resourcePathStr = codePathStr;
8282 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008283 String version = parser.getAttributeValue(null, "version");
8284 int versionCode = 0;
8285 if (version != null) {
8286 try {
8287 versionCode = Integer.parseInt(version);
8288 } catch (NumberFormatException e) {
8289 }
8290 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008292 int pkgFlags = 0;
8293 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008294 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008295 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008296 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008297 String timeStampStr = parser.getAttributeValue(null, "ts");
8298 if (timeStampStr != null) {
8299 try {
8300 long timeStamp = Long.parseLong(timeStampStr);
8301 ps.setTimeStamp(timeStamp, timeStampStr);
8302 } catch (NumberFormatException e) {
8303 }
8304 }
8305 String idStr = parser.getAttributeValue(null, "userId");
8306 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8307 if(ps.userId <= 0) {
8308 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8309 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8310 }
8311 int outerDepth = parser.getDepth();
8312 int type;
8313 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8314 && (type != XmlPullParser.END_TAG
8315 || parser.getDepth() > outerDepth)) {
8316 if (type == XmlPullParser.END_TAG
8317 || type == XmlPullParser.TEXT) {
8318 continue;
8319 }
8320
8321 String tagName = parser.getName();
8322 if (tagName.equals("perms")) {
8323 readGrantedPermissionsLP(parser,
8324 ps.grantedPermissions);
8325 } else {
8326 reportSettingsProblem(Log.WARN,
8327 "Unknown element under <updated-package>: "
8328 + parser.getName());
8329 XmlUtils.skipCurrentTag(parser);
8330 }
8331 }
8332 mDisabledSysPackages.put(name, ps);
8333 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008335 private void readPackageLP(XmlPullParser parser)
8336 throws XmlPullParserException, IOException {
8337 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008338 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 String idStr = null;
8340 String sharedIdStr = null;
8341 String codePathStr = null;
8342 String resourcePathStr = null;
8343 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008344 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008345 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 int pkgFlags = 0;
8347 String timeStampStr;
8348 long timeStamp = 0;
8349 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008350 String version = null;
8351 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 try {
8353 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008354 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008355 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008356 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008357 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8358 codePathStr = parser.getAttributeValue(null, "codePath");
8359 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008360 version = parser.getAttributeValue(null, "version");
8361 if (version != null) {
8362 try {
8363 versionCode = Integer.parseInt(version);
8364 } catch (NumberFormatException e) {
8365 }
8366 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008367 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008368
8369 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008370 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008371 try {
8372 pkgFlags = Integer.parseInt(systemStr);
8373 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008374 }
8375 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008376 // For backward compatibility
8377 systemStr = parser.getAttributeValue(null, "system");
8378 if (systemStr != null) {
8379 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8380 } else {
8381 // Old settings that don't specify system... just treat
8382 // them as system, good enough.
8383 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008385 }
8386 timeStampStr = parser.getAttributeValue(null, "ts");
8387 if (timeStampStr != null) {
8388 try {
8389 timeStamp = Long.parseLong(timeStampStr);
8390 } catch (NumberFormatException e) {
8391 }
8392 }
8393 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8394 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8395 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8396 if (resourcePathStr == null) {
8397 resourcePathStr = codePathStr;
8398 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008399 if (realName != null) {
8400 realName = realName.intern();
8401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008402 if (name == null) {
8403 reportSettingsProblem(Log.WARN,
8404 "Error in package manager settings: <package> has no name at "
8405 + parser.getPositionDescription());
8406 } else if (codePathStr == null) {
8407 reportSettingsProblem(Log.WARN,
8408 "Error in package manager settings: <package> has no codePath at "
8409 + parser.getPositionDescription());
8410 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008411 packageSetting = addPackageLP(name.intern(), realName,
8412 new File(codePathStr), new File(resourcePathStr),
8413 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8415 + ": userId=" + userId + " pkg=" + packageSetting);
8416 if (packageSetting == null) {
8417 reportSettingsProblem(Log.ERROR,
8418 "Failure adding uid " + userId
8419 + " while parsing settings at "
8420 + parser.getPositionDescription());
8421 } else {
8422 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8423 }
8424 } else if (sharedIdStr != null) {
8425 userId = sharedIdStr != null
8426 ? Integer.parseInt(sharedIdStr) : 0;
8427 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008428 packageSetting = new PendingPackage(name.intern(), realName,
8429 new File(codePathStr), new File(resourcePathStr),
8430 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008431 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8432 mPendingPackages.add((PendingPackage) packageSetting);
8433 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8434 + ": sharedUserId=" + userId + " pkg="
8435 + packageSetting);
8436 } else {
8437 reportSettingsProblem(Log.WARN,
8438 "Error in package manager settings: package "
8439 + name + " has bad sharedId " + sharedIdStr
8440 + " at " + parser.getPositionDescription());
8441 }
8442 } else {
8443 reportSettingsProblem(Log.WARN,
8444 "Error in package manager settings: package "
8445 + name + " has bad userId " + idStr + " at "
8446 + parser.getPositionDescription());
8447 }
8448 } catch (NumberFormatException e) {
8449 reportSettingsProblem(Log.WARN,
8450 "Error in package manager settings: package "
8451 + name + " has bad userId " + idStr + " at "
8452 + parser.getPositionDescription());
8453 }
8454 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008455 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008456 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008457 final String enabledStr = parser.getAttributeValue(null, "enabled");
8458 if (enabledStr != null) {
8459 if (enabledStr.equalsIgnoreCase("true")) {
8460 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8461 } else if (enabledStr.equalsIgnoreCase("false")) {
8462 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8463 } else if (enabledStr.equalsIgnoreCase("default")) {
8464 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8465 } else {
8466 reportSettingsProblem(Log.WARN,
8467 "Error in package manager settings: package "
8468 + name + " has bad enabled value: " + idStr
8469 + " at " + parser.getPositionDescription());
8470 }
8471 } else {
8472 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8473 }
8474 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8475 if (installStatusStr != null) {
8476 if (installStatusStr.equalsIgnoreCase("false")) {
8477 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8478 } else {
8479 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8480 }
8481 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483 int outerDepth = parser.getDepth();
8484 int type;
8485 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8486 && (type != XmlPullParser.END_TAG
8487 || parser.getDepth() > outerDepth)) {
8488 if (type == XmlPullParser.END_TAG
8489 || type == XmlPullParser.TEXT) {
8490 continue;
8491 }
8492
8493 String tagName = parser.getName();
8494 if (tagName.equals("disabled-components")) {
8495 readDisabledComponentsLP(packageSetting, parser);
8496 } else if (tagName.equals("enabled-components")) {
8497 readEnabledComponentsLP(packageSetting, parser);
8498 } else if (tagName.equals("sigs")) {
8499 packageSetting.signatures.readXml(parser, mPastSignatures);
8500 } else if (tagName.equals("perms")) {
8501 readGrantedPermissionsLP(parser,
8502 packageSetting.loadedPermissions);
8503 packageSetting.permissionsFixed = true;
8504 } else {
8505 reportSettingsProblem(Log.WARN,
8506 "Unknown element under <package>: "
8507 + parser.getName());
8508 XmlUtils.skipCurrentTag(parser);
8509 }
8510 }
8511 } else {
8512 XmlUtils.skipCurrentTag(parser);
8513 }
8514 }
8515
8516 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8517 XmlPullParser parser)
8518 throws IOException, XmlPullParserException {
8519 int outerDepth = parser.getDepth();
8520 int type;
8521 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8522 && (type != XmlPullParser.END_TAG
8523 || parser.getDepth() > outerDepth)) {
8524 if (type == XmlPullParser.END_TAG
8525 || type == XmlPullParser.TEXT) {
8526 continue;
8527 }
8528
8529 String tagName = parser.getName();
8530 if (tagName.equals("item")) {
8531 String name = parser.getAttributeValue(null, "name");
8532 if (name != null) {
8533 packageSetting.disabledComponents.add(name.intern());
8534 } else {
8535 reportSettingsProblem(Log.WARN,
8536 "Error in package manager settings: <disabled-components> has"
8537 + " no name at " + parser.getPositionDescription());
8538 }
8539 } else {
8540 reportSettingsProblem(Log.WARN,
8541 "Unknown element under <disabled-components>: "
8542 + parser.getName());
8543 }
8544 XmlUtils.skipCurrentTag(parser);
8545 }
8546 }
8547
8548 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8549 XmlPullParser parser)
8550 throws IOException, XmlPullParserException {
8551 int outerDepth = parser.getDepth();
8552 int type;
8553 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8554 && (type != XmlPullParser.END_TAG
8555 || parser.getDepth() > outerDepth)) {
8556 if (type == XmlPullParser.END_TAG
8557 || type == XmlPullParser.TEXT) {
8558 continue;
8559 }
8560
8561 String tagName = parser.getName();
8562 if (tagName.equals("item")) {
8563 String name = parser.getAttributeValue(null, "name");
8564 if (name != null) {
8565 packageSetting.enabledComponents.add(name.intern());
8566 } else {
8567 reportSettingsProblem(Log.WARN,
8568 "Error in package manager settings: <enabled-components> has"
8569 + " no name at " + parser.getPositionDescription());
8570 }
8571 } else {
8572 reportSettingsProblem(Log.WARN,
8573 "Unknown element under <enabled-components>: "
8574 + parser.getName());
8575 }
8576 XmlUtils.skipCurrentTag(parser);
8577 }
8578 }
8579
8580 private void readSharedUserLP(XmlPullParser parser)
8581 throws XmlPullParserException, IOException {
8582 String name = null;
8583 String idStr = null;
8584 int pkgFlags = 0;
8585 SharedUserSetting su = null;
8586 try {
8587 name = parser.getAttributeValue(null, "name");
8588 idStr = parser.getAttributeValue(null, "userId");
8589 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8590 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8591 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8592 }
8593 if (name == null) {
8594 reportSettingsProblem(Log.WARN,
8595 "Error in package manager settings: <shared-user> has no name at "
8596 + parser.getPositionDescription());
8597 } else if (userId == 0) {
8598 reportSettingsProblem(Log.WARN,
8599 "Error in package manager settings: shared-user "
8600 + name + " has bad userId " + idStr + " at "
8601 + parser.getPositionDescription());
8602 } else {
8603 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8604 reportSettingsProblem(Log.ERROR,
8605 "Occurred while parsing settings at "
8606 + parser.getPositionDescription());
8607 }
8608 }
8609 } catch (NumberFormatException e) {
8610 reportSettingsProblem(Log.WARN,
8611 "Error in package manager settings: package "
8612 + name + " has bad userId " + idStr + " at "
8613 + parser.getPositionDescription());
8614 };
8615
8616 if (su != null) {
8617 int outerDepth = parser.getDepth();
8618 int type;
8619 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8620 && (type != XmlPullParser.END_TAG
8621 || parser.getDepth() > outerDepth)) {
8622 if (type == XmlPullParser.END_TAG
8623 || type == XmlPullParser.TEXT) {
8624 continue;
8625 }
8626
8627 String tagName = parser.getName();
8628 if (tagName.equals("sigs")) {
8629 su.signatures.readXml(parser, mPastSignatures);
8630 } else if (tagName.equals("perms")) {
8631 readGrantedPermissionsLP(parser, su.loadedPermissions);
8632 } else {
8633 reportSettingsProblem(Log.WARN,
8634 "Unknown element under <shared-user>: "
8635 + parser.getName());
8636 XmlUtils.skipCurrentTag(parser);
8637 }
8638 }
8639
8640 } else {
8641 XmlUtils.skipCurrentTag(parser);
8642 }
8643 }
8644
8645 private void readGrantedPermissionsLP(XmlPullParser parser,
8646 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8647 int outerDepth = parser.getDepth();
8648 int type;
8649 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8650 && (type != XmlPullParser.END_TAG
8651 || parser.getDepth() > outerDepth)) {
8652 if (type == XmlPullParser.END_TAG
8653 || type == XmlPullParser.TEXT) {
8654 continue;
8655 }
8656
8657 String tagName = parser.getName();
8658 if (tagName.equals("item")) {
8659 String name = parser.getAttributeValue(null, "name");
8660 if (name != null) {
8661 outPerms.add(name.intern());
8662 } else {
8663 reportSettingsProblem(Log.WARN,
8664 "Error in package manager settings: <perms> has"
8665 + " no name at " + parser.getPositionDescription());
8666 }
8667 } else {
8668 reportSettingsProblem(Log.WARN,
8669 "Unknown element under <perms>: "
8670 + parser.getName());
8671 }
8672 XmlUtils.skipCurrentTag(parser);
8673 }
8674 }
8675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008676 private void readPreferredActivitiesLP(XmlPullParser parser)
8677 throws XmlPullParserException, IOException {
8678 int outerDepth = parser.getDepth();
8679 int type;
8680 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8681 && (type != XmlPullParser.END_TAG
8682 || parser.getDepth() > outerDepth)) {
8683 if (type == XmlPullParser.END_TAG
8684 || type == XmlPullParser.TEXT) {
8685 continue;
8686 }
8687
8688 String tagName = parser.getName();
8689 if (tagName.equals("item")) {
8690 PreferredActivity pa = new PreferredActivity(parser);
8691 if (pa.mParseError == null) {
8692 mPreferredActivities.addFilter(pa);
8693 } else {
8694 reportSettingsProblem(Log.WARN,
8695 "Error in package manager settings: <preferred-activity> "
8696 + pa.mParseError + " at "
8697 + parser.getPositionDescription());
8698 }
8699 } else {
8700 reportSettingsProblem(Log.WARN,
8701 "Unknown element under <preferred-activities>: "
8702 + parser.getName());
8703 XmlUtils.skipCurrentTag(parser);
8704 }
8705 }
8706 }
8707
8708 // Returns -1 if we could not find an available UserId to assign
8709 private int newUserIdLP(Object obj) {
8710 // Let's be stupidly inefficient for now...
8711 final int N = mUserIds.size();
8712 for (int i=0; i<N; i++) {
8713 if (mUserIds.get(i) == null) {
8714 mUserIds.set(i, obj);
8715 return FIRST_APPLICATION_UID + i;
8716 }
8717 }
8718
8719 // None left?
8720 if (N >= MAX_APPLICATION_UIDS) {
8721 return -1;
8722 }
8723
8724 mUserIds.add(obj);
8725 return FIRST_APPLICATION_UID + N;
8726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728 public PackageSetting getDisabledSystemPkg(String name) {
8729 synchronized(mPackages) {
8730 PackageSetting ps = mDisabledSysPackages.get(name);
8731 return ps;
8732 }
8733 }
8734
8735 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8736 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8737 if (Config.LOGV) {
8738 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8739 + " componentName = " + componentInfo.name);
8740 Log.v(TAG, "enabledComponents: "
8741 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8742 Log.v(TAG, "disabledComponents: "
8743 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8744 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008745 if (packageSettings == null) {
8746 if (false) {
8747 Log.w(TAG, "WAITING FOR DEBUGGER");
8748 Debug.waitForDebugger();
8749 Log.i(TAG, "We will crash!");
8750 }
8751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8753 || ((componentInfo.enabled
8754 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8755 || (componentInfo.applicationInfo.enabled
8756 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8757 && !packageSettings.disabledComponents.contains(componentInfo.name))
8758 || packageSettings.enabledComponents.contains(componentInfo.name));
8759 }
8760 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008761
8762 // ------- apps on sdcard specific code -------
8763 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008764 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008765 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008766 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008767 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008768
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008769 private String getEncryptKey() {
8770 try {
8771 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8772 if (sdEncKey == null) {
8773 sdEncKey = SystemKeyStore.getInstance().
8774 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8775 if (sdEncKey == null) {
8776 Log.e(TAG, "Failed to create encryption keys");
8777 return null;
8778 }
8779 }
8780 return sdEncKey;
8781 } catch (NoSuchAlgorithmException nsae) {
8782 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8783 return null;
8784 }
8785 }
8786
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008787 static String getTempContainerId() {
8788 String prefix = "smdl1tmp";
8789 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008790 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008791 if (list != null) {
8792 int idx = 0;
8793 int idList[] = new int[MAX_CONTAINERS];
8794 boolean neverFound = true;
8795 for (String name : list) {
8796 // Ignore null entries
8797 if (name == null) {
8798 continue;
8799 }
8800 int sidx = name.indexOf(prefix);
8801 if (sidx == -1) {
8802 // Not a temp file. just ignore
8803 continue;
8804 }
8805 String subStr = name.substring(sidx + prefix.length());
8806 idList[idx] = -1;
8807 if (subStr != null) {
8808 try {
8809 int cid = Integer.parseInt(subStr);
8810 idList[idx++] = cid;
8811 neverFound = false;
8812 } catch (NumberFormatException e) {
8813 }
8814 }
8815 }
8816 if (!neverFound) {
8817 // Sort idList
8818 Arrays.sort(idList);
8819 for (int j = 1; j <= idList.length; j++) {
8820 if (idList[j-1] != j) {
8821 tmpIdx = j;
8822 break;
8823 }
8824 }
8825 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008826 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008827 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008828 }
8829
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008830 public void updateExternalMediaStatus(final boolean mediaStatus) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008831 synchronized (mPackages) {
8832 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8833 mediaStatus+", mMediaMounted=" + mMediaMounted);
8834 if (mediaStatus == mMediaMounted) {
8835 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008836 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008837 mMediaMounted = mediaStatus;
8838 // Queue up an async operation since the package installation may take a little while.
8839 mHandler.post(new Runnable() {
8840 public void run() {
8841 mHandler.removeCallbacks(this);
8842 updateExternalMediaStatusInner(mediaStatus);
8843 }
8844 });
8845 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008846 }
8847
8848 void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008849 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008850 if (list == null || list.length == 0) {
8851 return;
8852 }
8853 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8854 int uidList[] = new int[list.length];
8855 int num = 0;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008856 synchronized (mPackages) {
8857 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8858 for (String cid : list) {
8859 SdInstallArgs args = new SdInstallArgs(cid);
8860 String removeEntry = null;
8861 for (String app : appList) {
8862 if (args.matchContainer(app)) {
8863 removeEntry = app;
8864 break;
8865 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008866 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008867 if (removeEntry == null) {
8868 // No matching app on device. Skip entry or may be cleanup?
8869 // Ignore default package
8870 continue;
8871 }
8872 appList.remove(removeEntry);
8873 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8874 processCids.put(args, ps.codePathString);
8875 int uid = ps.userId;
8876 if (uid != -1) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008877 uidList[num++] = uid;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008878 }
8879 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008880 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008881 int uidArr[] = null;
8882 if (num > 0) {
8883 // Sort uid list
8884 Arrays.sort(uidList, 0, num);
8885 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008886 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008887 uidArr[0] = uidList[0];
8888 int di = 0;
8889 for (int i = 1; i < num; i++) {
8890 if (uidList[i-1] != uidList[i]) {
8891 uidArr[di++] = uidList[i];
8892 }
8893 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008894 }
8895 if (mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008896 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008897 loadMediaPackages(processCids, uidArr);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008898 startCleaningPackages();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008899 } else {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008900 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008901 unloadMediaPackages(processCids, uidArr);
8902 }
8903 }
8904
8905 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8906 ArrayList<String> pkgList, int uidArr[]) {
8907 int size = pkgList.size();
8908 if (size > 0) {
8909 // Send broadcasts here
8910 Bundle extras = new Bundle();
8911 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8912 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008913 if (uidArr != null) {
8914 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8915 }
8916 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8917 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008918 sendPackageBroadcast(action, null, extras);
8919 }
8920 }
8921
8922 void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8923 ArrayList<String> pkgList = new ArrayList<String>();
8924 Set<SdInstallArgs> keys = processCids.keySet();
8925 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008926 String codePath = processCids.get(args);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008927 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install pkg : "
8928 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008929 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008930 Log.e(TAG, "Failed to install package: " + codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008931 continue;
8932 }
8933 // Parse package
8934 int parseFlags = PackageParser.PARSE_CHATTY |
8935 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8936 PackageParser pp = new PackageParser(codePath);
8937 pp.setSeparateProcesses(mSeparateProcesses);
8938 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
8939 codePath, mMetrics, parseFlags);
8940 if (pkg == null) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008941 Log.e(TAG, "Trying to install pkg : "
8942 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008943 continue;
8944 }
8945 setApplicationInfoPaths(pkg, codePath, codePath);
8946 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8947 synchronized (mInstallLock) {
8948 // Scan the package
8949 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
8950 synchronized (mPackages) {
8951 // Grant permissions
8952 grantPermissionsLP(pkg, false);
8953 // Persist settings
8954 mSettings.writeLP();
8955 retCode = PackageManager.INSTALL_SUCCEEDED;
8956 pkgList.add(pkg.packageName);
8957 }
8958 } else {
8959 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
8960 }
8961 }
8962 args.doPostInstall(retCode);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008963 }
8964 // Send broadcasts first
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008965 if (pkgList.size() > 0) {
8966 sendResourcesChangedBroadcast(true, pkgList, uidArr);
8967 Runtime.getRuntime().gc();
8968 // If something failed do we clean up here or next install?
8969 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008970 }
8971
8972 void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008973 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008974 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008975 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008976 Set<SdInstallArgs> keys = processCids.keySet();
8977 for (SdInstallArgs args : keys) {
8978 String cid = args.cid;
8979 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008980 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008981 // Delete package internally
8982 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8983 synchronized (mInstallLock) {
8984 boolean res = deletePackageLI(pkgName, false,
8985 PackageManager.DONT_DELETE_DATA, outInfo);
8986 if (res) {
8987 pkgList.add(pkgName);
8988 } else {
8989 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008990 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008991 }
8992 }
8993 }
8994 // Send broadcasts
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008995 if (pkgList.size() > 0) {
8996 sendResourcesChangedBroadcast(false, pkgList, uidArr);
8997 Runtime.getRuntime().gc();
8998 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008999 // Do clean up. Just unmount
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009000 for (SdInstallArgs args : failedList) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009001 synchronized (mInstallLock) {
9002 args.doPostDeleteLI(false);
9003 }
9004 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009005 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009006
9007 public void movePackage(final String packageName,
9008 final IPackageMoveObserver observer, final int flags) {
9009 if (packageName == null) {
9010 return;
9011 }
9012 mContext.enforceCallingOrSelfPermission(
9013 android.Manifest.permission.MOVE_PACKAGE, null);
9014 int returnCode = PackageManager.MOVE_SUCCEEDED;
9015 int currFlags = 0;
9016 int newFlags = 0;
9017 synchronized (mPackages) {
9018 PackageParser.Package pkg = mPackages.get(packageName);
9019 if (pkg == null) {
9020 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9021 }
9022 // Disable moving fwd locked apps and system packages
9023 if (pkg.applicationInfo != null &&
9024 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9025 Log.w(TAG, "Cannot move system application");
9026 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9027 } else if (pkg.applicationInfo != null &&
9028 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9029 Log.w(TAG, "Cannot move forward locked app.");
9030 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9031 } else {
9032 // Find install location first
9033 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9034 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9035 Log.w(TAG, "Ambigous flags specified for move location.");
9036 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9037 } else {
9038 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9039 PackageManager.INSTALL_EXTERNAL : 0;
9040 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0 ?
9041 PackageManager.INSTALL_EXTERNAL : 0;
9042 if (newFlags == currFlags) {
9043 Log.w(TAG, "No move required. Trying to move to same location");
9044 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9045 }
9046 }
9047 }
9048 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9049 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9050 } else {
9051 Message msg = mHandler.obtainMessage(INIT_COPY);
9052 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9053 pkg.applicationInfo.publicSourceDir);
9054 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9055 packageName);
9056 msg.obj = mp;
9057 mHandler.sendMessage(msg);
9058 }
9059 }
9060 }
9061
9062 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9063 // Queue up an async operation since the package deletion may take a little while.
9064 mHandler.post(new Runnable() {
9065 public void run() {
9066 mHandler.removeCallbacks(this);
9067 int returnCode = currentStatus;
9068 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9069 if (moveSucceeded) {
9070 int uid = -1;
9071 synchronized (mPackages) {
9072 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9073 }
9074 ArrayList<String> pkgList = new ArrayList<String>();
9075 pkgList.add(mp.packageName);
9076 int uidArr[] = new int[] { uid };
9077 // Send resources unavailable broadcast
9078 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9079
9080 // Update package code and resource paths
9081 synchronized (mPackages) {
9082 PackageParser.Package pkg = mPackages.get(mp.packageName);
9083 if (pkg != null) {
9084 String oldCodePath = pkg.mPath;
9085 String newCodePath = mp.targetArgs.getCodePath();
9086 String newResPath = mp.targetArgs.getResourcePath();
9087 pkg.mPath = newCodePath;
9088 // Move dex files around
9089 if (moveDexFiles(pkg)
9090 != PackageManager.INSTALL_SUCCEEDED) {
9091 // Moving of dex files failed. Set
9092 // error code and abort move.
9093 pkg.mPath = pkg.mScanPath;
9094 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9095 moveSucceeded = false;
9096 } else {
9097 pkg.mScanPath = newCodePath;
9098 pkg.applicationInfo.sourceDir = newCodePath;
9099 pkg.applicationInfo.publicSourceDir = newResPath;
9100 PackageSetting ps = (PackageSetting) pkg.mExtras;
9101 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9102 ps.codePathString = ps.codePath.getPath();
9103 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9104 ps.resourcePathString = ps.resourcePath.getPath();
9105 // Set the application info flag correctly.
9106 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9107 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_ON_SDCARD;
9108 } else {
9109 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_ON_SDCARD;
9110 }
9111 ps.setFlags(pkg.applicationInfo.flags);
9112 mAppDirs.remove(oldCodePath);
9113 mAppDirs.put(newCodePath, pkg);
9114 // Persist settings
9115 mSettings.writeLP();
9116 }
9117 }
9118 }
9119 if (moveSucceeded) {
9120 // Delete older code
9121 synchronized (mInstallLock) {
9122 mp.srcArgs.cleanUpResourcesLI();
9123 }
9124 // Send resources available broadcast
9125 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9126 Runtime.getRuntime().gc();
9127 }
9128 }
9129 if (!moveSucceeded){
9130 // Clean up failed installation
9131 if (mp.targetArgs != null) {
9132 mp.targetArgs.doPostInstall(
9133 PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
9134 }
9135 }
9136 IPackageMoveObserver observer = mp.observer;
9137 if (observer != null) {
9138 try {
9139 observer.packageMoved(mp.packageName, returnCode);
9140 } catch (RemoteException e) {
9141 Log.i(TAG, "Observer no longer exists.");
9142 }
9143 }
9144 }
9145 });
9146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147}