Bug 1229620 - Replace #ifdefs in b2g/ code by AppConstants r=timdream
authorFabrice Desré <fabrice@mozilla.com>
Thu, 03 Dec 2015 09:14:07 -0800
changeset 314042 92aebcffdfa972709c86c56bd255b2c360ea3d17
parent 314041 6b5f8dba7afa5a24748add72d95f385b5acf07ab
child 314043 8815619f5425bc331d1ff160ccf4a047725575cd
push id8167
push userarmenzg@mozilla.com
push dateFri, 04 Dec 2015 00:22:30 +0000
reviewerstimdream
bugs1229620
milestone45.0a1
Bug 1229620 - Replace #ifdefs in b2g/ code by AppConstants r=timdream
.eslintignore
b2g/chrome/content/devtools/debugger.js
b2g/chrome/content/settings.js
b2g/chrome/content/shell.js
b2g/chrome/jar.mn
b2g/components/DirectoryProvider.js
b2g/components/HelperAppDialog.js
b2g/components/KillSwitchMain.jsm
b2g/components/RecoveryService.js
b2g/components/UpdatePrompt.js
b2g/components/moz.build
toolkit/modules/AppConstants.jsm
--- a/.eslintignore
+++ b/.eslintignore
@@ -4,17 +4,16 @@
 # Exclude expected objdirs.
 obj*/**
 
 # We ignore all these directories by default, until we get them enabled.
 # If you are enabling a directory, please add directory specific exclusions
 # below.
 accessible/**
 addon-sdk/**
-b2g/**
 build/**
 caps/**
 chrome/**
 config/**
 db/**
 docshell/**
 dom/**
 editor/**
@@ -50,16 +49,21 @@ tools/**
 uriloader/**
 view/**
 webapprt/**
 widget/**
 xpcom/**
 xpfe/**
 xulrunner/**
 
+# b2g exclusions (pref files).
+b2g/app/b2g.js
+b2g/graphene/graphene.js
+b2g/locales/en-US/b2g-l10n.js
+
 # browser/ exclusions
 browser/app/**
 browser/base/content/browser-social.js
 browser/base/content/nsContextMenu.js
 browser/base/content/sanitizeDialog.js
 browser/base/content/test/**
 browser/base/content/newtab/**
 browser/components/customizableui/**
--- a/b2g/chrome/content/devtools/debugger.js
+++ b/b2g/chrome/content/devtools/debugger.js
@@ -214,21 +214,21 @@ var RemoteDebugger = {
         } : DebuggerServer.globalActorFactories
       };
       let { RootActor } = devtools.require("devtools/server/actors/root");
       let root = new RootActor(connection, parameters);
       root.applicationType = "operating-system";
       return root;
     };
 
-#ifdef MOZ_WIDGET_GONK
-    DebuggerServer.on("connectionchange", function() {
-      AdbController.updateState();
-    });
-#endif
+    if (isGonk) {
+      DebuggerServer.on("connectionchange", function() {
+        AdbController.updateState();
+      });
+    }
   }
 };
 
 RemoteDebugger.allowConnection =
   RemoteDebugger.allowConnection.bind(RemoteDebugger);
 RemoteDebugger.receiveOOB =
   RemoteDebugger.receiveOOB.bind(RemoteDebugger);
 
@@ -368,19 +368,17 @@ var WiFiRemoteDebugger = {
     try {
       (value == "adb-devtools") ? USBRemoteDebugger.start()
                                 : USBRemoteDebugger.stop();
     } catch(e) {
       dump("Error while initializing USB devtools: " +
            e + "\n" + e.stack + "\n");
     }
 
-#ifdef MOZ_WIDGET_GONK
-    AdbController.setRemoteDebuggerState(value != "disabled");
-#endif
+    isGonk && AdbController.setRemoteDebuggerState(value != "disabled");
   });
 
   SettingsListener.observe("devtools.remote.wifi.enabled", false,
                            function(value) {
     devtoolsWiFi = value;
     Services.prefs.setBoolPref("devtools.debugger.remote-enabled",
                                devtoolsUSB || devtoolsWiFi);
     // Allow remote debugging on non-local interfaces when WiFi debug is enabled
--- a/b2g/chrome/content/settings.js
+++ b/b2g/chrome/content/settings.js
@@ -17,22 +17,24 @@ var Cr = Components.results;
 // prior to using SettingsListener otherwise there is a race in acquiring the
 // lock and fulfilling it. If we ever move SettingsListener or this file down in
 // the load order of shell.html things will likely break.
 Cu.import('resource://gre/modules/SettingsRequestManager.jsm');
 Cu.import('resource://gre/modules/XPCOMUtils.jsm');
 Cu.import('resource://gre/modules/Services.jsm');
 Cu.import('resource://gre/modules/AppConstants.jsm');
 
-#ifdef MOZ_WIDGET_GONK
-XPCOMUtils.defineLazyGetter(this, "libcutils", function () {
-  Cu.import("resource://gre/modules/systemlibs.js");
-  return libcutils;
-});
-#endif
+const isGonk = AppConstants.platform === 'gonk';
+
+if (isGonk) {
+  XPCOMUtils.defineLazyGetter(this, "libcutils", function () {
+    Cu.import("resource://gre/modules/systemlibs.js");
+    return libcutils;
+  });
+}
 
 XPCOMUtils.defineLazyServiceGetter(this, "uuidgen",
                                    "@mozilla.org/uuid-generator;1",
                                    "nsIUUIDGenerator");
 
 XPCOMUtils.defineLazyServiceGetter(this, "gPACGenerator",
                                    "@mozilla.org/pac-generator;1",
                                    "nsIPACGenerator");
@@ -147,39 +149,37 @@ SettingsListener.observe('language.curre
 })();
 
 //=================== DeviceInfo ====================
 Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
 Components.utils.import('resource://gre/modules/ctypes.jsm');
 (function DeviceInfoToSettings() {
   // MOZ_B2G_VERSION is set in b2g/confvars.sh, and is output as a #define value
   // from configure.in, defaults to 1.0.0 if this value is not exist.
-#filter attemptSubstitution
-  let os_version = '@MOZ_B2G_VERSION@';
-  let os_name = '@MOZ_B2G_OS_NAME@';
-#unfilter attemptSubstitution
+  let os_version = AppConstants.MOZ_B2G_VERSION;
+  let os_name = AppConstants.MOZ_B2G_OS_NAME;
 
   let appInfo = Cc["@mozilla.org/xre/app-info;1"]
                   .getService(Ci.nsIXULAppInfo);
 
   // Get the hardware info and firmware revision from device properties.
   let hardware_info = null;
   let firmware_revision = null;
   let product_manufacturer = null;
   let product_model = null;
   let product_device = null;
   let build_number = null;
-#ifdef MOZ_WIDGET_GONK
+  if (isGonk) {
     hardware_info = libcutils.property_get('ro.hardware');
     firmware_revision = libcutils.property_get('ro.firmware_revision');
     product_manufacturer = libcutils.property_get('ro.product.manufacturer');
     product_model = libcutils.property_get('ro.product.model');
     product_device = libcutils.property_get('ro.product.device');
     build_number = libcutils.property_get('ro.build.version.incremental');
-#endif
+  }
 
   // Populate deviceinfo settings,
   // copying any existing deviceinfo.os into deviceinfo.previous_os
   let lock = window.navigator.mozSettings.createLock();
   let req = lock.get('deviceinfo.os');
   req.onsuccess = req.onerror = () => {
     let previous_os = req.result && req.result['deviceinfo.os'] || '';
     let software = os_name + ' ' + os_version;
@@ -213,42 +213,41 @@ SettingsListener.observe('devtools.overl
     developerHUD.init();
   } else {
     if (developerHUD) {
       developerHUD.uninit();
     }
   }
 });
 
-#ifdef MOZ_WIDGET_GONK
-
-var LogShake;
-(function() {
-  let scope = {};
-  Cu.import('resource://gre/modules/LogShake.jsm', scope);
-  LogShake = scope.LogShake;
-  LogShake.init();
-})();
+if (isGonk) {
+  var LogShake;
+  (function() {
+    let scope = {};
+    Cu.import('resource://gre/modules/LogShake.jsm', scope);
+    LogShake = scope.LogShake;
+    LogShake.init();
+  })();
 
-SettingsListener.observe('devtools.logshake.enabled', false, value => {
-  if (value) {
-    LogShake.enableDeviceMotionListener();
-  } else {
-    LogShake.disableDeviceMotionListener();
-  }
-});
+  SettingsListener.observe('devtools.logshake.enabled', false, value => {
+    if (value) {
+      LogShake.enableDeviceMotionListener();
+    } else {
+      LogShake.disableDeviceMotionListener();
+    }
+  });
 
-SettingsListener.observe('devtools.logshake.qa_enabled', false, value => {
-  if (value) {
-    LogShake.enableQAMode();
-  } else {
-    LogShake.disableQAMode();
-  }
-});
-#endif
+  SettingsListener.observe('devtools.logshake.qa_enabled', false, value => {
+    if (value) {
+      LogShake.enableQAMode();
+    } else {
+      LogShake.disableQAMode();
+    }
+  });
+}
 
 // =================== Device Storage ====================
 SettingsListener.observe('device.storage.writable.name', 'sdcard', function(value) {
   if (Services.prefs.getPrefType('device.storage.writable.name') != Ci.nsIPrefBranch.PREF_STRING) {
     // We clear the pref because it used to be erroneously written as a bool
     // and we need to clear it before we can change it to have the correct type.
     Services.prefs.clearUserPref('device.storage.writable.name');
   }
@@ -375,25 +374,23 @@ setUpdateTrackingId();
   //3. presence of ro.display.colorfill at the Gonk level
 
   var req = navigator.mozSettings.createLock().get('layers.composer2d.enabled');
   req.onsuccess = function() {
     if (typeof(req.result['layers.composer2d.enabled']) === 'undefined') {
       var enabled = false;
       if (Services.prefs.getPrefType('layers.composer2d.enabled') == Ci.nsIPrefBranch.PREF_BOOL) {
         enabled = Services.prefs.getBoolPref('layers.composer2d.enabled');
-      } else {
-#ifdef MOZ_WIDGET_GONK
+      } else if (isGonk) {
         let androidVersion = libcutils.property_get("ro.build.version.sdk");
         if (androidVersion >= 17 ) {
           enabled = true;
         } else {
           enabled = (libcutils.property_get('ro.display.colorfill') === '1');
         }
-#endif
       }
       navigator.mozSettings.createLock().set({'layers.composer2d.enabled': enabled });
     }
 
     SettingsListener.observe("layers.composer2d.enabled", true, function(value) {
       Services.prefs.setBoolPref("layers.composer2d.enabled", value);
     });
   };
@@ -438,21 +435,17 @@ setUpdateTrackingId();
   let geckoPrefName = 'toolkit.telemetry.enabled';
   SettingsListener.observe(gaiaSettingName, null, function(value) {
     if (value !== null) {
       // Gaia setting has been set; update Gecko pref to that.
       Services.prefs.setBoolPref(geckoPrefName, value);
       return;
     }
     // Gaia setting has not been set; set the gaia setting to default.
-#ifdef MOZ_TELEMETRY_ON_BY_DEFAULT
-    let prefValue = true;
-#else
-    let prefValue = false;
-#endif
+    let prefValue = AppConstants.MOZ_TELEMETRY_ON_BY_DEFAULT;
     try {
       prefValue = Services.prefs.getBoolPref(geckoPrefName);
     } catch (e) {
       // Pref not set; use default value.
     }
     let setting = {};
     setting[gaiaSettingName] = prefValue;
     window.navigator.mozSettings.createLock().set(setting);
@@ -566,57 +559,57 @@ SettingsListener.observe("theme.selected
   SettingsListener.observe('browser.proxy.port', 0, function(value) {
     Services.prefs.setIntPref('network.proxy.browsing.port', value);
     setPAC();
   });
 
   setPAC();
 })();
 
-#ifdef MOZ_B2G_RIL
-XPCOMUtils.defineLazyModuleGetter(this, "AppsUtils",
-                                  "resource://gre/modules/AppsUtils.jsm");
-
 // ======================= Dogfooders FOTA ==========================
-SettingsListener.observe('debug.performance_data.dogfooding', false,
-  isDogfooder => {
-    if (!isDogfooder) {
-      dump('AUS:Settings: Not a dogfooder!\n');
-      return;
-    }
+if (AppConstants.MOZ_B2G_RIL) {
+  XPCOMUtils.defineLazyModuleGetter(this, "AppsUtils",
+                                    "resource://gre/modules/AppsUtils.jsm");
 
-    if (!('mozTelephony' in navigator)) {
-      dump('AUS:Settings: There is no mozTelephony!\n');
-      return;
-    }
+  SettingsListener.observe('debug.performance_data.dogfooding', false,
+    isDogfooder => {
+      if (!isDogfooder) {
+        dump('AUS:Settings: Not a dogfooder!\n');
+        return;
+      }
 
-    if (!('mozMobileConnections' in navigator)) {
-      dump('AUS:Settings: There is no mozMobileConnections!\n');
-      return;
-    }
-
-    let conn = navigator.mozMobileConnections[0];
-    conn.addEventListener('radiostatechange', function onradiostatechange() {
-      if (conn.radioState !== 'enabled') {
+      if (!('mozTelephony' in navigator)) {
+        dump('AUS:Settings: There is no mozTelephony!\n');
         return;
       }
 
-      conn.removeEventListener('radiostatechange', onradiostatechange);
-      navigator.mozTelephony.dial('*#06#').then(call => {
-        return call.result.then(res => {
-          if (res.success && res.statusMessage
-              && (res.serviceCode === 'scImei')) {
-            Services.prefs.setCharPref("app.update.imei_hash",
-                                       AppsUtils.computeHash(res.statusMessage, "SHA512"));
-          }
+      if (!('mozMobileConnections' in navigator)) {
+        dump('AUS:Settings: There is no mozMobileConnections!\n');
+        return;
+      }
+
+      let conn = navigator.mozMobileConnections[0];
+      conn.addEventListener('radiostatechange', function onradiostatechange() {
+        if (conn.radioState !== 'enabled') {
+          return;
+        }
+
+        conn.removeEventListener('radiostatechange', onradiostatechange);
+        navigator.mozTelephony.dial('*#06#').then(call => {
+          return call.result.then(res => {
+            if (res.success && res.statusMessage
+                && (res.serviceCode === 'scImei')) {
+              Services.prefs.setCharPref("app.update.imei_hash",
+                                         AppsUtils.computeHash(res.statusMessage, "SHA512"));
+            }
+          });
         });
       });
     });
-  });
-#endif
+}
 
 // =================== Various simple mapping  ======================
 var settingsToObserve = {
   'accessibility.screenreader_quicknav_modes': {
     prefName: 'accessibility.accessfu.quicknav_modes',
     resetToPref: true,
     defaultValue: ''
   },
@@ -658,28 +651,21 @@ var settingsToObserve = {
   'dom.presentation.discovery.enabled': false,
   'dom.presentation.discoverable': false,
   'dom.serviceWorkers.interception.enabled': true,
   'dom.serviceWorkers.testing.enabled': false,
   'gfx.layerscope.enabled': false,
   'layers.draw-borders': false,
   'layers.draw-tile-borders': false,
   'layers.dump': false,
-#ifdef XP_WIN
-  'layers.enable-tiles': false,
-#else
+  'layers.enable-tiles': AppConstants.platform !== "win",
   'layers.enable-tiles': true,
-#endif
   'layers.effect.invert': false,
   'layers.effect.grayscale': false,
   'layers.effect.contrast': '0.0',
-#ifdef MOZ_GRAPHENE
-  // Restart required
-  'layers.async-pan-zoom.enabled': false,
-#endif
   'layout.display-list.dump': false,
   'mms.debugging.enabled': false,
   'network.debugging.enabled': false,
   'privacy.donottrackheader.enabled': false,
   'privacy.trackingprotection.enabled': false,
   'ril.debugging.enabled': false,
   'ril.radio.disabled': false,
   'ril.mms.requestReadReport.enabled': {
@@ -724,16 +710,21 @@ var settingsToObserve = {
   },
   'ui.click_hold_context_menus.delay': {
     resetToPref: true
   },
   'wap.UAProf.tagname': 'x-wap-profile',
   'wap.UAProf.url': ''
 };
 
+if (AppConstants.MOZ_GRAPHENE) {
+  // Restart required
+  settingsToObserve['layers.async-pan-zoom.enabled'] = false;
+}
+
 function settingObserver(setPref, prefName, setting) {
   return value => {
     setPref(prefName, value);
     if (setting.notifyChange) {
       SystemAppProxy._sendCustomEvent('mozPrefChromeEvent', {
         prefName: prefName,
         value: value
       });
--- a/b2g/chrome/content/shell.js
+++ b/b2g/chrome/content/shell.js
@@ -14,21 +14,23 @@ Cu.import('resource://gre/modules/Notifi
 Cu.import('resource://gre/modules/Payment.jsm');
 Cu.import("resource://gre/modules/AppsUtils.jsm");
 Cu.import('resource://gre/modules/UserAgentOverrides.jsm');
 Cu.import('resource://gre/modules/Keyboard.jsm');
 Cu.import('resource://gre/modules/ErrorPage.jsm');
 Cu.import('resource://gre/modules/AlertsHelper.jsm');
 Cu.import('resource://gre/modules/RequestSyncService.jsm');
 Cu.import('resource://gre/modules/SystemUpdateService.jsm');
-#ifdef MOZ_WIDGET_GONK
-Cu.import('resource://gre/modules/MultiscreenHandler.jsm');
-Cu.import('resource://gre/modules/NetworkStatsService.jsm');
-Cu.import('resource://gre/modules/ResourceStatsService.jsm');
-#endif
+
+if (isGonk) {
+  Cu.import('resource://gre/modules/MultiscreenHandler.jsm');
+  Cu.import('resource://gre/modules/NetworkStatsService.jsm');
+  Cu.import('resource://gre/modules/ResourceStatsService.jsm');
+}
+
 Cu.import('resource://gre/modules/KillSwitchMain.jsm');
 
 // Identity
 Cu.import('resource://gre/modules/SignInToWebsite.jsm');
 SignInToWebsiteController.init();
 
 Cu.import('resource://gre/modules/FxAccountsMgmtService.jsm');
 Cu.import('resource://gre/modules/DownloadsAPI.jsm');
@@ -57,31 +59,31 @@ XPCOMUtils.defineLazyServiceGetter(this,
                                    '@mozilla.org/system-message-internal;1',
                                    'nsISystemMessagesInternal');
 
 XPCOMUtils.defineLazyGetter(this, "ppmm", function() {
   return Cc["@mozilla.org/parentprocessmessagemanager;1"]
          .getService(Ci.nsIMessageListenerManager);
 });
 
-#ifdef MOZ_WIDGET_GONK
-XPCOMUtils.defineLazyGetter(this, "libcutils", function () {
-  Cu.import("resource://gre/modules/systemlibs.js");
-  return libcutils;
-});
-#endif
+if (isGonk) {
+  XPCOMUtils.defineLazyGetter(this, "libcutils", function () {
+    Cu.import("resource://gre/modules/systemlibs.js");
+    return libcutils;
+  });
+}
 
 XPCOMUtils.defineLazyServiceGetter(Services, 'captivePortalDetector',
                                   '@mozilla.org/toolkit/captive-detector;1',
                                   'nsICaptivePortalDetector');
 
-#ifdef MOZ_SAFE_BROWSING
-XPCOMUtils.defineLazyModuleGetter(this, "SafeBrowsing",
-              "resource://gre/modules/SafeBrowsing.jsm");
-#endif
+if (AppConstants.MOZ_SAFE_BROWSING) {
+  XPCOMUtils.defineLazyModuleGetter(this, "SafeBrowsing",
+                "resource://gre/modules/SafeBrowsing.jsm");
+}
 
 XPCOMUtils.defineLazyModuleGetter(this, "SafeMode",
                                   "resource://gre/modules/SafeMode.jsm");
 
 window.performance.measure('gecko-shell-jsm-loaded', 'gecko-shell-loadstart');
 
 function debug(str) {
   dump(' -*- Shell.js: ' + str + '\n');
@@ -115,35 +117,31 @@ function clearCacheAndReload() {
 }
 
 function restart() {
   let appStartup = Cc['@mozilla.org/toolkit/app-startup;1']
                      .getService(Ci.nsIAppStartup);
   appStartup.quit(Ci.nsIAppStartup.eForceQuit | Ci.nsIAppStartup.eRestart);
 }
 
-#ifdef MOZ_CRASHREPORTER
 function debugCrashReport(aStr) {
-  dump('Crash reporter : ' + aStr);
+  AppConstants.MOZ_CRASHREPORTER && dump('Crash reporter : ' + aStr);
 }
-#else
-function debugCrashReport(aStr) {}
-#endif
 
 var shell = {
 
   get CrashSubmit() {
     delete this.CrashSubmit;
-#ifdef MOZ_CRASHREPORTER
-    Cu.import("resource://gre/modules/CrashSubmit.jsm", this);
-    return this.CrashSubmit;
-#else
-    dump('Crash reporter : disabled at build time.');
-    return this.CrashSubmit = null;
-#endif
+    if (AppConstants.MOZ_CRASHREPORTER) {
+      Cu.import("resource://gre/modules/CrashSubmit.jsm", this);
+      return this.CrashSubmit;
+    } else {
+      dump('Crash reporter : disabled at build time.');
+      return this.CrashSubmit = null;
+    }
   },
 
   onlineForCrashReport: function shell_onlineForCrashReport() {
     let wifiManager = navigator.mozWifiManager;
     let onWifi = (wifiManager &&
                   (wifiManager.connection.status == 'connected'));
     return !Services.io.offline && onWifi;
   },
@@ -260,54 +258,52 @@ var shell = {
   },
 
   _started: false,
   hasStarted: function shell_hasStarted() {
     return this._started;
   },
 
   bootstrap: function() {
-#ifdef MOZ_B2GDROID
-    Cc["@mozilla.org/b2g/b2gdroid-setup;1"]
-      .getService(Ci.nsIObserver).observe(window, "shell-startup", null);
-#endif
+    if (AppConstants.MOZ_B2GDROID) {
+      Cc["@mozilla.org/b2g/b2gdroid-setup;1"]
+        .getService(Ci.nsIObserver).observe(window, "shell-startup", null);
+    }
 
     window.performance.mark('gecko-shell-bootstrap');
 
     // Before anything, check if we want to start in safe mode.
     SafeMode.check(window).then(() => {
       let startManifestURL =
         Cc['@mozilla.org/commandlinehandler/general-startup;1?type=b2gbootstrap']
           .getService(Ci.nsISupports).wrappedJSObject.startManifestURL;
 
-#ifdef MOZ_GRAPHENE
       // If --start-manifest hasn't been specified, we re-use the latest specified manifest.
       // If it's the first launch, we will fallback to b2g.default.start_manifest_url
-      if (!startManifestURL) {
+      if (AppConstants.MOZ_GRAPHENE && !startManifestURL) {
         try {
           startManifestURL = Services.prefs.getCharPref("b2g.system_manifest_url");
         } catch(e) {}
       }
-#endif
 
       if (!startManifestURL) {
         try {
           startManifestURL = Services.prefs.getCharPref("b2g.default.start_manifest_url");
         } catch(e) {}
       }
 
       if (startManifestURL) {
         Cu.import('resource://gre/modules/Bootstraper.jsm');
-#ifdef MOZ_GRAPHENE
-        if (Bootstraper.isInstallRequired(startManifestURL)) {
+
+        if (AppConstants.MOZ_GRAPHENE && Bootstraper.isInstallRequired(startManifestURL)) {
           // Installing the app my take some time. We don't want to keep the
           // native window hidden.
           showInstallScreen();
         }
-#endif
+
         Bootstraper.ensureSystemAppInstall(startManifestURL)
                    .then(this.start.bind(this))
                    .catch(Bootstraper.bailout);
       } else {
         this.start();
       }
     });
   },
@@ -329,44 +325,44 @@ var shell = {
       try {
         let dogfoodId = Services.prefs.getCharPref('prerelease.dogfood.id');
         if (dogfoodId != "") {
           cr.annotateCrashReport("Email", dogfoodId);
         }
       }
       catch (e) { }
 
-#ifdef MOZ_WIDGET_GONK
-      // Annotate crash report
-      let annotations = [ [ "Android_Hardware",     "ro.hardware" ],
-                          [ "Android_Device",       "ro.product.device" ],
-                          [ "Android_CPU_ABI2",     "ro.product.cpu.abi2" ],
-                          [ "Android_CPU_ABI",      "ro.product.cpu.abi" ],
-                          [ "Android_Manufacturer", "ro.product.manufacturer" ],
-                          [ "Android_Brand",        "ro.product.brand" ],
-                          [ "Android_Model",        "ro.product.model" ],
-                          [ "Android_Board",        "ro.product.board" ],
-        ];
+      if (isGonk) {
+        // Annotate crash report
+        let annotations = [ [ "Android_Hardware",     "ro.hardware" ],
+                            [ "Android_Device",       "ro.product.device" ],
+                            [ "Android_CPU_ABI2",     "ro.product.cpu.abi2" ],
+                            [ "Android_CPU_ABI",      "ro.product.cpu.abi" ],
+                            [ "Android_Manufacturer", "ro.product.manufacturer" ],
+                            [ "Android_Brand",        "ro.product.brand" ],
+                            [ "Android_Model",        "ro.product.model" ],
+                            [ "Android_Board",        "ro.product.board" ],
+          ];
 
-      annotations.forEach(function (element) {
-          cr.annotateCrashReport(element[0], libcutils.property_get(element[1]));
-        });
+        annotations.forEach(function (element) {
+            cr.annotateCrashReport(element[0], libcutils.property_get(element[1]));
+          });
 
-      let androidVersion = libcutils.property_get("ro.build.version.sdk") +
-                           "(" + libcutils.property_get("ro.build.version.codename") + ")";
-      cr.annotateCrashReport("Android_Version", androidVersion);
+        let androidVersion = libcutils.property_get("ro.build.version.sdk") +
+                             "(" + libcutils.property_get("ro.build.version.codename") + ")";
+        cr.annotateCrashReport("Android_Version", androidVersion);
 
-      SettingsListener.observe("deviceinfo.os", "", function(value) {
-        try {
-          let cr = Cc["@mozilla.org/xre/app-info;1"]
-                     .getService(Ci.nsICrashReporter);
-          cr.annotateCrashReport("B2G_OS_Version", value);
-        } catch(e) { }
-      });
-#endif
+        SettingsListener.observe("deviceinfo.os", "", function(value) {
+          try {
+            let cr = Cc["@mozilla.org/xre/app-info;1"]
+                       .getService(Ci.nsICrashReporter);
+            cr.annotateCrashReport("B2G_OS_Version", value);
+          } catch(e) { }
+        });
+      }
     } catch(e) {
       debugCrashReport('exception: ' + e);
     }
 
     let homeURL = this.homeURL;
     if (!homeURL) {
       let msg = 'Fatal error during startup: No homescreen found: try setting B2G_HOMESCREEN';
       alert(msg);
@@ -380,33 +376,35 @@ var shell = {
     let systemAppFrame =
       document.createElementNS('http://www.w3.org/1999/xhtml', 'html:iframe');
     systemAppFrame.setAttribute('id', 'systemapp');
     systemAppFrame.setAttribute('mozbrowser', 'true');
     systemAppFrame.setAttribute('mozapp', manifestURL);
     systemAppFrame.setAttribute('allowfullscreen', 'true');
     systemAppFrame.setAttribute('src', 'blank.html');
     let container = document.getElementById('container');
-#ifdef MOZ_WIDGET_COCOA
-    // See shell.html
-    let hotfix = document.getElementById('placeholder');
-    if (hotfix) {
-      container.removeChild(hotfix);
+
+    if (AppConstants.platform == 'macosx') {
+      // See shell.html
+      let hotfix = document.getElementById('placeholder');
+      if (hotfix) {
+        container.removeChild(hotfix);
+      }
     }
-#endif
+
     this.contentBrowser = container.appendChild(systemAppFrame);
 
     let webNav = systemAppFrame.contentWindow
                                .QueryInterface(Ci.nsIInterfaceRequestor)
                                .getInterface(Ci.nsIWebNavigation);
     webNav.sessionHistory = Cc["@mozilla.org/browser/shistory;1"].createInstance(Ci.nsISHistory);
 
-#ifdef MOZ_GRAPHENE
-    webNav.QueryInterface(Ci.nsIDocShell).windowDraggingAllowed = true;
-#endif
+    if (AppConstants.MOZ_GRAPHENE) {
+      webNav.QueryInterface(Ci.nsIDocShell).windowDraggingAllowed = true;
+    }
 
     let audioChannels = systemAppFrame.allowedAudioChannels;
     audioChannels && audioChannels.forEach(function(audioChannel) {
       // Set all audio channels as unmuted by default
       // because some audio in System app will be played
       // before AudioChannelService[1] is Gaia is loaded.
       // [1]: https://github.com/mozilla-b2g/gaia/blob/master/apps/system/js/audio_channel_service.js
       audioChannel.setMuted(false);
@@ -446,21 +444,22 @@ var shell = {
 
     window.performance.mark('gecko-shell-system-frame-set');
 
     ppmm.addMessageListener("content-handler", this);
     ppmm.addMessageListener("dial-handler", this);
     ppmm.addMessageListener("sms-handler", this);
     ppmm.addMessageListener("mail-handler", this);
     ppmm.addMessageListener("file-picker", this);
-#ifdef MOZ_SAFE_BROWSING
-    setTimeout(function() {
-      SafeBrowsing.init();
-    }, 5000);
-#endif
+
+    if (AppConstants.MOZ_SAFE_BROWSING) {
+      setTimeout(function() {
+        SafeBrowsing.init();
+      }, 5000);
+    }
   },
 
   stop: function shell_stop() {
     window.removeEventListener('unload', this);
     window.removeEventListener('keydown', this, true);
     window.removeEventListener('keyup', this, true);
     window.removeEventListener('MozApplicationManifest', this);
     window.removeEventListener('sizemodechange', this);
@@ -749,55 +748,50 @@ var shell = {
     this.reportCrash(true);
 
     SystemAppProxy.registerFrame(shell.contentBrowser);
 
     this.sendEvent(window, 'ContentStart');
 
     Services.obs.notifyObservers(null, 'content-start', null);
 
-#ifdef MOZ_WIDGET_GONK
-    Cu.import('resource://gre/modules/OperatorApps.jsm');
-#endif
+    isGonk && Cu.import('resource://gre/modules/OperatorApps.jsm');
 
-#ifdef MOZ_GRAPHENE
-    if (Services.prefs.getBoolPref("b2g.nativeWindowGeometry.fullscreen")) {
+    if (AppConstants.MOZ_GRAPHENE &&
+        Services.prefs.getBoolPref("b2g.nativeWindowGeometry.fullscreen")) {
       window.fullScreen = true;
     }
-#endif
 
     shell.handleCmdLine();
   },
 
   handleCmdLine: function() {
-  // This isn't supported on devices.
-#ifndef ANDROID
-    let b2gcmds = Cc["@mozilla.org/commandlinehandler/general-startup;1?type=b2gcmds"]
-                    .getService(Ci.nsISupports);
-    let args = b2gcmds.wrappedJSObject.cmdLine;
-    try {
-      // Returns null if -url is not present.
-      let url = args.handleFlagWithParam("url", false);
-      if (url) {
-        this.sendChromeEvent({type: "mozbrowseropenwindow", url});
-        args.preventDefault = true;
+    // This isn't supported on devices.
+    if (!isGonk && !AppConstants.MOZ_B2GDROID) {
+      let b2gcmds = Cc["@mozilla.org/commandlinehandler/general-startup;1?type=b2gcmds"]
+                      .getService(Ci.nsISupports);
+      let args = b2gcmds.wrappedJSObject.cmdLine;
+      try {
+        // Returns null if -url is not present.
+        let url = args.handleFlagWithParam("url", false);
+        if (url) {
+          this.sendChromeEvent({type: "mozbrowseropenwindow", url});
+          args.preventDefault = true;
+        }
+      } catch(e) {
+        // Throws if -url is present with no params.
       }
-    } catch(e) {
-      // Throws if -url is present with no params.
     }
-#endif
   },
 
   // This gets called when window.onload fires on the System app content window,
   // which means things in <html> are parsed and statically referenced <script>s
   // and <script defer>s are loaded and run.
   notifyContentWindowLoaded: function shell_notifyContentWindowLoaded() {
-#ifdef MOZ_WIDGET_GONK
-    libcutils.property_set('sys.boot_completed', '1');
-#endif
+    isGonk && libcutils.property_set('sys.boot_completed', '1');
 
     // This will cause Gonk Widget to remove boot animation from the screen
     // and reveals the page.
     Services.obs.notifyObservers(null, "browser-ui-startup-complete", "");
 
     SystemAppProxy.setIsLoaded();
   },
 
@@ -1119,29 +1113,31 @@ window.addEventListener('ContentStart', 
     }
   });
 });
 
 window.addEventListener('ContentStart', function update_onContentStart() {
   Cu.import('resource://gre/modules/WebappsUpdater.jsm');
   WebappsUpdater.handleContentStart(shell);
 
-#ifdef MOZ_UPDATER
+  if (!AppConstants.MOZ_UPDATER) {
+    return;
+  }
+
   let promptCc = Cc["@mozilla.org/updates/update-prompt;1"];
   if (!promptCc) {
     return;
   }
 
   let updatePrompt = promptCc.createInstance(Ci.nsIUpdatePrompt);
   if (!updatePrompt) {
     return;
   }
 
   updatePrompt.wrappedJSObject.handleContentStart(shell);
-#endif
 });
 
 (function geolocationStatusTracker() {
   let gGeolocationActive = false;
 
   Services.obs.addObserver(function(aSubject, aTopic, aData) {
     let oldState = gGeolocationActive;
     if (aData == "starting") {
@@ -1308,152 +1304,148 @@ window.addEventListener('ContentStart', 
   Services.obs.addObserver(function(aSubject, aTopic, aData) {
     shell.sendChromeEvent({
       type: 'volume-state-changed',
       active: (aData == 'Shared')
     });
 }, 'volume-state-changed', false);
 })();
 
-#ifdef MOZ_WIDGET_GONK
-// Devices don't have all the same partition size for /cache where we
-// store the http cache.
-(function setHTTPCacheSize() {
-  let path = Services.prefs.getCharPref("browser.cache.disk.parent_directory");
-  let volumeService = Cc["@mozilla.org/telephony/volume-service;1"]
-                        .getService(Ci.nsIVolumeService);
+if (isGonk) {
+  // Devices don't have all the same partition size for /cache where we
+  // store the http cache.
+  (function setHTTPCacheSize() {
+    let path = Services.prefs.getCharPref("browser.cache.disk.parent_directory");
+    let volumeService = Cc["@mozilla.org/telephony/volume-service;1"]
+                          .getService(Ci.nsIVolumeService);
 
-  let stats = volumeService.createOrGetVolumeByPath(path).getStats();
+    let stats = volumeService.createOrGetVolumeByPath(path).getStats();
 
-  // We must set the size in KB, and keep a bit of free space.
-  let size = Math.floor(stats.totalBytes / 1024) - 1024;
+    // We must set the size in KB, and keep a bit of free space.
+    let size = Math.floor(stats.totalBytes / 1024) - 1024;
 
-  // keep the default value if it is smaller than the physical partition size.
-  let oldSize = Services.prefs.getIntPref("browser.cache.disk.capacity");
-  if (size < oldSize) {
-    Services.prefs.setIntPref("browser.cache.disk.capacity", size);
-  }
-})();
-#endif
+    // keep the default value if it is smaller than the physical partition size.
+    let oldSize = Services.prefs.getIntPref("browser.cache.disk.capacity");
+    if (size < oldSize) {
+      Services.prefs.setIntPref("browser.cache.disk.capacity", size);
+    }
+  })();
 
-#ifdef MOZ_WIDGET_GONK
-try {
-  let gmpService = Cc["@mozilla.org/gecko-media-plugin-service;1"]
-                     .getService(Ci.mozIGeckoMediaPluginChromeService);
-  gmpService.addPluginDirectory("/system/b2g/gmp-clearkey/0.1");
-} catch(e) {
-  dump("Failed to add clearkey path! " + e + "\n");
+  try {
+    let gmpService = Cc["@mozilla.org/gecko-media-plugin-service;1"]
+                       .getService(Ci.mozIGeckoMediaPluginChromeService);
+    gmpService.addPluginDirectory("/system/b2g/gmp-clearkey/0.1");
+  } catch(e) {
+    dump("Failed to add clearkey path! " + e + "\n");
+  }
 }
-#endif
 
 // Calling this observer will cause a shutdown an a profile reset.
 // Use eg. : Services.obs.notifyObservers(null, 'b2g-reset-profile', null);
 Services.obs.addObserver(function resetProfile(subject, topic, data) {
   Services.obs.removeObserver(resetProfile, topic);
 
   // Listening for 'profile-before-change2' which is late in the shutdown
   // sequence, but still has xpcom access.
   Services.obs.addObserver(function clearProfile(subject, topic, data) {
     Services.obs.removeObserver(clearProfile, topic);
-#ifdef MOZ_WIDGET_GONK
-    let json = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
-    json.initWithPath('/system/b2g/webapps/webapps.json');
-    let toRemove = json.exists()
-      // This is a user build, just rm -r /data/local /data/b2g/mozilla
-      ? ['/data/local', '/data/b2g/mozilla']
-      // This is an eng build. We clear the profile and a set of files
-      // under /data/local.
-      : ['/data/b2g/mozilla',
-         '/data/local/permissions.sqlite',
-         '/data/local/storage',
-         '/data/local/OfflineCache'];
+    if (isGonk) {
+      let json = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
+      json.initWithPath('/system/b2g/webapps/webapps.json');
+      let toRemove = json.exists()
+        // This is a user build, just rm -r /data/local /data/b2g/mozilla
+        ? ['/data/local', '/data/b2g/mozilla']
+        // This is an eng build. We clear the profile and a set of files
+        // under /data/local.
+        : ['/data/b2g/mozilla',
+           '/data/local/permissions.sqlite',
+           '/data/local/storage',
+           '/data/local/OfflineCache'];
 
-    toRemove.forEach(function(dir) {
-      try {
-        let file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
-        file.initWithPath(dir);
-        file.remove(true);
-      } catch(e) { dump(e); }
-    });
-#else
-    // Desktop builds.
-    let profile = Services.dirsvc.get('ProfD', Ci.nsIFile);
+      toRemove.forEach(function(dir) {
+        try {
+          let file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
+          file.initWithPath(dir);
+          file.remove(true);
+        } catch(e) { dump(e); }
+      });
+    } else {
+      // Desktop builds.
+      let profile = Services.dirsvc.get('ProfD', Ci.nsIFile);
 
-    // We don't want to remove everything from the profile, since this
-    // would prevent us from starting up.
-    let whitelist = ['defaults', 'extensions', 'settings.json',
-                     'user.js', 'webapps'];
-    let enumerator = profile.directoryEntries;
-    while (enumerator.hasMoreElements()) {
-      let file = enumerator.getNext().QueryInterface(Ci.nsIFile);
-      if (whitelist.indexOf(file.leafName) == -1) {
-        file.remove(true);
+      // We don't want to remove everything from the profile, since this
+      // would prevent us from starting up.
+      let whitelist = ['defaults', 'extensions', 'settings.json',
+                       'user.js', 'webapps'];
+      let enumerator = profile.directoryEntries;
+      while (enumerator.hasMoreElements()) {
+        let file = enumerator.getNext().QueryInterface(Ci.nsIFile);
+        if (whitelist.indexOf(file.leafName) == -1) {
+          file.remove(true);
+        }
       }
     }
-#endif
   },
   'profile-before-change2', false);
 
   let appStartup = Cc['@mozilla.org/toolkit/app-startup;1']
                      .getService(Ci.nsIAppStartup);
   appStartup.quit(Ci.nsIAppStartup.eForceQuit);
 }, 'b2g-reset-profile', false);
 
-#ifdef MOZ_GRAPHENE
+if (AppConstants.MOZ_GRAPHENE) {
+  const restoreWindowGeometry = () => {
+    let screenX = Services.prefs.getIntPref("b2g.nativeWindowGeometry.screenX");
+    let screenY = Services.prefs.getIntPref("b2g.nativeWindowGeometry.screenY");
+    let width = Services.prefs.getIntPref("b2g.nativeWindowGeometry.width");
+    let height = Services.prefs.getIntPref("b2g.nativeWindowGeometry.height");
+
+    if (screenX == -1) {
+      // Center
+      screenX = (screen.width - width) / 2;
+      screenY = (screen.height - height) / 2;
+    }
+
+    moveTo(screenX, screenY);
+    resizeTo(width, height);
+  }
+  restoreWindowGeometry();
 
-const restoreWindowGeometry = () => {
-  let screenX = Services.prefs.getIntPref("b2g.nativeWindowGeometry.screenX");
-  let screenY = Services.prefs.getIntPref("b2g.nativeWindowGeometry.screenY");
-  let width = Services.prefs.getIntPref("b2g.nativeWindowGeometry.width");
-  let height = Services.prefs.getIntPref("b2g.nativeWindowGeometry.height");
+  const saveWindowGeometry = () => {
+    window.removeEventListener("unload", saveWindowGeometry);
+    Services.prefs.setIntPref("b2g.nativeWindowGeometry.screenX", screenX);
+    Services.prefs.setIntPref("b2g.nativeWindowGeometry.screenY", screenY);
+    Services.prefs.setIntPref("b2g.nativeWindowGeometry.width", outerWidth);
+    Services.prefs.setIntPref("b2g.nativeWindowGeometry.height", outerHeight);
+  }
+  window.addEventListener("unload", saveWindowGeometry);
 
-  if (screenX == -1) {
-    // Center
-    screenX = (screen.width - width) / 2;
-    screenY = (screen.height - height) / 2;
+  var baseWindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
+                         .getInterface(Ci.nsIWebNavigation)
+                         .QueryInterface(Ci.nsIDocShellTreeItem)
+                         .treeOwner
+                         .QueryInterface(Ci.nsIInterfaceRequestor)
+                         .getInterface(Ci.nsIBaseWindow);
+
+  const showNativeWindow = () => baseWindow.visibility = true;
+  const hideNativeWindow = () => baseWindow.visibility = false;
+
+  const showInstallScreen = () => {
+    const grapheneStrings =
+      Services.strings.createBundle('chrome://b2g-l10n/locale/graphene.properties');
+    document.querySelector('#installing > .message').textContent =
+      grapheneStrings.GetStringFromName('installing');
+    showNativeWindow();
   }
 
-  moveTo(screenX, screenY);
-  resizeTo(width, height);
-}
-restoreWindowGeometry();
-
-const saveWindowGeometry = () => {
-  window.removeEventListener("unload", saveWindowGeometry);
-  Services.prefs.setIntPref("b2g.nativeWindowGeometry.screenX", screenX);
-  Services.prefs.setIntPref("b2g.nativeWindowGeometry.screenY", screenY);
-  Services.prefs.setIntPref("b2g.nativeWindowGeometry.width", outerWidth);
-  Services.prefs.setIntPref("b2g.nativeWindowGeometry.height", outerHeight);
-}
-window.addEventListener("unload", saveWindowGeometry);
-
-var baseWindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
-                       .getInterface(Ci.nsIWebNavigation)
-                       .QueryInterface(Ci.nsIDocShellTreeItem)
-                       .treeOwner
-                       .QueryInterface(Ci.nsIInterfaceRequestor)
-                       .getInterface(Ci.nsIBaseWindow);
+  const hideInstallScreen = () => {
+    document.body.classList.add('content-loaded');
+  }
 
-const showNativeWindow = () => baseWindow.visibility = true;
-const hideNativeWindow = () => baseWindow.visibility = false;
-
-const showInstallScreen = () => {
-  const grapheneStrings =
-    Services.strings.createBundle('chrome://b2g-l10n/locale/graphene.properties');
-  document.querySelector('#installing > .message').textContent =
-    grapheneStrings.GetStringFromName('installing');
-  showNativeWindow();
-}
+  window.addEventListener('ContentStart', () => {
+    shell.contentBrowser.contentWindow.addEventListener('load', () => {
+      hideInstallScreen();
+      showNativeWindow();
+    });
+  });
 
-const hideInstallScreen = () => {
-  document.body.classList.add('content-loaded');
+  hideNativeWindow();
 }
-
-window.addEventListener('ContentStart', () => {
-  shell.contentBrowser.contentWindow.addEventListener('load', () => {
-    hideInstallScreen();
-    showNativeWindow();
-  });
-});
-
-hideNativeWindow();
-
-#endif
--- a/b2g/chrome/jar.mn
+++ b/b2g/chrome/jar.mn
@@ -4,28 +4,28 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 
 chrome.jar:
 % content branding %content/branding/ contentaccessible=yes
 % content b2g %content/
 
   content/arrow.svg                     (content/arrow.svg)
-* content/settings.js                   (content/settings.js)
+  content/settings.js                   (content/settings.js)
 * content/shell.html                    (content/shell.html)
-* content/shell.js                      (content/shell.js)
+  content/shell.js                      (content/shell.js)
   content/shell_remote.html             (content/shell_remote.html)
   content/shell_remote.js               (content/shell_remote.js)
 * content/shell.css                     (content/shell.css)
   content/blank.html                    (content/blank.html)
   content/blank.css                     (content/blank.css)
 #ifdef MOZ_WIDGET_GONK
   content/devtools/adb.js               (content/devtools/adb.js)
 #endif
-* content/devtools/debugger.js          (content/devtools/debugger.js)
+  content/devtools/debugger.js          (content/devtools/debugger.js)
   content/devtools/hud.js               (content/devtools/hud.js)
 #ifndef MOZ_WIDGET_GONK
   content/desktop.css                   (content/desktop.css)
   content/images/desktop/home-black.png (content/images/desktop/home-black.png)
   content/images/desktop/home-white.png (content/images/desktop/home-white.png)
   content/images/desktop/rotate.png     (content/images/desktop/rotate.png)
   content/desktop.js                    (content/desktop.js)
   content/screen.js                     (content/screen.js)
--- a/b2g/components/DirectoryProvider.js
+++ b/b2g/components/DirectoryProvider.js
@@ -4,16 +4,17 @@
 
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cu = Components.utils;
 const Cr = Components.results;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/AppConstants.jsm");
 
 const XRE_OS_UPDATE_APPLY_TO_DIR = "OSUpdApplyToD"
 const UPDATE_ARCHIVE_DIR = "UpdArchD"
 const LOCAL_DIR = "/data/local";
 const UPDATES_DIR = "updates/0";
 const FOTA_DIR = "updates/fota";
 const COREAPPSDIR_PREF = "b2g.coreappsdir"
 
@@ -52,18 +53,24 @@ function DirectoryProvider() {
 DirectoryProvider.prototype = {
   classID: Components.ID("{9181eb7c-6f87-11e1-90b1-4f59d80dd2e5}"),
 
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIDirectoryServiceProvider]),
   _xpcom_factory: XPCOMUtils.generateSingletonFactory(DirectoryProvider),
 
   _profD: null,
 
-  getFile: function dp_getFile(prop, persistent) {
-#ifdef MOZ_WIDGET_GONK
+  getFile: function(prop, persistent) {
+    if (AppConstants.platform === "gonk") {
+      return this.getFileOnGonk(prop, persistent);
+    }
+    return this.getFileNotGonk(prop, persistent);
+  },
+
+  getFileOnGonk: function(prop, persistent) {
     let localProps = ["cachePDir", "webappsDir", "PrefD", "indexedDBPDir",
                       "permissionDBPDir", "UpdRootD"];
     if (localProps.indexOf(prop) != -1) {
       let file = Cc["@mozilla.org/file/local;1"]
                    .createInstance(Ci.nsILocalFile)
       file.initWithPath(LOCAL_DIR);
       persistent.value = true;
       return file;
@@ -92,17 +99,20 @@ DirectoryProvider.prototype = {
     }
     if (prop == XRE_OS_UPDATE_APPLY_TO_DIR) {
       // getUpdateDir will set persistent to false since it may toggle between
       // /data/local/ and /mnt/sdcard based on free space and/or availability
       // of the sdcard.
       // before apply, check if free space is 1.1 times of update.mar
       return this.getUpdateDir(persistent, FOTA_DIR, 1.1);
     }
-#else
+    return null;
+  },
+
+  getFileNotGonk: function(prop, persistent) {
     // In desktop builds, coreAppsDir is the same as the profile
     // directory unless otherwise specified. We just need to get the
     // path from the parent, and it is then used to build
     // jar:remoteopenfile:// uris.
     if (prop == "coreAppsDir") {
       let coreAppsDirPref;
       try {
         coreAppsDirPref = Services.prefs.getCharPref(COREAPPSDIR_PREF);
@@ -132,17 +142,16 @@ DirectoryProvider.prototype = {
       if (!this._profD) {
         this._profD = cpmm.sendSyncMessage("getProfD", {})[0];
       }
       let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
       file.initWithPath(this._profD);
       persistent.value = true;
       return file;
     }
-#endif
     return null;
   },
 
   // The VolumeService only exists on the device, and not on desktop
   volumeHasFreeSpace: function dp_volumeHasFreeSpace(volumePath, requiredSpace) {
     if (!volumePath) {
       return false;
     }
--- a/b2g/components/HelperAppDialog.js
+++ b/b2g/components/HelperAppDialog.js
@@ -34,17 +34,17 @@ HelperAppLauncherDialog.prototype = {
   },
 
   promptForSaveToFileAsync: function(aLauncher,
                                      aContext,
                                      aDefaultFile,
                                      aSuggestedFileExt,
                                      aForcePrompt) {
     // Retrieve the user's default download directory.
-    Task.spawn(function() {
+    Task.spawn(function*() {
       let file = null;
       try {
         let defaultFolder = yield Downloads.getPreferredDownloadsDirectory();
         let dir = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
         dir.initWithPath(defaultFolder);
         file = this.validateLeafName(dir, aDefaultFile, aSuggestedFileExt);
       } catch(e) { }
       aLauncher.saveDestinationAvailable(file);
--- a/b2g/components/KillSwitchMain.jsm
+++ b/b2g/components/KillSwitchMain.jsm
@@ -5,16 +5,17 @@
 "use strict";
 
 this.EXPORTED_SYMBOLS = [ "KillSwitchMain" ];
 
 const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/AppConstants.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Promise", "resource://gre/modules/Promise.jsm");
 
 XPCOMUtils.defineLazyServiceGetter(this, "settings",
                    "@mozilla.org/settingsService;1",
                    "nsISettingsService");
 
@@ -22,24 +23,24 @@ XPCOMUtils.defineLazyServiceGetter(this,
                    "@mozilla.org/parentprocessmessagemanager;1",
                    "nsIMessageBroadcaster");
 
 XPCOMUtils.defineLazyGetter(this, "permMgr", function() {
   return Cc["@mozilla.org/permissionmanager;1"]
            .getService(Ci.nsIPermissionManager);
 });
 
-#ifdef MOZ_WIDGET_GONK
-XPCOMUtils.defineLazyGetter(this, "libcutils", function () {
-  Cu.import("resource://gre/modules/systemlibs.js");
-  return libcutils;
-});
-#else
-this.libcutils = null;
-#endif
+if (AppConstants.platform === "gonk") {
+  XPCOMUtils.defineLazyGetter(this, "libcutils", function () {
+    Cu.import("resource://gre/modules/systemlibs.js");
+    return libcutils;
+  });
+} else {
+  this.libcutils = null;
+}
 
 const DEBUG = false;
 
 const kEnableKillSwitch   = "KillSwitch:Enable";
 const kEnableKillSwitchOK = "KillSwitch:Enable:OK";
 const kEnableKillSwitchKO = "KillSwitch:Enable:KO";
 
 const kDisableKillSwitch   = "KillSwitch:Disable";
--- a/b2g/components/RecoveryService.js
+++ b/b2g/components/RecoveryService.js
@@ -4,76 +4,82 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 "use strict";
 
 const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/ctypes.jsm");
+Cu.import("resource://gre/modules/AppConstants.jsm");
 
 const RECOVERYSERVICE_CID = Components.ID("{b3caca5d-0bb0-48c6-912b-6be6cbf08832}");
 const RECOVERYSERVICE_CONTRACTID = "@mozilla.org/recovery-service;1";
 
 function log(msg) {
   dump("-*- RecoveryService: " + msg + "\n");
 }
 
-#ifdef MOZ_WIDGET_GONK
-var librecovery = (function() {
-  let library;
-  try {
-    library = ctypes.open("librecovery.so");
-  } catch (e) {
-    log("Unable to open librecovery.so");
-    throw Cr.NS_ERROR_FAILURE;
-  }
-  // Bug 1163956, modify updatePath from ctyps.char.ptr to ctype.char.array(4096)
-  // align with librecovery.h. 4096 comes from PATH_MAX
-  let FotaUpdateStatus = new ctypes.StructType("FotaUpdateStatus", [
-                                                { result: ctypes.int },
-                                                { updatePath: ctypes.char.array(4096) }
-                                              ]);
+const isGonk = AppConstants.platform === 'gonk';
+
+if (isGonk) {
+  var librecovery = (function() {
+    let library;
+    try {
+      library = ctypes.open("librecovery.so");
+    } catch (e) {
+      log("Unable to open librecovery.so");
+      throw Cr.NS_ERROR_FAILURE;
+    }
+    // Bug 1163956, modify updatePath from ctyps.char.ptr to ctype.char.array(4096)
+    // align with librecovery.h. 4096 comes from PATH_MAX
+    let FotaUpdateStatus = new ctypes.StructType("FotaUpdateStatus", [
+                                                  { result: ctypes.int },
+                                                  { updatePath: ctypes.char.array(4096) }
+                                                ]);
 
-  return {
-    factoryReset:        library.declare("factoryReset",
-                                         ctypes.default_abi,
-                                         ctypes.int),
-    installFotaUpdate:   library.declare("installFotaUpdate",
-                                         ctypes.default_abi,
-                                         ctypes.int,
-                                         ctypes.char.ptr,
-                                         ctypes.int),
+    return {
+      factoryReset:        library.declare("factoryReset",
+                                           ctypes.default_abi,
+                                           ctypes.int),
+      installFotaUpdate:   library.declare("installFotaUpdate",
+                                           ctypes.default_abi,
+                                           ctypes.int,
+                                           ctypes.char.ptr,
+                                           ctypes.int),
 
-    FotaUpdateStatus:    FotaUpdateStatus,
-    getFotaUpdateStatus: library.declare("getFotaUpdateStatus",
-                                         ctypes.default_abi,
-                                         ctypes.int,
-                                         FotaUpdateStatus.ptr)
-  };
-})();
+      FotaUpdateStatus:    FotaUpdateStatus,
+      getFotaUpdateStatus: library.declare("getFotaUpdateStatus",
+                                           ctypes.default_abi,
+                                           ctypes.int,
+                                           FotaUpdateStatus.ptr)
+    };
+  })();
 
-const gFactoryResetFile = "__post_reset_cmd__";
+  const gFactoryResetFile = "__post_reset_cmd__";
 
-#endif
+}
 
 function RecoveryService() {}
 
 RecoveryService.prototype = {
   classID: RECOVERYSERVICE_CID,
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIRecoveryService]),
   classInfo: XPCOMUtils.generateCI({
     classID: RECOVERYSERVICE_CID,
     contractID: RECOVERYSERVICE_CONTRACTID,
     interfaces: [Ci.nsIRecoveryService],
     classDescription: "B2G Recovery Service"
   }),
 
   factoryReset: function RS_factoryReset(reason) {
-#ifdef MOZ_WIDGET_GONK
+    if (!isGonk) {
+      Cr.NS_ERROR_FAILURE;
+    }
+
     function doReset() {
       // If this succeeds, then the device reboots and this never returns
       if (librecovery.factoryReset() != 0) {
         log("Error: Factory reset failed. Trying again after clearing cache.");
       }
       let cache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
                     .getService(Ci.nsICacheStorageService);
       cache.clear();
@@ -114,42 +120,41 @@ RecoveryService.prototype = {
                                         { tmpPath: postResetFile + ".tmp" });
 
       promise.then(doReset, function onError(error) {
         log("Error: " + error);
       });
     } else {
       doReset();
     }
-#endif
-    throw Cr.NS_ERROR_FAILURE;
   },
 
   installFotaUpdate: function RS_installFotaUpdate(updatePath) {
-#ifdef MOZ_WIDGET_GONK
+    if (!isGonk) {
+      throw Cr.NS_ERROR_FAILURE;
+    }
+
     // If this succeeds, then the device reboots and this never returns
     if (librecovery.installFotaUpdate(updatePath, updatePath.length) != 0) {
       log("Error: FOTA install failed. Trying again after clearing cache.");
     }
     var cache = Cc["@mozilla.org/netwerk/cache-storage-service;1"].getService(Ci.nsICacheStorageService);
     cache.clear();
     if (librecovery.installFotaUpdate(updatePath, updatePath.length) != 0) {
       log("Error: FOTA install failed again");
     }
-#endif
-    throw Cr.NS_ERROR_FAILURE;
   },
 
   getFotaUpdateStatus: function RS_getFotaUpdateStatus() {
     let status =  Ci.nsIRecoveryService.FOTA_UPDATE_UNKNOWN;
-#ifdef MOZ_WIDGET_GONK
-    let cStatus = librecovery.FotaUpdateStatus();
+
+    if (isGonk) {
+      let cStatus = librecovery.FotaUpdateStatus();
 
-    if (librecovery.getFotaUpdateStatus(cStatus.address()) == 0) {
-      status = cStatus.result;
+      if (librecovery.getFotaUpdateStatus(cStatus.address()) == 0) {
+        status = cStatus.result;
+      }
     }
-
-#endif
     return status;
   }
 };
 
 this.NSGetFactory = XPCOMUtils.generateNSGetFactory([RecoveryService]);
--- a/b2g/components/UpdatePrompt.js
+++ b/b2g/components/UpdatePrompt.js
@@ -8,16 +8,17 @@
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cu = Components.utils;
 const Cr = Components.results;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/WebappsUpdater.jsm");
+Cu.import("resource://gre/modules/AppConstants.jsm");
 
 const VERBOSE = 1;
 var log =
   VERBOSE ?
   function log_dump(msg) { dump("UpdatePrompt: "+ msg +"\n"); } :
   function log_noop(msg) { };
 
 const PREF_APPLY_PROMPT_TIMEOUT          = "b2g.update.apply-prompt-timeout";
@@ -394,40 +395,40 @@ UpdatePrompt.prototype = {
     }
 
     if (!this.sendUpdateEvent("update-prompt-apply", aUpdate)) {
       log("Unable to prompt, forcing restart");
       this.restartProcess();
       return;
     }
 
-#ifdef MOZ_B2G_RIL
-    let window = Services.wm.getMostRecentWindow("navigator:browser");
-    let pinReq = window.navigator.mozIccManager.getCardLock("pin");
-    pinReq.onsuccess = function(e) {
-      if (e.target.result.enabled) {
-        // The SIM is pin locked. Don't use a fallback timer. This means that
-        // the user has to press Install to apply the update. If we use the
-        // timer, and the timer reboots the phone, then the phone will be
-        // unusable until the SIM is unlocked.
-        log("SIM is pin locked. Not starting fallback timer.");
-      } else {
-        // This means that no pin lock is enabled, so we go ahead and start
-        // the fallback timer.
+    if (AppConstants.MOZ_B2G_RIL) {
+      let window = Services.wm.getMostRecentWindow("navigator:browser");
+      let pinReq = window.navigator.mozIccManager.getCardLock("pin");
+      pinReq.onsuccess = function(e) {
+        if (e.target.result.enabled) {
+          // The SIM is pin locked. Don't use a fallback timer. This means that
+          // the user has to press Install to apply the update. If we use the
+          // timer, and the timer reboots the phone, then the phone will be
+          // unusable until the SIM is unlocked.
+          log("SIM is pin locked. Not starting fallback timer.");
+        } else {
+          // This means that no pin lock is enabled, so we go ahead and start
+          // the fallback timer.
+          this._applyPromptTimer = this.createTimer(this.applyPromptTimeout);
+        }
+      }.bind(this);
+      pinReq.onerror = function(e) {
         this._applyPromptTimer = this.createTimer(this.applyPromptTimeout);
-      }
-    }.bind(this);
-    pinReq.onerror = function(e) {
+      }.bind(this);
+    } else {
+      // Schedule a fallback timeout in case the UI is unable to respond or show
+      // a prompt for some reason.
       this._applyPromptTimer = this.createTimer(this.applyPromptTimeout);
-    }.bind(this);
-#else
-    // Schedule a fallback timeout in case the UI is unable to respond or show
-    // a prompt for some reason.
-    this._applyPromptTimer = this.createTimer(this.applyPromptTimeout);
-#endif
+    }
   },
 
   _copyProperties: ["appVersion", "buildID", "detailsURL", "displayVersion",
                     "errorCode", "isOSUpdate", "platformVersion",
                     "previousAppVersion", "state", "statusText"],
 
   sendUpdateEvent: function UP_sendUpdateEvent(aType, aUpdate) {
     let detail = {};
@@ -548,26 +549,26 @@ UpdatePrompt.prototype = {
       this.showUpdateError(this._update);
     }
   },
 
   restartProcess: function UP_restartProcess() {
     log("Update downloaded, restarting to apply it");
 
     let callbackAfterSet = function() {
-#ifndef MOZ_WIDGET_GONK
-      let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"]
-                       .getService(Ci.nsIAppStartup);
-      appStartup.quit(appStartup.eForceQuit | appStartup.eRestart);
-#else
-      // NB: on Gonk, we rely on the system process manager to restart us.
-      let pmService = Cc["@mozilla.org/power/powermanagerservice;1"]
-                      .getService(Ci.nsIPowerManagerService);
-      pmService.restart();
-#endif
+      if (AppConstants.platform !== "gonk") {
+        let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"]
+                         .getService(Ci.nsIAppStartup);
+        appStartup.quit(appStartup.eForceQuit | appStartup.eRestart);
+      } else {
+        // NB: on Gonk, we rely on the system process manager to restart us.
+        let pmService = Cc["@mozilla.org/power/powermanagerservice;1"]
+                        .getService(Ci.nsIPowerManagerService);
+        pmService.restart();
+      }
     }
 
     if (useSettings()) {
       // Save current os version in deviceinfo.previous_os
       let lock = Services.settings.createLock({
         handle: callbackAfterSet,
         handleAbort: function(error) {
           log("Abort callback when trying to set previous_os: " + error);
--- a/b2g/components/moz.build
+++ b/b2g/components/moz.build
@@ -39,49 +39,46 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk
       'SimulatorScreen.js'
     ]
 
 EXTRA_PP_COMPONENTS += [
     'B2GComponents.manifest',
 ]
 
 if CONFIG['MOZ_B2G'] and not CONFIG['MOZ_B2GDROID']:
-    EXTRA_PP_COMPONENTS += [
+    EXTRA_COMPONENTS += [
         'DirectoryProvider.js',
         'RecoveryService.js',
     ]
 
 if CONFIG['MOZ_UPDATER']:
-    EXTRA_PP_COMPONENTS += [
+    EXTRA_COMPONENTS += [
         'UpdatePrompt.js',
     ]
 
 EXTRA_JS_MODULES += [
     'AboutServiceWorkers.jsm',
     'ActivityChannel.jsm',
     'AlertsHelper.jsm',
     'Bootstraper.jsm',
     'ContentRequestHelper.jsm',
     'DebuggerActors.js',
     'ErrorPage.jsm',
     'Frames.jsm',
     'FxAccountsMgmtService.jsm',
+    'KillSwitchMain.jsm',
     'LogCapture.jsm',
     'LogParser.jsm',
     'LogShake.jsm',
     'MultiscreenHandler.jsm',
     'OrientationChangeHandler.jsm',
     'SafeMode.jsm',
     'Screenshot.jsm',
     'SignInToWebsite.jsm',
     'SystemAppProxy.jsm',
     'TelURIParser.jsm',
     'WebappsUpdater.jsm',
 ]
 
-EXTRA_PP_JS_MODULES += [
-    'KillSwitchMain.jsm'
-]
-
 if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
     EXTRA_JS_MODULES += [
       'GlobalSimulatorScreen.jsm'
     ]
--- a/toolkit/modules/AppConstants.jsm
+++ b/toolkit/modules/AppConstants.jsm
@@ -89,16 +89,23 @@ this.AppConstants = Object.freeze({
 
   MOZ_TELEMETRY_REPORTING:
 #ifdef MOZ_TELEMETRY_REPORTING
   true,
 #else
   false,
 #endif
 
+  MOZ_TELEMETRY_ON_BY_DEFAULT:
+#ifdef MOZ_TELEMETRY_ON_BY_DEFAULT
+  true,
+#else
+  false,
+#endif
+
   MOZ_SERVICES_CLOUDSYNC:
 #ifdef MOZ_SERVICES_CLOUDSYNC
   true,
 #else
   false,
 #endif
 
   MOZ_UPDATER:
@@ -193,30 +200,37 @@ this.AppConstants = Object.freeze({
 
   DEBUG:
 #ifdef DEBUG
   true,
 #else
   false,
 #endif
 
-  MOZ_B2G:
-#ifdef MOZ_B2G
+  MOZ_B2G_RIL:
+#ifdef MOZ_B2G_RIL
   true,
 #else
   false,
 #endif
 
   MOZ_B2GDROID:
 #ifdef MOZ_B2GDROID
   true,
 #else
   false,
 #endif
 
+  MOZ_GRAPHENE:
+#ifdef MOZ_GRAPHENE
+  true,
+#else
+  false,
+#endif
+
   MOZ_PLACES:
 #ifdef MOZ_PLACES
   true,
 #else
   false,
 #endif
 
   MOZ_ANDROID_HISTORY:
@@ -232,16 +246,18 @@ this.AppConstants = Object.freeze({
   MOZ_APP_NAME: "@MOZ_APP_NAME@",
   MOZ_APP_VERSION: "@MOZ_APP_VERSION@",
   MOZ_APP_VERSION_DISPLAY: "@MOZ_APP_VERSION_DISPLAY@",
   MOZ_BUILD_APP: "@MOZ_BUILD_APP@",
   MOZ_UPDATE_CHANNEL: "@MOZ_UPDATE_CHANNEL@",
   INSTALL_LOCALE: "@AB_CD@",
   MOZ_WIDGET_TOOLKIT: "@MOZ_WIDGET_TOOLKIT@",
   ANDROID_PACKAGE_NAME: "@ANDROID_PACKAGE_NAME@",
+  MOZ_B2G_VERSION: @MOZ_B2G_VERSION@,
+  MOZ_B2G_OS_NAME: @MOZ_B2G_OS_NAME@,
 
   MOZ_ANDROID_APZ:
 #ifdef MOZ_ANDROID_APZ
     true,
 #else
     false,
 #endif
   DEBUG_JS_MODULES: "@DEBUG_JS_MODULES@",