ContextImpl.java revision 9630704ed3b265f008a8f64ec60a33cf9dcd3345
1/*
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 android.app;
18
19import com.android.internal.policy.PolicyManager;
20
21import android.bluetooth.BluetoothAdapter;
22import android.content.BroadcastReceiver;
23import android.content.ComponentName;
24import android.content.ContentResolver;
25import android.content.Context;
26import android.content.ContextWrapper;
27import android.content.IContentProvider;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.IIntentReceiver;
31import android.content.IntentSender;
32import android.content.ReceiverCallNotAllowedException;
33import android.content.ServiceConnection;
34import android.content.SharedPreferences;
35import android.content.pm.ApplicationInfo;
36import android.content.pm.IPackageManager;
37import android.content.pm.PackageManager;
38import android.content.res.AssetManager;
39import android.content.res.CompatibilityInfo;
40import android.content.res.Configuration;
41import android.content.res.Resources;
42import android.database.DatabaseErrorHandler;
43import android.database.sqlite.SQLiteDatabase;
44import android.database.sqlite.SQLiteDatabase.CursorFactory;
45import android.graphics.Bitmap;
46import android.graphics.drawable.Drawable;
47import android.hardware.ISerialManager;
48import android.hardware.SensorManager;
49import android.hardware.SerialManager;
50import android.hardware.SystemSensorManager;
51import android.hardware.display.DisplayManager;
52import android.hardware.input.IInputManager;
53import android.hardware.input.InputManager;
54import android.hardware.usb.IUsbManager;
55import android.hardware.usb.UsbManager;
56import android.location.CountryDetector;
57import android.location.ICountryDetector;
58import android.location.ILocationManager;
59import android.location.LocationManager;
60import android.media.AudioManager;
61import android.media.MediaRouter;
62import android.net.ConnectivityManager;
63import android.net.IConnectivityManager;
64import android.net.INetworkPolicyManager;
65import android.net.NetworkPolicyManager;
66import android.net.ThrottleManager;
67import android.net.IThrottleManager;
68import android.net.Uri;
69import android.net.nsd.INsdManager;
70import android.net.nsd.NsdManager;
71import android.net.wifi.IWifiManager;
72import android.net.wifi.WifiManager;
73import android.net.wifi.p2p.IWifiP2pManager;
74import android.net.wifi.p2p.WifiP2pManager;
75import android.nfc.NfcManager;
76import android.os.Binder;
77import android.os.Bundle;
78import android.os.DropBoxManager;
79import android.os.Environment;
80import android.os.FileUtils;
81import android.os.Handler;
82import android.os.IBinder;
83import android.os.IPowerManager;
84import android.os.IUserManager;
85import android.os.Looper;
86import android.os.PowerManager;
87import android.os.Process;
88import android.os.RemoteException;
89import android.os.ServiceManager;
90import android.os.UserId;
91import android.os.SystemVibrator;
92import android.os.UserManager;
93import android.os.storage.StorageManager;
94import android.telephony.TelephonyManager;
95import android.content.ClipboardManager;
96import android.util.AndroidRuntimeException;
97import android.util.Log;
98import android.view.ContextThemeWrapper;
99import android.view.WindowManagerImpl;
100import android.view.accessibility.AccessibilityManager;
101import android.view.inputmethod.InputMethodManager;
102import android.view.textservice.TextServicesManager;
103import android.accounts.AccountManager;
104import android.accounts.IAccountManager;
105import android.app.admin.DevicePolicyManager;
106import com.android.internal.os.IDropBoxManagerService;
107
108import java.io.File;
109import java.io.FileInputStream;
110import java.io.FileNotFoundException;
111import java.io.FileOutputStream;
112import java.io.IOException;
113import java.io.InputStream;
114import java.util.ArrayList;
115import java.util.HashMap;
116
117class ReceiverRestrictedContext extends ContextWrapper {
118    ReceiverRestrictedContext(Context base) {
119        super(base);
120    }
121
122    @Override
123    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
124        return registerReceiver(receiver, filter, null, null);
125    }
126
127    @Override
128    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
129            String broadcastPermission, Handler scheduler) {
130        throw new ReceiverCallNotAllowedException(
131                "IntentReceiver components are not allowed to register to receive intents");
132        //ex.fillInStackTrace();
133        //Log.e("IntentReceiver", ex.getMessage(), ex);
134        //return mContext.registerReceiver(receiver, filter, broadcastPermission,
135        //        scheduler);
136    }
137
138    @Override
139    public boolean bindService(Intent service, ServiceConnection conn, int flags) {
140        throw new ReceiverCallNotAllowedException(
141                "IntentReceiver components are not allowed to bind to services");
142        //ex.fillInStackTrace();
143        //Log.e("IntentReceiver", ex.getMessage(), ex);
144        //return mContext.bindService(service, interfaceName, conn, flags);
145    }
146}
147
148/**
149 * Common implementation of Context API, which provides the base
150 * context object for Activity and other application components.
151 */
152class ContextImpl extends Context {
153    private final static String TAG = "ApplicationContext";
154    private final static boolean DEBUG = false;
155
156    private static final HashMap<String, SharedPreferencesImpl> sSharedPrefs =
157            new HashMap<String, SharedPreferencesImpl>();
158
159    /*package*/ LoadedApk mPackageInfo;
160    private String mBasePackageName;
161    private Resources mResources;
162    /*package*/ ActivityThread mMainThread;
163    private Context mOuterContext;
164    private IBinder mActivityToken = null;
165    private ApplicationContentResolver mContentResolver;
166    private int mThemeResource = 0;
167    private Resources.Theme mTheme = null;
168    private PackageManager mPackageManager;
169    private Context mReceiverRestrictedContext = null;
170    private boolean mRestricted;
171
172    private final Object mSync = new Object();
173
174    private File mDatabasesDir;
175    private File mPreferencesDir;
176    private File mFilesDir;
177    private File mCacheDir;
178    private File mObbDir;
179    private File mExternalFilesDir;
180    private File mExternalCacheDir;
181
182    private static final String[] EMPTY_FILE_LIST = {};
183
184    /**
185     * Override this class when the system service constructor needs a
186     * ContextImpl.  Else, use StaticServiceFetcher below.
187     */
188    /*package*/ static class ServiceFetcher {
189        int mContextCacheIndex = -1;
190
191        /**
192         * Main entrypoint; only override if you don't need caching.
193         */
194        public Object getService(ContextImpl ctx) {
195            ArrayList<Object> cache = ctx.mServiceCache;
196            Object service;
197            synchronized (cache) {
198                if (cache.size() == 0) {
199                    // Initialize the cache vector on first access.
200                    // At this point sNextPerContextServiceCacheIndex
201                    // is the number of potential services that are
202                    // cached per-Context.
203                    for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) {
204                        cache.add(null);
205                    }
206                } else {
207                    service = cache.get(mContextCacheIndex);
208                    if (service != null) {
209                        return service;
210                    }
211                }
212                service = createService(ctx);
213                cache.set(mContextCacheIndex, service);
214                return service;
215            }
216        }
217
218        /**
219         * Override this to create a new per-Context instance of the
220         * service.  getService() will handle locking and caching.
221         */
222        public Object createService(ContextImpl ctx) {
223            throw new RuntimeException("Not implemented");
224        }
225    }
226
227    /**
228     * Override this class for services to be cached process-wide.
229     */
230    abstract static class StaticServiceFetcher extends ServiceFetcher {
231        private Object mCachedInstance;
232
233        @Override
234        public final Object getService(ContextImpl unused) {
235            synchronized (StaticServiceFetcher.this) {
236                Object service = mCachedInstance;
237                if (service != null) {
238                    return service;
239                }
240                return mCachedInstance = createStaticService();
241            }
242        }
243
244        public abstract Object createStaticService();
245    }
246
247    private static final HashMap<String, ServiceFetcher> SYSTEM_SERVICE_MAP =
248            new HashMap<String, ServiceFetcher>();
249
250    private static int sNextPerContextServiceCacheIndex = 0;
251    private static void registerService(String serviceName, ServiceFetcher fetcher) {
252        if (!(fetcher instanceof StaticServiceFetcher)) {
253            fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++;
254        }
255        SYSTEM_SERVICE_MAP.put(serviceName, fetcher);
256    }
257
258    // This one's defined separately and given a variable name so it
259    // can be re-used by getWallpaperManager(), avoiding a HashMap
260    // lookup.
261    private static ServiceFetcher WALLPAPER_FETCHER = new ServiceFetcher() {
262            public Object createService(ContextImpl ctx) {
263                return new WallpaperManager(ctx.getOuterContext(),
264                        ctx.mMainThread.getHandler());
265            }};
266
267    static {
268        registerService(ACCESSIBILITY_SERVICE, new ServiceFetcher() {
269                public Object getService(ContextImpl ctx) {
270                    return AccessibilityManager.getInstance(ctx);
271                }});
272
273        registerService(ACCOUNT_SERVICE, new ServiceFetcher() {
274                public Object createService(ContextImpl ctx) {
275                    IBinder b = ServiceManager.getService(ACCOUNT_SERVICE);
276                    IAccountManager service = IAccountManager.Stub.asInterface(b);
277                    return new AccountManager(ctx, service);
278                }});
279
280        registerService(ACTIVITY_SERVICE, new ServiceFetcher() {
281                public Object createService(ContextImpl ctx) {
282                    return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
283                }});
284
285        registerService(ALARM_SERVICE, new StaticServiceFetcher() {
286                public Object createStaticService() {
287                    IBinder b = ServiceManager.getService(ALARM_SERVICE);
288                    IAlarmManager service = IAlarmManager.Stub.asInterface(b);
289                    return new AlarmManager(service);
290                }});
291
292        registerService(AUDIO_SERVICE, new ServiceFetcher() {
293                public Object createService(ContextImpl ctx) {
294                    return new AudioManager(ctx);
295                }});
296
297        registerService(MEDIA_ROUTER_SERVICE, new ServiceFetcher() {
298                public Object createService(ContextImpl ctx) {
299                    return new MediaRouter(ctx);
300                }});
301
302        registerService(BLUETOOTH_SERVICE, new ServiceFetcher() {
303                public Object createService(ContextImpl ctx) {
304                    return BluetoothAdapter.getDefaultAdapter();
305                }});
306
307        registerService(CLIPBOARD_SERVICE, new ServiceFetcher() {
308                public Object createService(ContextImpl ctx) {
309                    return new ClipboardManager(ctx.getOuterContext(),
310                            ctx.mMainThread.getHandler());
311                }});
312
313        registerService(CONNECTIVITY_SERVICE, new StaticServiceFetcher() {
314                public Object createStaticService() {
315                    IBinder b = ServiceManager.getService(CONNECTIVITY_SERVICE);
316                    return new ConnectivityManager(IConnectivityManager.Stub.asInterface(b));
317                }});
318
319        registerService(COUNTRY_DETECTOR, new StaticServiceFetcher() {
320                public Object createStaticService() {
321                    IBinder b = ServiceManager.getService(COUNTRY_DETECTOR);
322                    return new CountryDetector(ICountryDetector.Stub.asInterface(b));
323                }});
324
325        registerService(DEVICE_POLICY_SERVICE, new ServiceFetcher() {
326                public Object createService(ContextImpl ctx) {
327                    return DevicePolicyManager.create(ctx, ctx.mMainThread.getHandler());
328                }});
329
330        registerService(DOWNLOAD_SERVICE, new ServiceFetcher() {
331                public Object createService(ContextImpl ctx) {
332                    return new DownloadManager(ctx.getContentResolver(), ctx.getPackageName());
333                }});
334
335        registerService(NFC_SERVICE, new ServiceFetcher() {
336                public Object createService(ContextImpl ctx) {
337                    return new NfcManager(ctx);
338                }});
339
340        registerService(DROPBOX_SERVICE, new StaticServiceFetcher() {
341                public Object createStaticService() {
342                    return createDropBoxManager();
343                }});
344
345        registerService(INPUT_SERVICE, new StaticServiceFetcher() {
346                public Object createStaticService() {
347                    return InputManager.getInstance();
348                }});
349
350        registerService(DISPLAY_SERVICE, new StaticServiceFetcher() {
351            public Object createStaticService() {
352                return DisplayManager.getInstance();
353            }});
354
355        registerService(INPUT_METHOD_SERVICE, new ServiceFetcher() {
356                public Object createService(ContextImpl ctx) {
357                    return InputMethodManager.getInstance(ctx);
358                }});
359
360        registerService(TEXT_SERVICES_MANAGER_SERVICE, new ServiceFetcher() {
361                public Object createService(ContextImpl ctx) {
362                    return TextServicesManager.getInstance();
363                }});
364
365        registerService(KEYGUARD_SERVICE, new ServiceFetcher() {
366                public Object getService(ContextImpl ctx) {
367                    // TODO: why isn't this caching it?  It wasn't
368                    // before, so I'm preserving the old behavior and
369                    // using getService(), instead of createService()
370                    // which would do the caching.
371                    return new KeyguardManager();
372                }});
373
374        registerService(LAYOUT_INFLATER_SERVICE, new ServiceFetcher() {
375                public Object createService(ContextImpl ctx) {
376                    return PolicyManager.makeNewLayoutInflater(ctx.getOuterContext());
377                }});
378
379        registerService(LOCATION_SERVICE, new ServiceFetcher() {
380                public Object createService(ContextImpl ctx) {
381                    IBinder b = ServiceManager.getService(LOCATION_SERVICE);
382                    return new LocationManager(ctx, ILocationManager.Stub.asInterface(b));
383                }});
384
385        registerService(NETWORK_POLICY_SERVICE, new ServiceFetcher() {
386            @Override
387            public Object createService(ContextImpl ctx) {
388                return new NetworkPolicyManager(INetworkPolicyManager.Stub.asInterface(
389                        ServiceManager.getService(NETWORK_POLICY_SERVICE)));
390            }
391        });
392
393        registerService(NOTIFICATION_SERVICE, new ServiceFetcher() {
394                public Object createService(ContextImpl ctx) {
395                    final Context outerContext = ctx.getOuterContext();
396                    return new NotificationManager(
397                        new ContextThemeWrapper(outerContext,
398                                Resources.selectSystemTheme(0,
399                                        outerContext.getApplicationInfo().targetSdkVersion,
400                                        com.android.internal.R.style.Theme_Dialog,
401                                        com.android.internal.R.style.Theme_Holo_Dialog,
402                                        com.android.internal.R.style.Theme_DeviceDefault_Dialog)),
403                        ctx.mMainThread.getHandler());
404                }});
405
406        registerService(NSD_SERVICE, new ServiceFetcher() {
407                @Override
408                public Object createService(ContextImpl ctx) {
409                    IBinder b = ServiceManager.getService(NSD_SERVICE);
410                    INsdManager service = INsdManager.Stub.asInterface(b);
411                    return new NsdManager(ctx.getOuterContext(), service);
412                }});
413
414        // Note: this was previously cached in a static variable, but
415        // constructed using mMainThread.getHandler(), so converting
416        // it to be a regular Context-cached service...
417        registerService(POWER_SERVICE, new ServiceFetcher() {
418                public Object createService(ContextImpl ctx) {
419                    IBinder b = ServiceManager.getService(POWER_SERVICE);
420                    IPowerManager service = IPowerManager.Stub.asInterface(b);
421                    return new PowerManager(ctx.getOuterContext(),
422                            service, ctx.mMainThread.getHandler());
423                }});
424
425        registerService(SEARCH_SERVICE, new ServiceFetcher() {
426                public Object createService(ContextImpl ctx) {
427                    return new SearchManager(ctx.getOuterContext(),
428                            ctx.mMainThread.getHandler());
429                }});
430
431        registerService(SENSOR_SERVICE, new ServiceFetcher() {
432                public Object createService(ContextImpl ctx) {
433                    return new SystemSensorManager(ctx.mMainThread.getHandler().getLooper());
434                }});
435
436        registerService(STATUS_BAR_SERVICE, new ServiceFetcher() {
437                public Object createService(ContextImpl ctx) {
438                    return new StatusBarManager(ctx.getOuterContext());
439                }});
440
441        registerService(STORAGE_SERVICE, new ServiceFetcher() {
442                public Object createService(ContextImpl ctx) {
443                    try {
444                        return new StorageManager(ctx.mMainThread.getHandler().getLooper());
445                    } catch (RemoteException rex) {
446                        Log.e(TAG, "Failed to create StorageManager", rex);
447                        return null;
448                    }
449                }});
450
451        registerService(TELEPHONY_SERVICE, new ServiceFetcher() {
452                public Object createService(ContextImpl ctx) {
453                    return new TelephonyManager(ctx.getOuterContext());
454                }});
455
456        registerService(THROTTLE_SERVICE, new StaticServiceFetcher() {
457                public Object createStaticService() {
458                    IBinder b = ServiceManager.getService(THROTTLE_SERVICE);
459                    return new ThrottleManager(IThrottleManager.Stub.asInterface(b));
460                }});
461
462        registerService(UI_MODE_SERVICE, new ServiceFetcher() {
463                public Object createService(ContextImpl ctx) {
464                    return new UiModeManager();
465                }});
466
467        registerService(USB_SERVICE, new ServiceFetcher() {
468                public Object createService(ContextImpl ctx) {
469                    IBinder b = ServiceManager.getService(USB_SERVICE);
470                    return new UsbManager(ctx, IUsbManager.Stub.asInterface(b));
471                }});
472
473        registerService(SERIAL_SERVICE, new ServiceFetcher() {
474                public Object createService(ContextImpl ctx) {
475                    IBinder b = ServiceManager.getService(SERIAL_SERVICE);
476                    return new SerialManager(ctx, ISerialManager.Stub.asInterface(b));
477                }});
478
479        registerService(VIBRATOR_SERVICE, new ServiceFetcher() {
480                public Object createService(ContextImpl ctx) {
481                    return new SystemVibrator();
482                }});
483
484        registerService(WALLPAPER_SERVICE, WALLPAPER_FETCHER);
485
486        registerService(WIFI_SERVICE, new ServiceFetcher() {
487                public Object createService(ContextImpl ctx) {
488                    IBinder b = ServiceManager.getService(WIFI_SERVICE);
489                    IWifiManager service = IWifiManager.Stub.asInterface(b);
490                    return new WifiManager(ctx.getOuterContext(), service);
491                }});
492
493        registerService(WIFI_P2P_SERVICE, new ServiceFetcher() {
494                public Object createService(ContextImpl ctx) {
495                    IBinder b = ServiceManager.getService(WIFI_P2P_SERVICE);
496                    IWifiP2pManager service = IWifiP2pManager.Stub.asInterface(b);
497                    return new WifiP2pManager(service);
498                }});
499
500        registerService(WINDOW_SERVICE, new ServiceFetcher() {
501                public Object getService(ContextImpl ctx) {
502                    return WindowManagerImpl.getDefault().makeCompatible(
503                            ctx.mPackageInfo.mCompatibilityInfo);
504                }});
505
506        registerService(USER_SERVICE, new ServiceFetcher() {
507            public Object getService(ContextImpl ctx) {
508                IBinder b = ServiceManager.getService(USER_SERVICE);
509                IUserManager service = IUserManager.Stub.asInterface(b);
510                return new UserManager(ctx, service);
511            }});
512    }
513
514    static ContextImpl getImpl(Context context) {
515        Context nextContext;
516        while ((context instanceof ContextWrapper) &&
517                (nextContext=((ContextWrapper)context).getBaseContext()) != null) {
518            context = nextContext;
519        }
520        return (ContextImpl)context;
521    }
522
523    // The system service cache for the system services that are
524    // cached per-ContextImpl.  Package-scoped to avoid accessor
525    // methods.
526    final ArrayList<Object> mServiceCache = new ArrayList<Object>();
527
528    @Override
529    public AssetManager getAssets() {
530        return getResources().getAssets();
531    }
532
533    @Override
534    public Resources getResources() {
535        return mResources;
536    }
537
538    @Override
539    public PackageManager getPackageManager() {
540        if (mPackageManager != null) {
541            return mPackageManager;
542        }
543
544        IPackageManager pm = ActivityThread.getPackageManager();
545        if (pm != null) {
546            // Doesn't matter if we make more than one instance.
547            return (mPackageManager = new ApplicationPackageManager(this, pm));
548        }
549
550        return null;
551    }
552
553    @Override
554    public ContentResolver getContentResolver() {
555        return mContentResolver;
556    }
557
558    @Override
559    public Looper getMainLooper() {
560        return mMainThread.getLooper();
561    }
562
563    @Override
564    public Context getApplicationContext() {
565        return (mPackageInfo != null) ?
566                mPackageInfo.getApplication() : mMainThread.getApplication();
567    }
568
569    @Override
570    public void setTheme(int resid) {
571        mThemeResource = resid;
572    }
573
574    @Override
575    public int getThemeResId() {
576        return mThemeResource;
577    }
578
579    @Override
580    public Resources.Theme getTheme() {
581        if (mTheme == null) {
582            mThemeResource = Resources.selectDefaultTheme(mThemeResource,
583                    getOuterContext().getApplicationInfo().targetSdkVersion);
584            mTheme = mResources.newTheme();
585            mTheme.applyStyle(mThemeResource, true);
586        }
587        return mTheme;
588    }
589
590    @Override
591    public ClassLoader getClassLoader() {
592        return mPackageInfo != null ?
593                mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader();
594    }
595
596    @Override
597    public String getPackageName() {
598        if (mPackageInfo != null) {
599            return mPackageInfo.getPackageName();
600        }
601        throw new RuntimeException("Not supported in system context");
602    }
603
604    @Override
605    public ApplicationInfo getApplicationInfo() {
606        if (mPackageInfo != null) {
607            return mPackageInfo.getApplicationInfo();
608        }
609        throw new RuntimeException("Not supported in system context");
610    }
611
612    @Override
613    public String getPackageResourcePath() {
614        if (mPackageInfo != null) {
615            return mPackageInfo.getResDir();
616        }
617        throw new RuntimeException("Not supported in system context");
618    }
619
620    @Override
621    public String getPackageCodePath() {
622        if (mPackageInfo != null) {
623            return mPackageInfo.getAppDir();
624        }
625        throw new RuntimeException("Not supported in system context");
626    }
627
628    public File getSharedPrefsFile(String name) {
629        return makeFilename(getPreferencesDir(), name + ".xml");
630    }
631
632    @Override
633    public SharedPreferences getSharedPreferences(String name, int mode) {
634        SharedPreferencesImpl sp;
635        synchronized (sSharedPrefs) {
636            sp = sSharedPrefs.get(name);
637            if (sp == null) {
638                File prefsFile = getSharedPrefsFile(name);
639                sp = new SharedPreferencesImpl(prefsFile, mode);
640                sSharedPrefs.put(name, sp);
641                return sp;
642            }
643        }
644        if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
645            getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
646            // If somebody else (some other process) changed the prefs
647            // file behind our back, we reload it.  This has been the
648            // historical (if undocumented) behavior.
649            sp.startReloadIfChangedUnexpectedly();
650        }
651        return sp;
652    }
653
654    private File getPreferencesDir() {
655        synchronized (mSync) {
656            if (mPreferencesDir == null) {
657                mPreferencesDir = new File(getDataDirFile(), "shared_prefs");
658            }
659            return mPreferencesDir;
660        }
661    }
662
663    @Override
664    public FileInputStream openFileInput(String name)
665        throws FileNotFoundException {
666        File f = makeFilename(getFilesDir(), name);
667        return new FileInputStream(f);
668    }
669
670    @Override
671    public FileOutputStream openFileOutput(String name, int mode)
672        throws FileNotFoundException {
673        final boolean append = (mode&MODE_APPEND) != 0;
674        File f = makeFilename(getFilesDir(), name);
675        try {
676            FileOutputStream fos = new FileOutputStream(f, append);
677            setFilePermissionsFromMode(f.getPath(), mode, 0);
678            return fos;
679        } catch (FileNotFoundException e) {
680        }
681
682        File parent = f.getParentFile();
683        parent.mkdir();
684        FileUtils.setPermissions(
685            parent.getPath(),
686            FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
687            -1, -1);
688        FileOutputStream fos = new FileOutputStream(f, append);
689        setFilePermissionsFromMode(f.getPath(), mode, 0);
690        return fos;
691    }
692
693    @Override
694    public boolean deleteFile(String name) {
695        File f = makeFilename(getFilesDir(), name);
696        return f.delete();
697    }
698
699    @Override
700    public File getFilesDir() {
701        synchronized (mSync) {
702            if (mFilesDir == null) {
703                mFilesDir = new File(getDataDirFile(), "files");
704            }
705            if (!mFilesDir.exists()) {
706                if(!mFilesDir.mkdirs()) {
707                    Log.w(TAG, "Unable to create files directory " + mFilesDir.getPath());
708                    return null;
709                }
710                FileUtils.setPermissions(
711                        mFilesDir.getPath(),
712                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
713                        -1, -1);
714            }
715            return mFilesDir;
716        }
717    }
718
719    @Override
720    public File getExternalFilesDir(String type) {
721        synchronized (mSync) {
722            if (mExternalFilesDir == null) {
723                mExternalFilesDir = Environment.getExternalStorageAppFilesDirectory(
724                        getPackageName());
725            }
726            if (!mExternalFilesDir.exists()) {
727                try {
728                    (new File(Environment.getExternalStorageAndroidDataDir(),
729                            ".nomedia")).createNewFile();
730                } catch (IOException e) {
731                }
732                if (!mExternalFilesDir.mkdirs()) {
733                    Log.w(TAG, "Unable to create external files directory");
734                    return null;
735                }
736            }
737            if (type == null) {
738                return mExternalFilesDir;
739            }
740            File dir = new File(mExternalFilesDir, type);
741            if (!dir.exists()) {
742                if (!dir.mkdirs()) {
743                    Log.w(TAG, "Unable to create external media directory " + dir);
744                    return null;
745                }
746            }
747            return dir;
748        }
749    }
750
751    @Override
752    public File getObbDir() {
753        synchronized (mSync) {
754            if (mObbDir == null) {
755                mObbDir = Environment.getExternalStorageAppObbDirectory(
756                        getPackageName());
757            }
758            return mObbDir;
759        }
760    }
761
762    @Override
763    public File getCacheDir() {
764        synchronized (mSync) {
765            if (mCacheDir == null) {
766                mCacheDir = new File(getDataDirFile(), "cache");
767            }
768            if (!mCacheDir.exists()) {
769                if(!mCacheDir.mkdirs()) {
770                    Log.w(TAG, "Unable to create cache directory");
771                    return null;
772                }
773                FileUtils.setPermissions(
774                        mCacheDir.getPath(),
775                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
776                        -1, -1);
777            }
778        }
779        return mCacheDir;
780    }
781
782    @Override
783    public File getExternalCacheDir() {
784        synchronized (mSync) {
785            if (mExternalCacheDir == null) {
786                mExternalCacheDir = Environment.getExternalStorageAppCacheDirectory(
787                        getPackageName());
788            }
789            if (!mExternalCacheDir.exists()) {
790                try {
791                    (new File(Environment.getExternalStorageAndroidDataDir(),
792                            ".nomedia")).createNewFile();
793                } catch (IOException e) {
794                }
795                if (!mExternalCacheDir.mkdirs()) {
796                    Log.w(TAG, "Unable to create external cache directory");
797                    return null;
798                }
799            }
800            return mExternalCacheDir;
801        }
802    }
803
804    @Override
805    public File getFileStreamPath(String name) {
806        return makeFilename(getFilesDir(), name);
807    }
808
809    @Override
810    public String[] fileList() {
811        final String[] list = getFilesDir().list();
812        return (list != null) ? list : EMPTY_FILE_LIST;
813    }
814
815    @Override
816    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) {
817        return openOrCreateDatabase(name, mode, factory, null);
818    }
819
820    @Override
821    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory,
822            DatabaseErrorHandler errorHandler) {
823        File f = validateFilePath(name, true);
824        int flags = SQLiteDatabase.CREATE_IF_NECESSARY;
825        if ((mode & MODE_ENABLE_WRITE_AHEAD_LOGGING) != 0) {
826            flags |= SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING;
827        }
828        SQLiteDatabase db = SQLiteDatabase.openDatabase(f.getPath(), factory, flags, errorHandler);
829        setFilePermissionsFromMode(f.getPath(), mode, 0);
830        return db;
831    }
832
833    @Override
834    public boolean deleteDatabase(String name) {
835        try {
836            File f = validateFilePath(name, false);
837            return SQLiteDatabase.deleteDatabase(f);
838        } catch (Exception e) {
839        }
840        return false;
841    }
842
843    @Override
844    public File getDatabasePath(String name) {
845        return validateFilePath(name, false);
846    }
847
848    @Override
849    public String[] databaseList() {
850        final String[] list = getDatabasesDir().list();
851        return (list != null) ? list : EMPTY_FILE_LIST;
852    }
853
854
855    private File getDatabasesDir() {
856        synchronized (mSync) {
857            if (mDatabasesDir == null) {
858                mDatabasesDir = new File(getDataDirFile(), "databases");
859            }
860            if (mDatabasesDir.getPath().equals("databases")) {
861                mDatabasesDir = new File("/data/system");
862            }
863            return mDatabasesDir;
864        }
865    }
866
867    @Override
868    public Drawable getWallpaper() {
869        return getWallpaperManager().getDrawable();
870    }
871
872    @Override
873    public Drawable peekWallpaper() {
874        return getWallpaperManager().peekDrawable();
875    }
876
877    @Override
878    public int getWallpaperDesiredMinimumWidth() {
879        return getWallpaperManager().getDesiredMinimumWidth();
880    }
881
882    @Override
883    public int getWallpaperDesiredMinimumHeight() {
884        return getWallpaperManager().getDesiredMinimumHeight();
885    }
886
887    @Override
888    public void setWallpaper(Bitmap bitmap) throws IOException  {
889        getWallpaperManager().setBitmap(bitmap);
890    }
891
892    @Override
893    public void setWallpaper(InputStream data) throws IOException {
894        getWallpaperManager().setStream(data);
895    }
896
897    @Override
898    public void clearWallpaper() throws IOException {
899        getWallpaperManager().clear();
900    }
901
902    @Override
903    public void startActivity(Intent intent) {
904        startActivity(intent, null);
905    }
906
907    /** @hide */
908    @Override
909    public void startActivityAsUser(Intent intent, int userId) {
910        try {
911            ActivityManagerNative.getDefault().startActivityAsUser(
912                mMainThread.getApplicationThread(), intent,
913                intent.resolveTypeIfNeeded(getContentResolver()),
914                null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, null, null, userId);
915        } catch (RemoteException re) {
916        }
917    }
918
919    @Override
920    public void startActivity(Intent intent, Bundle options) {
921        if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
922            throw new AndroidRuntimeException(
923                    "Calling startActivity() from outside of an Activity "
924                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
925                    + " Is this really what you want?");
926        }
927        mMainThread.getInstrumentation().execStartActivity(
928            getOuterContext(), mMainThread.getApplicationThread(), null,
929            (Activity)null, intent, -1, options);
930    }
931
932    /** @hide */
933    @Override
934    public void startActivityAsUser(Intent intent, Bundle options, int userId) {
935        try {
936            ActivityManagerNative.getDefault().startActivityAsUser(
937                mMainThread.getApplicationThread(), intent,
938                intent.resolveTypeIfNeeded(getContentResolver()),
939                null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, null, options, userId);
940        } catch (RemoteException re) {
941        }
942    }
943
944    @Override
945    public void startActivities(Intent[] intents) {
946        startActivities(intents, null);
947    }
948
949    @Override
950    public void startActivities(Intent[] intents, Bundle options) {
951        if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
952            throw new AndroidRuntimeException(
953                    "Calling startActivities() from outside of an Activity "
954                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent."
955                    + " Is this really what you want?");
956        }
957        mMainThread.getInstrumentation().execStartActivities(
958            getOuterContext(), mMainThread.getApplicationThread(), null,
959            (Activity)null, intents, options);
960    }
961
962    @Override
963    public void startIntentSender(IntentSender intent,
964            Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
965            throws IntentSender.SendIntentException {
966        startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, null);
967    }
968
969    @Override
970    public void startIntentSender(IntentSender intent, Intent fillInIntent,
971            int flagsMask, int flagsValues, int extraFlags, Bundle options)
972            throws IntentSender.SendIntentException {
973        try {
974            String resolvedType = null;
975            if (fillInIntent != null) {
976                fillInIntent.setAllowFds(false);
977                resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
978            }
979            int result = ActivityManagerNative.getDefault()
980                .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
981                        fillInIntent, resolvedType, null, null,
982                        0, flagsMask, flagsValues, options);
983            if (result == ActivityManager.START_CANCELED) {
984                throw new IntentSender.SendIntentException();
985            }
986            Instrumentation.checkStartActivityResult(result, null);
987        } catch (RemoteException e) {
988        }
989    }
990
991    @Override
992    public void sendBroadcast(Intent intent) {
993        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
994        try {
995            intent.setAllowFds(false);
996            ActivityManagerNative.getDefault().broadcastIntent(
997                mMainThread.getApplicationThread(), intent, resolvedType, null,
998                Activity.RESULT_OK, null, null, null, false, false,
999                Binder.getOrigCallingUser());
1000        } catch (RemoteException e) {
1001        }
1002    }
1003
1004    @Override
1005    public void sendBroadcast(Intent intent, String receiverPermission) {
1006        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1007        try {
1008            intent.setAllowFds(false);
1009            ActivityManagerNative.getDefault().broadcastIntent(
1010                mMainThread.getApplicationThread(), intent, resolvedType, null,
1011                Activity.RESULT_OK, null, null, receiverPermission, false, false,
1012                Binder.getOrigCallingUser());
1013        } catch (RemoteException e) {
1014        }
1015    }
1016
1017    @Override
1018    public void sendOrderedBroadcast(Intent intent,
1019            String receiverPermission) {
1020        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1021        try {
1022            intent.setAllowFds(false);
1023            ActivityManagerNative.getDefault().broadcastIntent(
1024                mMainThread.getApplicationThread(), intent, resolvedType, null,
1025                Activity.RESULT_OK, null, null, receiverPermission, true, false,
1026                Binder.getOrigCallingUser());
1027        } catch (RemoteException e) {
1028        }
1029    }
1030
1031    @Override
1032    public void sendOrderedBroadcast(Intent intent,
1033            String receiverPermission, BroadcastReceiver resultReceiver,
1034            Handler scheduler, int initialCode, String initialData,
1035            Bundle initialExtras) {
1036        IIntentReceiver rd = null;
1037        if (resultReceiver != null) {
1038            if (mPackageInfo != null) {
1039                if (scheduler == null) {
1040                    scheduler = mMainThread.getHandler();
1041                }
1042                rd = mPackageInfo.getReceiverDispatcher(
1043                    resultReceiver, getOuterContext(), scheduler,
1044                    mMainThread.getInstrumentation(), false);
1045            } else {
1046                if (scheduler == null) {
1047                    scheduler = mMainThread.getHandler();
1048                }
1049                rd = new LoadedApk.ReceiverDispatcher(
1050                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1051            }
1052        }
1053        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1054        try {
1055            intent.setAllowFds(false);
1056            ActivityManagerNative.getDefault().broadcastIntent(
1057                mMainThread.getApplicationThread(), intent, resolvedType, rd,
1058                initialCode, initialData, initialExtras, receiverPermission,
1059                true, false, Binder.getOrigCallingUser());
1060        } catch (RemoteException e) {
1061        }
1062    }
1063
1064    @Override
1065    public void sendBroadcastToUser(Intent intent, int userHandle) {
1066        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1067        try {
1068            intent.setAllowFds(false);
1069            ActivityManagerNative.getDefault().broadcastIntent(mMainThread.getApplicationThread(),
1070                    intent, resolvedType, null, Activity.RESULT_OK, null, null, null, false, false,
1071                    userHandle);
1072        } catch (RemoteException e) {
1073        }
1074    }
1075
1076    @Override
1077    public void sendOrderedBroadcastToUser(Intent intent, int userHandle,
1078            BroadcastReceiver resultReceiver, Handler scheduler,
1079            int initialCode, String initialData, Bundle initialExtras) {
1080        IIntentReceiver rd = null;
1081        if (resultReceiver != null) {
1082            if (mPackageInfo != null) {
1083                if (scheduler == null) {
1084                    scheduler = mMainThread.getHandler();
1085                }
1086                rd = mPackageInfo.getReceiverDispatcher(
1087                    resultReceiver, getOuterContext(), scheduler,
1088                    mMainThread.getInstrumentation(), false);
1089            } else {
1090                if (scheduler == null) {
1091                    scheduler = mMainThread.getHandler();
1092                }
1093                rd = new LoadedApk.ReceiverDispatcher(
1094                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1095            }
1096        }
1097        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1098        try {
1099            intent.setAllowFds(false);
1100            ActivityManagerNative.getDefault().broadcastIntent(
1101                mMainThread.getApplicationThread(), intent, resolvedType, rd,
1102                initialCode, initialData, initialExtras, null,
1103                true, false, userHandle);
1104        } catch (RemoteException e) {
1105        }
1106    }
1107
1108    @Override
1109    public void sendStickyBroadcast(Intent intent) {
1110        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1111        try {
1112            intent.setAllowFds(false);
1113            ActivityManagerNative.getDefault().broadcastIntent(
1114                mMainThread.getApplicationThread(), intent, resolvedType, null,
1115                Activity.RESULT_OK, null, null, null, false, true,
1116                Binder.getOrigCallingUser());
1117        } catch (RemoteException e) {
1118        }
1119    }
1120
1121    @Override
1122    public void sendStickyOrderedBroadcast(Intent intent,
1123            BroadcastReceiver resultReceiver,
1124            Handler scheduler, int initialCode, String initialData,
1125            Bundle initialExtras) {
1126        IIntentReceiver rd = null;
1127        if (resultReceiver != null) {
1128            if (mPackageInfo != null) {
1129                if (scheduler == null) {
1130                    scheduler = mMainThread.getHandler();
1131                }
1132                rd = mPackageInfo.getReceiverDispatcher(
1133                    resultReceiver, getOuterContext(), scheduler,
1134                    mMainThread.getInstrumentation(), false);
1135            } else {
1136                if (scheduler == null) {
1137                    scheduler = mMainThread.getHandler();
1138                }
1139                rd = new LoadedApk.ReceiverDispatcher(
1140                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1141            }
1142        }
1143        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1144        try {
1145            intent.setAllowFds(false);
1146            ActivityManagerNative.getDefault().broadcastIntent(
1147                mMainThread.getApplicationThread(), intent, resolvedType, rd,
1148                initialCode, initialData, initialExtras, null,
1149                true, true, Binder.getOrigCallingUser());
1150        } catch (RemoteException e) {
1151        }
1152    }
1153
1154    @Override
1155    public void removeStickyBroadcast(Intent intent) {
1156        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1157        if (resolvedType != null) {
1158            intent = new Intent(intent);
1159            intent.setDataAndType(intent.getData(), resolvedType);
1160        }
1161        try {
1162            intent.setAllowFds(false);
1163            ActivityManagerNative.getDefault().unbroadcastIntent(
1164                    mMainThread.getApplicationThread(), intent, Binder.getOrigCallingUser());
1165        } catch (RemoteException e) {
1166        }
1167    }
1168
1169    @Override
1170    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
1171        return registerReceiver(receiver, filter, null, null);
1172    }
1173
1174    @Override
1175    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
1176            String broadcastPermission, Handler scheduler) {
1177        return registerReceiverInternal(receiver, filter, broadcastPermission,
1178                scheduler, getOuterContext());
1179    }
1180
1181    private Intent registerReceiverInternal(BroadcastReceiver receiver,
1182            IntentFilter filter, String broadcastPermission,
1183            Handler scheduler, Context context) {
1184        IIntentReceiver rd = null;
1185        if (receiver != null) {
1186            if (mPackageInfo != null && context != null) {
1187                if (scheduler == null) {
1188                    scheduler = mMainThread.getHandler();
1189                }
1190                rd = mPackageInfo.getReceiverDispatcher(
1191                    receiver, context, scheduler,
1192                    mMainThread.getInstrumentation(), true);
1193            } else {
1194                if (scheduler == null) {
1195                    scheduler = mMainThread.getHandler();
1196                }
1197                rd = new LoadedApk.ReceiverDispatcher(
1198                        receiver, context, scheduler, null, true).getIIntentReceiver();
1199            }
1200        }
1201        try {
1202            return ActivityManagerNative.getDefault().registerReceiver(
1203                    mMainThread.getApplicationThread(), mBasePackageName,
1204                    rd, filter, broadcastPermission);
1205        } catch (RemoteException e) {
1206            return null;
1207        }
1208    }
1209
1210    @Override
1211    public void unregisterReceiver(BroadcastReceiver receiver) {
1212        if (mPackageInfo != null) {
1213            IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher(
1214                    getOuterContext(), receiver);
1215            try {
1216                ActivityManagerNative.getDefault().unregisterReceiver(rd);
1217            } catch (RemoteException e) {
1218            }
1219        } else {
1220            throw new RuntimeException("Not supported in system context");
1221        }
1222    }
1223
1224    @Override
1225    public ComponentName startService(Intent service) {
1226        try {
1227            service.setAllowFds(false);
1228            ComponentName cn = ActivityManagerNative.getDefault().startService(
1229                mMainThread.getApplicationThread(), service,
1230                service.resolveTypeIfNeeded(getContentResolver()));
1231            if (cn != null && cn.getPackageName().equals("!")) {
1232                throw new SecurityException(
1233                        "Not allowed to start service " + service
1234                        + " without permission " + cn.getClassName());
1235            }
1236            return cn;
1237        } catch (RemoteException e) {
1238            return null;
1239        }
1240    }
1241
1242    @Override
1243    public boolean stopService(Intent service) {
1244        try {
1245            service.setAllowFds(false);
1246            int res = ActivityManagerNative.getDefault().stopService(
1247                mMainThread.getApplicationThread(), service,
1248                service.resolveTypeIfNeeded(getContentResolver()));
1249            if (res < 0) {
1250                throw new SecurityException(
1251                        "Not allowed to stop service " + service);
1252            }
1253            return res != 0;
1254        } catch (RemoteException e) {
1255            return false;
1256        }
1257    }
1258
1259    @Override
1260    public boolean bindService(Intent service, ServiceConnection conn,
1261            int flags) {
1262        return bindService(service, conn, flags, UserId.getUserId(Process.myUid()));
1263    }
1264
1265    /** @hide */
1266    @Override
1267    public boolean bindService(Intent service, ServiceConnection conn, int flags, int userHandle) {
1268        IServiceConnection sd;
1269        if (conn == null) {
1270            throw new IllegalArgumentException("connection is null");
1271        }
1272        if (mPackageInfo != null) {
1273            sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
1274                    mMainThread.getHandler(), flags);
1275        } else {
1276            throw new RuntimeException("Not supported in system context");
1277        }
1278        try {
1279            IBinder token = getActivityToken();
1280            if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
1281                    && mPackageInfo.getApplicationInfo().targetSdkVersion
1282                    < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1283                flags |= BIND_WAIVE_PRIORITY;
1284            }
1285            service.setAllowFds(false);
1286            int res = ActivityManagerNative.getDefault().bindService(
1287                mMainThread.getApplicationThread(), getActivityToken(),
1288                service, service.resolveTypeIfNeeded(getContentResolver()),
1289                sd, flags, userHandle);
1290            if (res < 0) {
1291                throw new SecurityException(
1292                        "Not allowed to bind to service " + service);
1293            }
1294            return res != 0;
1295        } catch (RemoteException e) {
1296            return false;
1297        }
1298    }
1299
1300    @Override
1301    public void unbindService(ServiceConnection conn) {
1302        if (conn == null) {
1303            throw new IllegalArgumentException("connection is null");
1304        }
1305        if (mPackageInfo != null) {
1306            IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
1307                    getOuterContext(), conn);
1308            try {
1309                ActivityManagerNative.getDefault().unbindService(sd);
1310            } catch (RemoteException e) {
1311            }
1312        } else {
1313            throw new RuntimeException("Not supported in system context");
1314        }
1315    }
1316
1317    @Override
1318    public boolean startInstrumentation(ComponentName className,
1319            String profileFile, Bundle arguments) {
1320        try {
1321            if (arguments != null) {
1322                arguments.setAllowFds(false);
1323            }
1324            return ActivityManagerNative.getDefault().startInstrumentation(
1325                    className, profileFile, 0, arguments, null);
1326        } catch (RemoteException e) {
1327            // System has crashed, nothing we can do.
1328        }
1329        return false;
1330    }
1331
1332    @Override
1333    public Object getSystemService(String name) {
1334        ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);
1335        return fetcher == null ? null : fetcher.getService(this);
1336    }
1337
1338    private WallpaperManager getWallpaperManager() {
1339        return (WallpaperManager) WALLPAPER_FETCHER.getService(this);
1340    }
1341
1342    /* package */ static DropBoxManager createDropBoxManager() {
1343        IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
1344        IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
1345        if (service == null) {
1346            // Don't return a DropBoxManager that will NPE upon use.
1347            // This also avoids caching a broken DropBoxManager in
1348            // getDropBoxManager during early boot, before the
1349            // DROPBOX_SERVICE is registered.
1350            return null;
1351        }
1352        return new DropBoxManager(service);
1353    }
1354
1355    @Override
1356    public int checkPermission(String permission, int pid, int uid) {
1357        if (permission == null) {
1358            throw new IllegalArgumentException("permission is null");
1359        }
1360
1361        try {
1362            return ActivityManagerNative.getDefault().checkPermission(
1363                    permission, pid, uid);
1364        } catch (RemoteException e) {
1365            return PackageManager.PERMISSION_DENIED;
1366        }
1367    }
1368
1369    @Override
1370    public int checkCallingPermission(String permission) {
1371        if (permission == null) {
1372            throw new IllegalArgumentException("permission is null");
1373        }
1374
1375        int pid = Binder.getCallingPid();
1376        if (pid != Process.myPid()) {
1377            return checkPermission(permission, pid, Binder.getCallingUid());
1378        }
1379        return PackageManager.PERMISSION_DENIED;
1380    }
1381
1382    @Override
1383    public int checkCallingOrSelfPermission(String permission) {
1384        if (permission == null) {
1385            throw new IllegalArgumentException("permission is null");
1386        }
1387
1388        return checkPermission(permission, Binder.getCallingPid(),
1389                Binder.getCallingUid());
1390    }
1391
1392    private void enforce(
1393            String permission, int resultOfCheck,
1394            boolean selfToo, int uid, String message) {
1395        if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
1396            throw new SecurityException(
1397                    (message != null ? (message + ": ") : "") +
1398                    (selfToo
1399                     ? "Neither user " + uid + " nor current process has "
1400                     : "User " + uid + " does not have ") +
1401                    permission +
1402                    ".");
1403        }
1404    }
1405
1406    public void enforcePermission(
1407            String permission, int pid, int uid, String message) {
1408        enforce(permission,
1409                checkPermission(permission, pid, uid),
1410                false,
1411                uid,
1412                message);
1413    }
1414
1415    public void enforceCallingPermission(String permission, String message) {
1416        enforce(permission,
1417                checkCallingPermission(permission),
1418                false,
1419                Binder.getCallingUid(),
1420                message);
1421    }
1422
1423    public void enforceCallingOrSelfPermission(
1424            String permission, String message) {
1425        enforce(permission,
1426                checkCallingOrSelfPermission(permission),
1427                true,
1428                Binder.getCallingUid(),
1429                message);
1430    }
1431
1432    @Override
1433    public void grantUriPermission(String toPackage, Uri uri, int modeFlags) {
1434         try {
1435            ActivityManagerNative.getDefault().grantUriPermission(
1436                    mMainThread.getApplicationThread(), toPackage, uri,
1437                    modeFlags);
1438        } catch (RemoteException e) {
1439        }
1440    }
1441
1442    @Override
1443    public void revokeUriPermission(Uri uri, int modeFlags) {
1444         try {
1445            ActivityManagerNative.getDefault().revokeUriPermission(
1446                    mMainThread.getApplicationThread(), uri,
1447                    modeFlags);
1448        } catch (RemoteException e) {
1449        }
1450    }
1451
1452    @Override
1453    public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
1454        try {
1455            return ActivityManagerNative.getDefault().checkUriPermission(
1456                    uri, pid, uid, modeFlags);
1457        } catch (RemoteException e) {
1458            return PackageManager.PERMISSION_DENIED;
1459        }
1460    }
1461
1462    @Override
1463    public int checkCallingUriPermission(Uri uri, int modeFlags) {
1464        int pid = Binder.getCallingPid();
1465        if (pid != Process.myPid()) {
1466            return checkUriPermission(uri, pid,
1467                    Binder.getCallingUid(), modeFlags);
1468        }
1469        return PackageManager.PERMISSION_DENIED;
1470    }
1471
1472    @Override
1473    public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) {
1474        return checkUriPermission(uri, Binder.getCallingPid(),
1475                Binder.getCallingUid(), modeFlags);
1476    }
1477
1478    @Override
1479    public int checkUriPermission(Uri uri, String readPermission,
1480            String writePermission, int pid, int uid, int modeFlags) {
1481        if (DEBUG) {
1482            Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
1483                    + readPermission + " writePermission=" + writePermission
1484                    + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
1485        }
1486        if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
1487            if (readPermission == null
1488                    || checkPermission(readPermission, pid, uid)
1489                    == PackageManager.PERMISSION_GRANTED) {
1490                return PackageManager.PERMISSION_GRANTED;
1491            }
1492        }
1493        if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
1494            if (writePermission == null
1495                    || checkPermission(writePermission, pid, uid)
1496                    == PackageManager.PERMISSION_GRANTED) {
1497                return PackageManager.PERMISSION_GRANTED;
1498            }
1499        }
1500        return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
1501                : PackageManager.PERMISSION_DENIED;
1502    }
1503
1504    private String uriModeFlagToString(int uriModeFlags) {
1505        switch (uriModeFlags) {
1506            case Intent.FLAG_GRANT_READ_URI_PERMISSION |
1507                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION:
1508                return "read and write";
1509            case Intent.FLAG_GRANT_READ_URI_PERMISSION:
1510                return "read";
1511            case Intent.FLAG_GRANT_WRITE_URI_PERMISSION:
1512                return "write";
1513        }
1514        throw new IllegalArgumentException(
1515                "Unknown permission mode flags: " + uriModeFlags);
1516    }
1517
1518    private void enforceForUri(
1519            int modeFlags, int resultOfCheck, boolean selfToo,
1520            int uid, Uri uri, String message) {
1521        if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
1522            throw new SecurityException(
1523                    (message != null ? (message + ": ") : "") +
1524                    (selfToo
1525                     ? "Neither user " + uid + " nor current process has "
1526                     : "User " + uid + " does not have ") +
1527                    uriModeFlagToString(modeFlags) +
1528                    " permission on " +
1529                    uri +
1530                    ".");
1531        }
1532    }
1533
1534    public void enforceUriPermission(
1535            Uri uri, int pid, int uid, int modeFlags, String message) {
1536        enforceForUri(
1537                modeFlags, checkUriPermission(uri, pid, uid, modeFlags),
1538                false, uid, uri, message);
1539    }
1540
1541    public void enforceCallingUriPermission(
1542            Uri uri, int modeFlags, String message) {
1543        enforceForUri(
1544                modeFlags, checkCallingUriPermission(uri, modeFlags),
1545                false,
1546                Binder.getCallingUid(), uri, message);
1547    }
1548
1549    public void enforceCallingOrSelfUriPermission(
1550            Uri uri, int modeFlags, String message) {
1551        enforceForUri(
1552                modeFlags,
1553                checkCallingOrSelfUriPermission(uri, modeFlags), true,
1554                Binder.getCallingUid(), uri, message);
1555    }
1556
1557    public void enforceUriPermission(
1558            Uri uri, String readPermission, String writePermission,
1559            int pid, int uid, int modeFlags, String message) {
1560        enforceForUri(modeFlags,
1561                      checkUriPermission(
1562                              uri, readPermission, writePermission, pid, uid,
1563                              modeFlags),
1564                      false,
1565                      uid,
1566                      uri,
1567                      message);
1568    }
1569
1570    @Override
1571    public Context createPackageContext(String packageName, int flags)
1572        throws PackageManager.NameNotFoundException {
1573        if (packageName.equals("system") || packageName.equals("android")) {
1574            final ContextImpl context = new ContextImpl(mMainThread.getSystemContext());
1575            context.mBasePackageName = mBasePackageName;
1576            return context;
1577        }
1578
1579        LoadedApk pi =
1580            mMainThread.getPackageInfo(packageName, mResources.getCompatibilityInfo(), flags);
1581        if (pi != null) {
1582            ContextImpl c = new ContextImpl();
1583            c.mRestricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED;
1584            c.init(pi, null, mMainThread, mResources, mBasePackageName);
1585            if (c.mResources != null) {
1586                return c;
1587            }
1588        }
1589
1590        // Should be a better exception.
1591        throw new PackageManager.NameNotFoundException(
1592            "Application package " + packageName + " not found");
1593    }
1594
1595    @Override
1596    public Context createConfigurationContext(Configuration overrideConfiguration) {
1597        ContextImpl c = new ContextImpl();
1598        c.init(mPackageInfo, null, mMainThread);
1599        c.mResources = mMainThread.getTopLevelResources(
1600                mPackageInfo.getResDir(), overrideConfiguration,
1601                mResources.getCompatibilityInfo());
1602        return c;
1603    }
1604
1605    @Override
1606    public boolean isRestricted() {
1607        return mRestricted;
1608    }
1609
1610    private File getDataDirFile() {
1611        if (mPackageInfo != null) {
1612            return mPackageInfo.getDataDirFile();
1613        }
1614        throw new RuntimeException("Not supported in system context");
1615    }
1616
1617    @Override
1618    public File getDir(String name, int mode) {
1619        name = "app_" + name;
1620        File file = makeFilename(getDataDirFile(), name);
1621        if (!file.exists()) {
1622            file.mkdir();
1623            setFilePermissionsFromMode(file.getPath(), mode,
1624                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH);
1625        }
1626        return file;
1627    }
1628
1629    static ContextImpl createSystemContext(ActivityThread mainThread) {
1630        ContextImpl context = new ContextImpl();
1631        context.init(Resources.getSystem(), mainThread);
1632        return context;
1633    }
1634
1635    ContextImpl() {
1636        mOuterContext = this;
1637    }
1638
1639    /**
1640     * Create a new ApplicationContext from an existing one.  The new one
1641     * works and operates the same as the one it is copying.
1642     *
1643     * @param context Existing application context.
1644     */
1645    public ContextImpl(ContextImpl context) {
1646        mPackageInfo = context.mPackageInfo;
1647        mBasePackageName = context.mBasePackageName;
1648        mResources = context.mResources;
1649        mMainThread = context.mMainThread;
1650        mContentResolver = context.mContentResolver;
1651        mOuterContext = this;
1652    }
1653
1654    final void init(LoadedApk packageInfo,
1655            IBinder activityToken, ActivityThread mainThread) {
1656        init(packageInfo, activityToken, mainThread, null, null);
1657    }
1658
1659    final void init(LoadedApk packageInfo,
1660                IBinder activityToken, ActivityThread mainThread,
1661                Resources container, String basePackageName) {
1662        mPackageInfo = packageInfo;
1663        mBasePackageName = basePackageName != null ? basePackageName : packageInfo.mPackageName;
1664        mResources = mPackageInfo.getResources(mainThread);
1665
1666        if (mResources != null && container != null
1667                && container.getCompatibilityInfo().applicationScale !=
1668                        mResources.getCompatibilityInfo().applicationScale) {
1669            if (DEBUG) {
1670                Log.d(TAG, "loaded context has different scaling. Using container's" +
1671                        " compatiblity info:" + container.getDisplayMetrics());
1672            }
1673            mResources = mainThread.getTopLevelResources(
1674                    mPackageInfo.getResDir(), null, container.getCompatibilityInfo());
1675        }
1676        mMainThread = mainThread;
1677        mContentResolver = new ApplicationContentResolver(this, mainThread);
1678        mActivityToken = activityToken;
1679    }
1680
1681    final void init(Resources resources, ActivityThread mainThread) {
1682        mPackageInfo = null;
1683        mBasePackageName = null;
1684        mResources = resources;
1685        mMainThread = mainThread;
1686        mContentResolver = new ApplicationContentResolver(this, mainThread);
1687    }
1688
1689    final void scheduleFinalCleanup(String who, String what) {
1690        mMainThread.scheduleContextCleanup(this, who, what);
1691    }
1692
1693    final void performFinalCleanup(String who, String what) {
1694        //Log.i(TAG, "Cleanup up context: " + this);
1695        mPackageInfo.removeContextRegistrations(getOuterContext(), who, what);
1696    }
1697
1698    final Context getReceiverRestrictedContext() {
1699        if (mReceiverRestrictedContext != null) {
1700            return mReceiverRestrictedContext;
1701        }
1702        return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext());
1703    }
1704
1705    final void setOuterContext(Context context) {
1706        mOuterContext = context;
1707    }
1708
1709    final Context getOuterContext() {
1710        return mOuterContext;
1711    }
1712
1713    final IBinder getActivityToken() {
1714        return mActivityToken;
1715    }
1716
1717    static void setFilePermissionsFromMode(String name, int mode,
1718            int extraPermissions) {
1719        int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR
1720            |FileUtils.S_IRGRP|FileUtils.S_IWGRP
1721            |extraPermissions;
1722        if ((mode&MODE_WORLD_READABLE) != 0) {
1723            perms |= FileUtils.S_IROTH;
1724        }
1725        if ((mode&MODE_WORLD_WRITEABLE) != 0) {
1726            perms |= FileUtils.S_IWOTH;
1727        }
1728        if (DEBUG) {
1729            Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode)
1730                  + ", perms=0x" + Integer.toHexString(perms));
1731        }
1732        FileUtils.setPermissions(name, perms, -1, -1);
1733    }
1734
1735    private File validateFilePath(String name, boolean createDirectory) {
1736        File dir;
1737        File f;
1738
1739        if (name.charAt(0) == File.separatorChar) {
1740            String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar));
1741            dir = new File(dirPath);
1742            name = name.substring(name.lastIndexOf(File.separatorChar));
1743            f = new File(dir, name);
1744        } else {
1745            dir = getDatabasesDir();
1746            f = makeFilename(dir, name);
1747        }
1748
1749        if (createDirectory && !dir.isDirectory() && dir.mkdir()) {
1750            FileUtils.setPermissions(dir.getPath(),
1751                FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1752                -1, -1);
1753        }
1754
1755        return f;
1756    }
1757
1758    private File makeFilename(File base, String name) {
1759        if (name.indexOf(File.separatorChar) < 0) {
1760            return new File(base, name);
1761        }
1762        throw new IllegalArgumentException(
1763                "File " + name + " contains a path separator");
1764    }
1765
1766    // ----------------------------------------------------------------------
1767    // ----------------------------------------------------------------------
1768    // ----------------------------------------------------------------------
1769
1770    private static final class ApplicationContentResolver extends ContentResolver {
1771        public ApplicationContentResolver(Context context, ActivityThread mainThread) {
1772            super(context);
1773            mMainThread = mainThread;
1774        }
1775
1776        @Override
1777        protected IContentProvider acquireProvider(Context context, String name) {
1778            return mMainThread.acquireProvider(context, name, true);
1779        }
1780
1781        @Override
1782        protected IContentProvider acquireExistingProvider(Context context, String name) {
1783            return mMainThread.acquireExistingProvider(context, name, true);
1784        }
1785
1786        @Override
1787        public boolean releaseProvider(IContentProvider provider) {
1788            return mMainThread.releaseProvider(provider, true);
1789        }
1790
1791        @Override
1792        protected IContentProvider acquireUnstableProvider(Context c, String name) {
1793            return mMainThread.acquireProvider(c, name, false);
1794        }
1795
1796        @Override
1797        public boolean releaseUnstableProvider(IContentProvider icp) {
1798            return mMainThread.releaseProvider(icp, false);
1799        }
1800
1801        @Override
1802        public void unstableProviderDied(IContentProvider icp) {
1803            mMainThread.handleUnstableProviderDied(icp.asBinder(), true);
1804        }
1805
1806        private final ActivityThread mMainThread;
1807    }
1808}
1809