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