Browse Source

ian rel-257 mozilla queue

Ian Neal 4 years ago
parent
commit
082d8748f8
100 changed files with 229921 additions and 0 deletions
  1. 181 0
      rel-257/ian/patches/1086964-61a1.patch
  2. 359 0
      rel-257/ian/patches/1231349-mozl10n_2-257.patch
  3. 69 0
      rel-257/ian/patches/1233768-61a1.patch
  4. 97 0
      rel-257/ian/patches/1242294-firefoxstrict-moz-v1_1-257.patch
  5. 140 0
      rel-257/ian/patches/1253064-62a1.patch
  6. 346 0
      rel-257/ian/patches/1255485-1-61a1.patch
  7. 78 0
      rel-257/ian/patches/1255485-2-61a1.patch
  8. 31 0
      rel-257/ian/patches/1255485-3-61a1.patch
  9. 38 0
      rel-257/ian/patches/1255485-4-61a1.patch
  10. 224 0
      rel-257/ian/patches/1255485-5-61a1.patch
  11. 45 0
      rel-257/ian/patches/1255485-6-61a1.patch
  12. 156 0
      rel-257/ian/patches/1270882-66a1.patch
  13. 131 0
      rel-257/ian/patches/1301547-63a1.patch
  14. 86 0
      rel-257/ian/patches/1336712-65a1.patch
  15. 95 0
      rel-257/ian/patches/1340588-61a1.patch
  16. 59 0
      rel-257/ian/patches/1341222-1-63a1.patch
  17. 31 0
      rel-257/ian/patches/1341222-2-63a1.patch
  18. 59 0
      rel-257/ian/patches/1341222-3-63a1.patch
  19. 224 0
      rel-257/ian/patches/1351078-67a1.patch
  20. 49 0
      rel-257/ian/patches/1362858-1partial-56a1.patch
  21. 90558 0
      rel-257/ian/patches/1371485-1-63a1.patch
  22. 6775 0
      rel-257/ian/patches/1371485-2-63a1.patch
  23. 91582 0
      rel-257/ian/patches/1371485-3-63a1.patch
  24. 4003 0
      rel-257/ian/patches/1371485-4-63a1.patch
  25. 40 0
      rel-257/ian/patches/1371485-5-63a1.patch
  26. 39 0
      rel-257/ian/patches/1371485-6-63a1.patch
  27. 39 0
      rel-257/ian/patches/1371485-7-63a1.patch
  28. 34 0
      rel-257/ian/patches/1371485-8-63a1.patch
  29. 342 0
      rel-257/ian/patches/1372381-1-61a1.patch
  30. 118 0
      rel-257/ian/patches/1372381-2-61a1.patch
  31. 383 0
      rel-257/ian/patches/1372381-3-61a1.patch
  32. 88 0
      rel-257/ian/patches/1372381-4-61a1.patch
  33. 209 0
      rel-257/ian/patches/1372458-63a1.patch
  34. 173 0
      rel-257/ian/patches/1376756-63a1.patch
  35. 57 0
      rel-257/ian/patches/1394825-67a1.patch
  36. 95 0
      rel-257/ian/patches/1397263-1-64a1.patch
  37. 459 0
      rel-257/ian/patches/1397263-2-64a1.patch
  38. 130 0
      rel-257/ian/patches/1397263-3-64a1.patch
  39. 139 0
      rel-257/ian/patches/1397263-4-64a1.patch
  40. 109 0
      rel-257/ian/patches/1397263-5-64a1.patch
  41. 157 0
      rel-257/ian/patches/1397263-6-64a1.patch
  42. 188 0
      rel-257/ian/patches/1401776-62a1.patch
  43. 95 0
      rel-257/ian/patches/1404666-1-66a1.patch
  44. 421 0
      rel-257/ian/patches/1404666-2-66a1.patch
  45. 108 0
      rel-257/ian/patches/1411589-1-61a1.patch
  46. 531 0
      rel-257/ian/patches/1411589-2-61a1.patch
  47. 69 0
      rel-257/ian/patches/1411589-3-61a1.patch
  48. 179 0
      rel-257/ian/patches/1418629-68a1.patch
  49. 45 0
      rel-257/ian/patches/1418629-BACKOUT-1362858-1-60.patch
  50. 563 0
      rel-257/ian/patches/1418749-61a1.patch
  51. 331 0
      rel-257/ian/patches/1419892-61a1.patch
  52. 42 0
      rel-257/ian/patches/1421501-6only-63a1.patch
  53. 74 0
      rel-257/ian/patches/1422368-61a1.patch
  54. 46 0
      rel-257/ian/patches/1423895-62a1.patch
  55. 102 0
      rel-257/ian/patches/1424281-1-61a1.patch
  56. 304 0
      rel-257/ian/patches/1424281-2-61a1.patch
  57. 275 0
      rel-257/ian/patches/1424281-3-61a1.patch
  58. 234 0
      rel-257/ian/patches/1429016-67a1.patch
  59. 103 0
      rel-257/ian/patches/1429875-1-61a1.patch
  60. 54 0
      rel-257/ian/patches/1429875-2-61a1.patch
  61. 287 0
      rel-257/ian/patches/1429875-3-61a1.patch
  62. 1776 0
      rel-257/ian/patches/1429875-4-61a1.patch
  63. 386 0
      rel-257/ian/patches/1429875-5-61a1.patch
  64. 284 0
      rel-257/ian/patches/1434837-60.patch
  65. 93 0
      rel-257/ian/patches/1434844-61a1.patch
  66. 44 0
      rel-257/ian/patches/1437128-61a1.patch
  67. 65 0
      rel-257/ian/patches/1437661-67a1.patch
  68. 33 0
      rel-257/ian/patches/1439323-BACKOUT-1429125-60.patch
  69. 94 0
      rel-257/ian/patches/1439450-64a1.patch
  70. 339 0
      rel-257/ian/patches/1443706-61a1.patch
  71. 1215 0
      rel-257/ian/patches/1444274-61a1.patch
  72. 354 0
      rel-257/ian/patches/1445024-1-61a1.patch
  73. 260 0
      rel-257/ian/patches/1445024-2-61a1.patch
  74. 278 0
      rel-257/ian/patches/1445024-3-61a1.patch
  75. 236 0
      rel-257/ian/patches/1445105-61a1.patch
  76. 154 0
      rel-257/ian/patches/1445398-61a1.patch
  77. 30 0
      rel-257/ian/patches/1445503-61a1.patch
  78. 47 0
      rel-257/ian/patches/1445671-61a1.patch
  79. 12804 0
      rel-257/ian/patches/1445731-1-NSS337-61a1.patch
  80. 238 0
      rel-257/ian/patches/1445731-10-NSS337-61a1.patch
  81. 127 0
      rel-257/ian/patches/1445731-11-NSS337-61a1.patch
  82. 4503 0
      rel-257/ian/patches/1445731-2-NSS337-61a1.patch
  83. 75 0
      rel-257/ian/patches/1445731-3-NSS337-61a1.patch
  84. 49 0
      rel-257/ian/patches/1445731-4-NSS337-61a1.patch
  85. 172 0
      rel-257/ian/patches/1445731-5-NSS337-61a1.patch
  86. 156 0
      rel-257/ian/patches/1445731-6-NSS337-61a1.patch
  87. 1278 0
      rel-257/ian/patches/1445731-7-NSS337-61a1.patch
  88. 1532 0
      rel-257/ian/patches/1445731-8-NSS337-61a1.patch
  89. 111 0
      rel-257/ian/patches/1445731-9-NSS337-61a1.patch
  90. 90 0
      rel-257/ian/patches/1445766-61a1.patch
  91. 36 0
      rel-257/ian/patches/1445969-61a1.patch
  92. 104 0
      rel-257/ian/patches/1446809-1-61a1.patch
  93. 128 0
      rel-257/ian/patches/1446809-2-61a1.patch
  94. 64 0
      rel-257/ian/patches/1446809-3-61a1.patch
  95. 97 0
      rel-257/ian/patches/1446809-4-61a1.patch
  96. 44 0
      rel-257/ian/patches/1446809-5-61a1.patch
  97. 255 0
      rel-257/ian/patches/1446809-6-61a1.patch
  98. 33 0
      rel-257/ian/patches/1446809-7-61a1.patch
  99. 140 0
      rel-257/ian/patches/1446809-8-61a1.patch
  100. 119 0
      rel-257/ian/patches/1446809-9-61a1.patch

+ 181 - 0
rel-257/ian/patches/1086964-61a1.patch

@@ -0,0 +1,181 @@
+# HG changeset patch
+# User Ryan VanderMeulen <ryanvm@gmail.com>
+# Date 1521065912 14400
+# Node ID 29365e0d62fb532de8cdde4378c0c0357c5301d5
+# Parent  0547fda3f29a8f82b959a5387e7a99aded6c7f26
+Bug 1086964 - Remove uses of no_pgo that are no longer needed. r=dmajor
+
+diff --git a/gfx/layers/moz.build b/gfx/layers/moz.build
+--- a/gfx/layers/moz.build
++++ b/gfx/layers/moz.build
+@@ -417,21 +417,23 @@ UNIFIED_SOURCES += [
+     'ipc/SharedPlanarYCbCrImage.cpp',
+     'ipc/SharedRGBImage.cpp',
+     'ipc/SharedSurfacesChild.cpp',
+     'ipc/SharedSurfacesParent.cpp',
+     'ipc/UiCompositorControllerChild.cpp',
+     'ipc/UiCompositorControllerParent.cpp',
+     'ipc/VideoBridgeChild.cpp',
+     'ipc/VideoBridgeParent.cpp',
++    'Layers.cpp',
+     'LayerScope.cpp',
+     'LayersHelpers.cpp',
+     'LayersLogging.cpp',
+     'LayerSorter.cpp',
+     'LayersTypes.cpp',
++    'LayerTreeInvalidation.cpp',
+     'mlgpu/BufferCache.cpp',
+     'mlgpu/CanvasLayerMLGPU.cpp',
+     'mlgpu/ContainerLayerMLGPU.cpp',
+     'mlgpu/FrameBuilder.cpp',
+     'mlgpu/ImageLayerMLGPU.cpp',
+     'mlgpu/LayerManagerMLGPU.cpp',
+     'mlgpu/LayerMLGPU.cpp',
+     'mlgpu/MaskOperation.cpp',
+@@ -475,34 +477,24 @@ UNIFIED_SOURCES += [
+     'wr/WebRenderUserData.cpp',
+     # XXX here are some unified build error.
+     #'wr/WebRenderTextureHost.cpp'
+ ]
+ 
+ SOURCES += [
+     'basic/BasicImageLayer.cpp',
+     'ImageContainer.cpp',
+-    'Layers.cpp',
+-    'LayerTreeInvalidation.cpp',
+     'PersistentBufferProvider.cpp',
+     'protobuf/LayerScopePacket.pb.cc',
+     'wr/WebRenderTextureHost.cpp',
+ ]
+ 
+ DEFINES['GOOGLE_PROTOBUF_NO_RTTI'] = True
+ DEFINES['GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER'] = True
+ 
+-# Workaround compiler bug (Bug 795594)
+-if CONFIG['CC_TYPE'] in ('msvc', 'clang-cl') and CONFIG['CPU_ARCH'] == 'x86_64':
+-    for src in [
+-        'Layers.cpp',
+-        'LayerTreeInvalidation.cpp',
+-    ]:
+-        SOURCES[src].no_pgo = True
+-
+ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
+     SOURCES += [
+         'basic/MacIOSurfaceTextureHostBasic.cpp',
+         'opengl/MacIOSurfaceTextureClientOGL.cpp',
+         'opengl/MacIOSurfaceTextureHostOGL.cpp',
+     ]
+ 
+ IPDL_SOURCES += [
+diff --git a/js/src/moz.build b/js/src/moz.build
+--- a/js/src/moz.build
++++ b/js/src/moz.build
+@@ -396,18 +396,18 @@ UNIFIED_SOURCES += [
+     'wasm/WasmTextToBinary.cpp',
+     'wasm/WasmTextUtils.cpp',
+     'wasm/WasmTypes.cpp',
+     'wasm/WasmValidate.cpp'
+ ]
+ 
+ # jsarray.cpp and vm/JSAtom.cpp cannot be built in unified mode because
+ #   xpcshell is broken during packaging when compiled with gcc-4.8.2
+-# builtin/RegExp.cpp cannot be built in unified mode because it is built
+-#   without PGO
++# builtin/RegExp.cpp cannot be built in unified mode because it causes huge
++#   win32 test slowdowns
+ # frontend/Parser.cpp cannot be built in unified mode because of explicit
+ #   template instantiations.
+ # jsmath.cpp cannot be built in unified mode because it needs to re-#define the
+ #   RtlGenRandom declaration's calling convention in <ntsecapi.h> on Windows.
+ # jsutil.cpp cannot be built in unified mode because it is needed for
+ #   check-vanilla-allocations.
+ # StoreBuffer.cpp cannot be built in unified because its template
+ #   instantiations may or may not be needed depending on what it gets bundled
+@@ -698,20 +698,16 @@ if CONFIG['JS_HAS_CTYPES']:
+     DEFINES['JS_HAS_CTYPES'] = True
+     for var in ('DLL_PREFIX', 'DLL_SUFFIX'):
+         DEFINES[var] = '"%s"' % CONFIG[var]
+ 
+ if CONFIG['MOZ_LINKER']:
+     DEFINES['MOZ_LINKER'] = True
+ 
+ if CONFIG['CC_TYPE'] in ('msvc', 'clang-cl'):
+-    if CONFIG['CPU_ARCH'] == 'x86':
+-        SOURCES['builtin/RegExp.cpp'].no_pgo = True # Bug 772303
+-    elif CONFIG['CPU_ARCH'] == 'x86_64' and CONFIG['JS_HAS_CTYPES']:
+-        SOURCES['ctypes/CTypes.cpp'].no_pgo = True # Bug 810661
+     # Prevent floating point errors caused by VC++ optimizations
+     # XXX We should add this to CXXFLAGS, too?
+     CFLAGS += ['-fp:precise']
+     # C4805 warns mixing bool with other integral types in computation.
+     # But given the conversion from bool is specified, and this is a
+     # pattern widely used in code in js/src, suppress this warning here.
+     CXXFLAGS += ['-wd4805']
+     # C4661 ("no suitable definition provided for explicit template
+diff --git a/netwerk/sctp/datachannel/moz.build b/netwerk/sctp/datachannel/moz.build
+--- a/netwerk/sctp/datachannel/moz.build
++++ b/netwerk/sctp/datachannel/moz.build
+@@ -25,12 +25,10 @@ LOCAL_INCLUDES += [
+ 
+ DEFINES['SCTP_DEBUG'] = 1
+ 
+ if CONFIG['OS_TARGET'] == 'WINNT':
+     DEFINES['__Userspace_os_Windows'] = 1
+ else:
+     DEFINES['__Userspace_os_%s' % CONFIG['OS_TARGET']] = 1
+ 
+-NO_PGO = True # Don't PGO
+-
+ if CONFIG['CC_TYPE'] in ('clang', 'gcc'):
+     CXXFLAGS += ['-Wno-error=shadow']
+diff --git a/netwerk/sctp/src/moz.build b/netwerk/sctp/src/moz.build
+--- a/netwerk/sctp/src/moz.build
++++ b/netwerk/sctp/src/moz.build
+@@ -81,12 +81,10 @@ if CONFIG['OS_TARGET'] == 'NetBSD':
+     DEFINES['__NetBSD__'] = False
+ 
+ if CONFIG['OS_TARGET'] == 'OpenBSD':
+     DEFINES['__OpenBSD__'] = False
+ 
+ if CONFIG['OS_TARGET'] == 'DragonFly':
+     DEFINES['__DragonFly__'] = False
+ 
+-NO_PGO = True # Don't PGO
+-
+ if CONFIG['CC_TYPE'] in ('clang', 'gcc'):
+     CFLAGS += ['-std=gnu99']
+diff --git a/xpcom/reflect/xptcall/md/unix/moz.build b/xpcom/reflect/xptcall/md/unix/moz.build
+--- a/xpcom/reflect/xptcall/md/unix/moz.build
++++ b/xpcom/reflect/xptcall/md/unix/moz.build
+@@ -327,10 +327,8 @@ if CONFIG['OS_ARCH'] == 'Linux':
+         ]
+ 
+ FINAL_LIBRARY = 'xul'
+ 
+ LOCAL_INCLUDES += [
+     '../..',
+     '/xpcom/reflect/xptinfo',
+ ]
+-
+-NO_PGO = True
+diff --git a/xpcom/reflect/xptcall/md/win32/moz.build b/xpcom/reflect/xptcall/md/win32/moz.build
+--- a/xpcom/reflect/xptcall/md/win32/moz.build
++++ b/xpcom/reflect/xptcall/md/win32/moz.build
+@@ -29,17 +29,16 @@ else:
+             'xptcstubs.cpp',
+         ]
+     else:
+         SOURCES += [
+             'xptcinvoke.cpp',
+             'xptcinvoke_asm_x86_msvc.asm',
+             'xptcstubs.cpp',
+         ]
+-        SOURCES['xptcinvoke.cpp'].no_pgo = True
+         SOURCES['xptcinvoke_asm_x86_msvc.asm'].flags += ['-safeseh']
+ 
+ FINAL_LIBRARY = 'xul'
+ 
+ LOCAL_INCLUDES += [
+     '../..',
+     '/xpcom/reflect/xptinfo',
+ ]

+ 359 - 0
rel-257/ian/patches/1231349-mozl10n_2-257.patch

@@ -0,0 +1,359 @@
+# HG changeset patch
+# User Edmund Wong <ewong@pw-wspx.org>
+# Date 1561250880 -7200
+# Parent  86e179e577b8684de444b8deccad0245f0ec2ff1
+Bug 1231349 - L10n repacks broken on with SM 2.42 and newer - add ignorelist argument to l10n repack. r=frg a=frg
+
+diff --git a/python/mozbuild/mozpack/packager/l10n.py b/python/mozbuild/mozpack/packager/l10n.py
+--- a/python/mozbuild/mozpack/packager/l10n.py
++++ b/python/mozbuild/mozpack/packager/l10n.py
+@@ -37,80 +37,138 @@ from mozpack.chrome.manifest import (
+     Manifest,
+ )
+ from mozpack.errors import errors
+ from mozpack.mozjar import JAR_DEFLATED
+ from mozpack.packager.unpack import UnpackFinder
+ from createprecomplete import generate_precomplete
+ 
+ 
++class UnpackFinder(UnpackFinder):
++
++    def __init__(self, *args, **kwargs):
++        self.ignorelist = kwargs.pop('ignorelist', [])
++        super(UnpackFinder, self).__init__(*args, **kwargs)
++
++    def _maybe_zip(self, path, file):
++        def check_ignore(p):
++            dn = False
++            for i in self.ignorelist:
++                if i in p:
++                    dn = True
++            return dn
++
++        if not check_ignore(path):
++            return super(UnpackFinder, self)._maybe_zip(path, file)
++        return False
++
++
+ class LocaleManifestFinder(object):
+-    def __init__(self, finder):
++    def __init__(self, finder, ignorelist=[]):
+         entries = self.entries = []
+         bases = self.bases = []
++        self.ignorelist = ignorelist
+ 
+         class MockFormatter(object):
++            def __init__(self, ignorelist=[]):
++                self.ignorelist = ignorelist
++
+             def add_interfaces(self, path, content):
+                 pass
+ 
+             def add(self, path, content):
+                 pass
+ 
+             def add_manifest(self, entry):
++                def check_ig(p):
++                    dn = False
++                    for i in self.ignorelist:
++                        if hasattr(p, 'name'):
++                            if i in p.name:
++                                dn = True
++                    return dn
+                 if entry.localized:
+-                    entries.append(entry)
++                    if not check_ig(entry):
++                        entries.append(entry)
+ 
+             def add_base(self, base, addon=False):
+-                bases.append(base)
++                def check_ignore(p):
++                    dn = False
++                    for i in self.ignorelist:
++                        if i in p:
++                            dn = True
++                    return dn
++                if not check_ignore(base):
++                    bases.append(base)
+ 
+         # SimplePackager rejects "manifest foo.manifest" entries with
+         # additional flags (such as "manifest foo.manifest application=bar").
+         # Those type of entries are used by language packs to work as addons,
+         # but are not necessary for the purpose of l10n repacking. So we wrap
+         # the finder in order to remove those entries.
+         class WrapFinder(object):
+-            def __init__(self, finder):
++            def __init__(self, finder, ignorelist=[]):
+                 self._finder = finder
++                self._ignorelist = []
+ 
+             def find(self, pattern):
+-                for p, f in self._finder.find(pattern):
+-                    if isinstance(f, ManifestFile):
+-                        unwanted = [
+-                            e for e in f._entries
+-                            if isinstance(e, Manifest) and e.flags
+-                        ]
+-                        if unwanted:
+-                            f = ManifestFile(
+-                                f._base,
+-                                [e for e in f._entries if e not in unwanted])
+-                    yield p, f
++                def check_ignore(pf):
++                    dn = False
++                    for i in self._ignorelist:
++                        if i in pf:
++                            dn = True
++                    return dn
++                if not check_ignore(pattern):
++                    for p, f in self._finder.find(pattern):
++                        if isinstance(f, ManifestFile):
++                            unwanted = [
++                                e for e in f._entries
++                                if isinstance(e, Manifest) and e.flags
++                            ]
++                            if unwanted:
++                                f = ManifestFile(
++                                    f._base,
++                                    [e for e in f._entries if e not in unwanted])
++                        yield p, f
+ 
+-        sink = SimpleManifestSink(WrapFinder(finder), MockFormatter())
++        sink = SimpleManifestSink(WrapFinder(finder,
++                                             ignorelist=self.ignorelist),
++                                  MockFormatter(ignorelist=self.ignorelist))
+         sink.add(Component(''), '*')
+         sink.close(False)
+ 
+         # Find unique locales used in these manifest entries.
+         self.locales = list(set(e.id for e in self.entries
+                                 if isinstance(e, ManifestLocale)))
+ 
+ 
+-def _repack(app_finder, l10n_finder, copier, formatter, non_chrome=set()):
+-    app = LocaleManifestFinder(app_finder)
++def _repack(app_finder, l10n_finder, copier, formatter, non_chrome=set(),
++            ignorelist=[]):
++
++    def check_ignore(p):
++        dn = False
++        for i in ignorelist:
++            if i in p:
++                dn = True
++        return dn
++
++    app = LocaleManifestFinder(app_finder, ignorelist=ignorelist)
+     l10n = LocaleManifestFinder(l10n_finder)
+ 
+     # The code further below assumes there's only one locale replaced with
+     # another one.
+-    if len(app.locales) > 1:
+-        errors.fatal("Multiple app locales aren't supported: " +
+-                     ",".join(app.locales))
+     if len(l10n.locales) > 1:
+         errors.fatal("Multiple l10n locales aren't supported: " +
+                      ",".join(l10n.locales))
++    l10n_locale = l10n.locales[0]
+     locale = app.locales[0]
+-    l10n_locale = l10n.locales[0]
++
++    if len(app.locales) > 1:
++        if l10n_locale in app.locales:
++            locale = l10n_locale
+ 
+     # For each base directory, store what path a locale chrome package name
+     # corresponds to.
+     # e.g., for the following entry under app/chrome:
+     #     locale foo en-US path/to/files
+     # keep track that the locale path for foo in app is
+     # app/chrome/path/to/files.
+     # As there may be multiple locale entries with the same base, but with
+@@ -129,17 +187,18 @@ def _repack(app_finder, l10n_finder, cop
+             base = mozpath.basedir(e.path, app.bases)
+             l10n_paths.setdefault(base, {})
+             l10n_paths[base][key(e)] = e.path
+ 
+     # For chrome and non chrome files or directories, store what langpack path
+     # corresponds to a package path.
+     paths = {}
+     for e in app.entries:
+-        if isinstance(e, ManifestEntryWithRelPath):
++        if isinstance(e, ManifestEntryWithRelPath) and \
++           not check_ignore(e.path):
+             base = mozpath.basedir(e.path, app.bases)
+             if base not in l10n_paths:
+                 errors.fatal("Locale doesn't contain %s/" % base)
+                 # Allow errors to accumulate
+                 continue
+             if key(e) not in l10n_paths[base]:
+                 errors.fatal("Locale doesn't have a manifest entry for '%s'" %
+                     e.name)
+@@ -224,17 +283,18 @@ def _repack(app_finder, l10n_finder, cop
+             formatter.add(p, f)
+ 
+     # Transplant jar preloading information.
+     for path, log in app_finder.jarlogs.iteritems():
+         assert isinstance(copier[path], Jarrer)
+         copier[path].preload([l.replace(locale, l10n_locale) for l in log])
+ 
+ 
+-def repack(source, l10n, extra_l10n={}, non_resources=[], non_chrome=set()):
++def repack(source, l10n, extra_l10n={}, non_resources=[], non_chrome=set(),
++           ignorelist=[]):
+     '''
+     Replace localized data from the `source` directory with localized data
+     from `l10n` and `extra_l10n`.
+ 
+     The `source` argument points to a directory containing a packaged
+     application (in omnijar, jar or flat form).
+     The `l10n` argument points to a directory containing the main localized
+     data (usually in the form of a language pack addon) to use to replace
+@@ -244,35 +304,35 @@ def repack(source, l10n, extra_l10n={}, 
+     This can be used to point at different language pack addons for different
+     parts of the package application.
+     The `non_resources` argument gives a list of relative paths in the source
+     that should not be added in an omnijar in case the packaged application
+     is in that format.
+     The `non_chrome` argument gives a list of file/directory patterns for
+     localized files that are not listed in a chrome.manifest.
+     '''
+-    app_finder = UnpackFinder(source)
+-    l10n_finder = UnpackFinder(l10n)
++    app_finder = UnpackFinder(source, ignorelist=ignorelist)
++    l10n_finder = UnpackFinder(l10n, ignorelist=ignorelist)
+     if extra_l10n:
+         finders = {
+             '': l10n_finder,
+         }
+         for base, path in extra_l10n.iteritems():
+-            finders[base] = UnpackFinder(path)
++            finders[base] = UnpackFinder(path, ignorelist=ignorelist)
+         l10n_finder = ComposedFinder(finders)
+     copier = FileCopier()
+     compress = min(app_finder.compressed, JAR_DEFLATED)
+     if app_finder.kind == 'flat':
+         formatter = FlatFormatter(copier)
+     elif app_finder.kind == 'jar':
+         formatter = JarFormatter(copier,
+                                  optimize=app_finder.optimizedjars,
+                                  compress=compress)
+     elif app_finder.kind == 'omni':
+         formatter = OmniJarFormatter(copier, app_finder.omnijar,
+                                      optimize=app_finder.optimizedjars,
+                                      compress=compress,
+                                      non_resources=non_resources)
+ 
+     with errors.accumulate():
+-        _repack(app_finder, l10n_finder, copier, formatter, non_chrome)
++        _repack(app_finder, l10n_finder, copier, formatter, non_chrome, ignorelist=ignorelist)
+     copier.copy(source, skip_if_older=False)
+     generate_precomplete(source)
+diff --git a/python/mozbuild/mozpack/packager/unpack.py b/python/mozbuild/mozpack/packager/unpack.py
+--- a/python/mozbuild/mozpack/packager/unpack.py
++++ b/python/mozbuild/mozpack/packager/unpack.py
+@@ -59,17 +59,17 @@ class UnpackFinder(BaseFinder):
+             # Skip the precomplete file, which is generated at packaging time.
+             if p == 'precomplete':
+                 continue
+             base = mozpath.dirname(p)
+             # If the file is a zip/jar that is not a .xpi, and contains a
+             # chrome.manifest, it is an omnijar. All the files it contains
+             # go in the directory containing the omnijar. Manifests are merged
+             # if there is a corresponding manifest in the directory.
+-            if not p.endswith('.xpi') and self._maybe_zip(f) and \
++            if not p.endswith('.xpi') and self._maybe_zip(p, f) and \
+                     (mozpath.basename(p) == self.omnijar or
+                      not self.omnijar):
+                 jar = self._open_jar(p, f)
+                 if 'chrome.manifest' in jar:
+                     self.kind = 'omni'
+                     self.omnijar = mozpath.basename(p)
+                     self._fill_with_jar(base, jar)
+                     continue
+@@ -81,17 +81,17 @@ class UnpackFinder(BaseFinder):
+                     else ManifestFile(base)
+                 for e in parse_manifest(self.base, p, f.open()):
+                     m.add(self._handle_manifest_entry(e, jars))
+                 if self.files.contains(p):
+                     continue
+                 f = m
+             # If the file is a packed addon, unpack it under a directory named
+             # after the xpi.
+-            if p.endswith('.xpi') and self._maybe_zip(f):
++            if p.endswith('.xpi') and self._maybe_zip(p, f):
+                 self._fill_with_jar(p[:-4], self._open_jar(p, f))
+                 continue
+             if not p in jars:
+                 self.files.add(p, f)
+ 
+     def _fill_with_jar(self, base, jar):
+         for j in jar:
+             path = mozpath.join(base, j.filename)
+@@ -148,17 +148,17 @@ class UnpackFinder(BaseFinder):
+             jarlog = jar.entries.keys()
+             self.jarlogs[path] = jarlog[:jarlog.index(jar.last_preloaded) + 1]
+         return jar
+ 
+     def find(self, path):
+         for p in self.files.match(path):
+             yield p, self.files[p]
+ 
+-    def _maybe_zip(self, file):
++    def _maybe_zip(self, path, file):
+         '''
+         Return whether the given BaseFile looks like a ZIP/Jar.
+         '''
+         header = file.open().read(8)
+         return len(header) == 8 and (header[0:2] == 'PK' or
+                                      header[4:6] == 'PK')
+ 
+     def _unjarize(self, entry, relpath):
+diff --git a/toolkit/locales/l10n.mk b/toolkit/locales/l10n.mk
+--- a/toolkit/locales/l10n.mk
++++ b/toolkit/locales/l10n.mk
+@@ -110,17 +110,18 @@ endif
+ # The path to the object dir for the mozilla-central build system,
+ # may be overridden if necessary.
+ MOZDEPTH ?= $(DEPTH)
+ 
+ repackage-zip: UNPACKAGE='$(ZIP_IN)'
+ repackage-zip:
+ 	$(PYTHON) $(MOZILLA_DIR)/toolkit/mozapps/installer/l10n-repack.py '$(STAGEDIST)' $(DIST)/xpi-stage/locale-$(AB_CD) \
+ 		$(MOZ_PKG_EXTRAL10N) \
+-		$(if $(filter omni,$(MOZ_PACKAGER_FORMAT)),$(if $(NON_OMNIJAR_FILES),--non-resource $(NON_OMNIJAR_FILES)))
++		$(if $(filter omni,$(MOZ_PACKAGER_FORMAT)),$(if $(NON_OMNIJAR_FILES),--non-resource $(NON_OMNIJAR_FILES))) \
++		--ignorelist inspector@ {59c81df5-4b modern chatzilla
+ 
+ ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
+ ifneq (en,$(LPROJ_ROOT))
+ 	mv '$(STAGEDIST)'/en.lproj '$(STAGEDIST)'/$(LPROJ_ROOT).lproj
+ endif
+ ifdef MOZ_CRASHREPORTER
+ # On Mac OS X, the crashreporter.ini file needs to be moved from under the
+ # application bundle's Resources directory where all other l10n files are
+diff --git a/toolkit/mozapps/installer/l10n-repack.py b/toolkit/mozapps/installer/l10n-repack.py
+--- a/toolkit/mozapps/installer/l10n-repack.py
++++ b/toolkit/mozapps/installer/l10n-repack.py
+@@ -43,18 +43,21 @@ def main():
+     parser.add_argument('extra_l10n', nargs='*', metavar='BASE=PATH',
+                         type=valid_extra_l10n,
+                         help='Extra directories with staged localized files '
+                              'to be considered under the given base in the '
+                              'repacked build')
+     parser.add_argument('--non-resource', nargs='+', metavar='PATTERN',
+                         default=[],
+                         help='Extra files not to be considered as resources')
++    parser.add_argument('--ignorelist', nargs='+', default=[],
++                        help='List of ignore patterns.')
+     args = parser.parse_args()
+ 
+     buildconfig.substs['USE_ELF_HACK'] = False
+     buildconfig.substs['PKG_SKIP_STRIP'] = True
+     l10n.repack(args.build, args.l10n, extra_l10n=dict(args.extra_l10n),
+-                non_resources=args.non_resource, non_chrome=NON_CHROME)
++                non_resources=args.non_resource, non_chrome=NON_CHROME,
++                ignorelist=args.ignorelist)
+ 
+ 
+ if __name__ == "__main__":
+     main()

+ 69 - 0
rel-257/ian/patches/1233768-61a1.patch

@@ -0,0 +1,69 @@
+# HG changeset patch
+# User David Major <dmajor@mozilla.com>
+# Date 1521824759 14400
+# Node ID 9f0acb32263cb463975a1820307edc7149a2dd0c
+# Parent  4db836a8d12bfea94b1280fc8d4198ee79eb5727
+Bug 1233768: Disable regparm under clang-cl in libffi. r=froydnj
+
+diff --git a/js/src/ctypes/libffi-patches/02-clang-cl.patch b/js/src/ctypes/libffi-patches/02-clang-cl.patch
+--- a/js/src/ctypes/libffi-patches/02-clang-cl.patch
++++ b/js/src/ctypes/libffi-patches/02-clang-cl.patch
+@@ -26,24 +26,30 @@ index 7aee5b4..9cba257 100644
+ +
+  When building with MSVC under a MingW environment, you may need to
+  remove the line in configure that sets 'fix_srcfile_path' to a 'cygpath'
+  command.  ('cygpath' is not present in MingW, and is not required when
+ diff --git a/include/ffi.h.in b/include/ffi.h.in
+ index 70c6179..ebed0aa 100644
+ --- a/include/ffi.h.in
+ +++ b/include/ffi.h.in
+-@@ -68,7 +68,7 @@ extern "C" {
++@@ -68,7 +68,13 @@
+  
+  #ifndef LIBFFI_ASM
+  
+ -#ifdef _MSC_VER
+ +#if defined(_MSC_VER) && !defined(__clang__)
+  #define __attribute__(X)
+  #endif
+++
+++/* Disable regparm under clang-cl because the assembly thunks were
+++   written for MSVC and pass all parameters on the stack. */
+++#if defined(_MSC_VER) && defined(__clang__)
+++#define regparm(X)
+++#endif
+  
+ diff --git a/msvcc.sh b/msvcc.sh
+ index 9208076..4a65b0b 100755
+ --- a/msvcc.sh
+ +++ b/msvcc.sh
+ @@ -63,11 +63,15 @@ do
+        shift 1
+      ;;
+diff --git a/js/src/ctypes/libffi/include/ffi.h.in b/js/src/ctypes/libffi/include/ffi.h.in
+--- a/js/src/ctypes/libffi/include/ffi.h.in
++++ b/js/src/ctypes/libffi/include/ffi.h.in
+@@ -67,16 +67,22 @@ extern "C" {
+ #include <ffitarget.h>
+ 
+ #ifndef LIBFFI_ASM
+ 
+ #if defined(_MSC_VER) && !defined(__clang__)
+ #define __attribute__(X)
+ #endif
+ 
++/* Disable regparm under clang-cl because the assembly thunks were
++   written for MSVC and pass all parameters on the stack. */
++#if defined(_MSC_VER) && defined(__clang__)
++#define regparm(X)
++#endif
++
+ #include <stddef.h>
+ #include <limits.h>
+ 
+ /* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
+    But we can find it either under the correct ANSI name, or under GNU
+    C's internal name.  */
+ 
+ #define FFI_64_BIT_MAX 9223372036854775807
+

+ 97 - 0
rel-257/ian/patches/1242294-firefoxstrict-moz-v1_1-257.patch

@@ -0,0 +1,97 @@
+# HG changeset patch
+# User Ian Neal <iann_cvs@blueyonder.co.uk>
+# Date 1587892026 -3600
+# Parent  b3f2923381a484c1f4c58493d310f20452854781
+Bug 1242294 - Update how Firefox compatibility is advertised - mozilla part. r=frg a=frg
+
+diff --git a/netwerk/protocol/http/nsHttpHandler.cpp b/netwerk/protocol/http/nsHttpHandler.cpp
+--- a/netwerk/protocol/http/nsHttpHandler.cpp
++++ b/netwerk/protocol/http/nsHttpHandler.cpp
+@@ -228,16 +228,17 @@ nsHttpHandler::nsHttpHandler()
+       mQoSBits(0x00),
+       mEnforceAssocReq(false),
+       mLastUniqueID(NowInSeconds()),
+       mSessionStartTime(0),
+       mLegacyAppName("Mozilla"),
+       mLegacyAppVersion("5.0"),
+       mProduct("Gecko"),
+       mCompatFirefoxEnabled(false),
++      mCompatFirefoxStrict(false),
+       mUserAgentIsDirty(true),
+       mAcceptLanguagesIsDirty(true),
+       mPromptTempRedirect(true),
+       mEnablePersistentHttpsCaching(false),
+       mDoNotTrackEnabled(false),
+       mSafeHintEnabled(false),
+       mParentalControlEnabled(false),
+       mHandlerActive(false),
+@@ -904,22 +905,23 @@ void nsHttpHandler::BuildUserAgent() {
+ 
+   // Product portion
+   mUserAgent += ' ';
+   mUserAgent += mProduct;
+   mUserAgent += '/';
+   mUserAgent += mProductSub;
+ 
+   bool isFirefox = mAppName.EqualsLiteral("Firefox");
+-  if (isFirefox || mCompatFirefoxEnabled) {
++  if (isFirefox || mCompatFirefoxEnabled || mCompatFirefoxStrict) {
+     // "Firefox/x.y" (compatibility) app token
+     mUserAgent += ' ';
+     mUserAgent += mCompatFirefox;
+   }
+-  if (!isFirefox) {
++  // If not "strict Firefox", advertise an app name.
++  if (!isFirefox && !mCompatFirefoxStrict) {
+     // App portion
+     mUserAgent += ' ';
+     mUserAgent += mAppName;
+     mUserAgent += '/';
+     mUserAgent += mAppVersion;
+   }
+ }
+ 
+@@ -1137,16 +1139,22 @@ void nsHttpHandler::PrefsChanged(nsIPref
+   bool cVar = false;
+ 
+   if (PREF_CHANGED(UA_PREF("compatMode.firefox"))) {
+     rv = prefs->GetBoolPref(UA_PREF("compatMode.firefox"), &cVar);
+     mCompatFirefoxEnabled = (NS_SUCCEEDED(rv) && cVar);
+     mUserAgentIsDirty = true;
+   }
+ 
++  if (PREF_CHANGED(UA_PREF("compatMode.strict-firefox"))) {
++      rv = prefs->GetBoolPref(UA_PREF("compatMode.strict-firefox"), &cVar);
++      mCompatFirefoxStrict = (NS_SUCCEEDED(rv) && cVar);
++      mUserAgentIsDirty = true;
++  }
++
+   // general.useragent.override
+   if (PREF_CHANGED(UA_PREF("override"))) {
+     prefs->GetCharPref(UA_PREF("override"), mUserAgentOverride);
+     mUserAgentIsDirty = true;
+   }
+ 
+ #ifdef ANDROID
+   // general.useragent.use_device
+diff --git a/netwerk/protocol/http/nsHttpHandler.h b/netwerk/protocol/http/nsHttpHandler.h
+--- a/netwerk/protocol/http/nsHttpHandler.h
++++ b/netwerk/protocol/http/nsHttpHandler.h
+@@ -511,16 +511,17 @@ class nsHttpHandler final : public nsIHt
+   nsCString mOscpu;
+   nsCString mMisc;
+   nsCString mProduct;
+   nsCString mProductSub;
+   nsCString mAppName;
+   nsCString mAppVersion;
+   nsCString mCompatFirefox;
+   bool mCompatFirefoxEnabled;
++  bool mCompatFirefoxStrict;
+   nsCString mCompatDevice;
+   nsCString mDeviceModelId;
+ 
+   nsCString mUserAgent;
+   nsCString mSpoofedUserAgent;
+   nsCString mUserAgentOverride;
+   bool mUserAgentIsDirty;  // true if mUserAgent should be rebuilt
+   bool mAcceptLanguagesIsDirty;

+ 140 - 0
rel-257/ian/patches/1253064-62a1.patch

@@ -0,0 +1,140 @@
+# HG changeset patch
+# User Mike Hommey <mh+mozilla@glandium.org>
+# Date 1527729370 -32400
+# Node ID 07db1154d5b9411004d33cfe5d6a0e842cf15163
+# Parent  e6f9ab6fcbbbcb976df385fc203d7bc81666c065
+Bug 1253064 - Prefer Clang to GCC in local developer builds. r=gps
+
+For Android targets, we just ignore plain clang, it's unlikely to work.
+
+diff --git a/build/moz.configure/toolchain.configure b/build/moz.configure/toolchain.configure
+--- a/build/moz.configure/toolchain.configure
++++ b/build/moz.configure/toolchain.configure
+@@ -1,14 +1,31 @@
+ # -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+ # vim: set filetype=python:
+ # This Source Code Form is subject to the terms of the Mozilla Public
+ # 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/.
+ 
++imply_option('--enable-release', mozilla_official)
++imply_option('--enable-release', depends_if('MOZ_AUTOMATION')(lambda x: True))
++
++js_option('--enable-release',
++          help='Build with more conservative, release engineering-oriented '
++               'options. This may slow down builds.')
++
++
++@depends('--enable-release')
++def developer_options(value):
++    if not value:
++        return True
++
++
++add_old_configure_assignment('DEVELOPER_OPTIONS', developer_options)
++set_config('DEVELOPER_OPTIONS', developer_options)
++
+ # PGO
+ # ==============================================================
+ js_option(env='MOZ_PGO', help='Build with profile guided optimizations')
+ 
+ set_config('MOZ_PGO', depends('MOZ_PGO')(lambda x: bool(x)))
+ add_old_configure_assignment('MOZ_PGO', depends('MOZ_PGO')(lambda x: bool(x)))
+ 
+ # Code optimization
+@@ -642,31 +659,35 @@ def toolchain_search_path(vc_compiler_pa
+ def default_c_compilers(host_or_target):
+     '''Template defining the set of default C compilers for the host and
+     target platforms.
+     `host_or_target` is either `host` or `target` (the @depends functions
+     from init.configure.
+     '''
+     assert host_or_target in (host, target)
+ 
+-    @depends(host_or_target, target, toolchain_prefix, android_clang_compiler)
+-    def default_c_compilers(host_or_target, target, toolchain_prefix, android_clang_compiler):
++    @depends(host_or_target, target, toolchain_prefix, android_clang_compiler,
++             developer_options)
++    def default_c_compilers(host_or_target, target, toolchain_prefix,
++                            android_clang_compiler, developer_options):
+         gcc = ('gcc',)
+         if toolchain_prefix and host_or_target is target:
+             gcc = tuple('%sgcc' % p for p in toolchain_prefix) + gcc
+         # Android sets toolchain_prefix and android_clang_compiler, but
+         # we want the latter to take precedence, because the latter can
+         # point at clang, which is what we want to use.
+         if android_clang_compiler and host_or_target is target:
+-            gcc = (android_clang_compiler,) + gcc
++            return (android_clang_compiler,) + gcc
+ 
+         if host_or_target.kernel == 'WINNT':
+             return ('cl', 'clang-cl') + gcc + ('clang',)
+         if host_or_target.kernel == 'Darwin':
+             return ('clang',)
++        if developer_options:
++            return ('clang',) + gcc
+         return gcc + ('clang',)
+ 
+     return default_c_compilers
+ 
+ 
+ @template
+ def default_cxx_compilers(c_compiler):
+     '''Template defining the set of default C++ compilers for the host and
+@@ -1371,34 +1392,16 @@ imply_option('--enable-pie', depends_if(
+ # ==============================================================
+ 
+ option(env='RUSTFLAGS',
+        nargs=1,
+        help='Rust compiler flags')
+ set_config('RUSTFLAGS', depends('RUSTFLAGS')(lambda flags: flags))
+ 
+ 
+-imply_option('--enable-release', mozilla_official)
+-imply_option('--enable-release', depends_if('MOZ_AUTOMATION')(lambda x: True))
+-
+-js_option('--enable-release',
+-          default=milestone.is_release_or_beta,
+-          help='Build with more conservative, release engineering-oriented '
+-               'options. This may slow down builds.')
+-
+-
+-@depends('--enable-release')
+-def developer_options(value):
+-    if not value:
+-        return True
+-
+-
+-add_old_configure_assignment('DEVELOPER_OPTIONS', developer_options)
+-set_config('DEVELOPER_OPTIONS', developer_options)
+-
+ # Rust compiler flags
+ # ==============================================================
+ 
+ js_option(env='RUSTC_OPT_LEVEL',
+           nargs=1,
+           help='Rust compiler optimization level (-C opt-level=%s)')
+ 
+ # --enable-release kicks in full optimizations.
+diff --git a/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py b/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
+--- a/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
++++ b/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
+@@ -351,16 +351,18 @@ class BaseToolchainTest(BaseConfigureTes
+           they can be omitted. Likewise for host_cxx_compiler vs.
+           cxx_compiler.
+         '''
+         environ = dict(environ)
+         if 'PATH' not in environ:
+             environ['PATH'] = os.pathsep.join(
+                 mozpath.abspath(p) for p in ('/bin', '/usr/bin'))
+ 
++        args = args + ['--enable-release']
++
+         sandbox = self.get_sandbox(paths, {}, args, environ,
+                                    logger=self.logger)
+ 
+         for var in ('c_compiler', 'cxx_compiler', 'host_c_compiler',
+                     'host_cxx_compiler'):
+             if var in results:
+                 result = results[var]
+             elif var.startswith('host_'):

+ 346 - 0
rel-257/ian/patches/1255485-1-61a1.patch

@@ -0,0 +1,346 @@
+# HG changeset patch
+# User Ted Mielczarek <ted@mielczarek.org>
+# Date 1515612372 18000
+# Node ID ad09b92fb875944ba775ef452a245669b567619d
+# Parent  200b8243af2a9ea3ea79a4a1a12c9e1e26d262ec
+bug 1255485 - build PROGRAMs directly in dist/bin instead of copying them. r=nalexander
+
+Historically we built all our binaries in directories in the objdir, then
+symlinked them into dist/bin. Some binaries needed to be copied instead
+so that certain relative path lookups work properly, so we resorted to
+sprinkling `NSDISTMODE=copy` around Makefiles.
+
+This change makes it so we build PROGRAMs (not any other sort of targets)
+directly in dist/bin instead. We could do the same for our other targets
+with a little more work.
+
+There were several places in the tree that were copying built binaries to
+some other place and needed fixup to match the new location of binaries.
+
+On Windows pdb files are left in the objdir where the program was
+originally linked. symbolstore.py needs to locate the pdb file both to
+determine whether it should dump symbols for a binary and also to copy
+the pdb file into the symbol package. We fix this by simply looking for
+the pdb file in the current working directory if it isn't present next
+to the binary, which matches how we invoke symbolstore.py.
+
+MozReview-Commit-ID: 8TOD1uTXD5e
+
+diff --git a/browser/app/Makefile.in b/browser/app/Makefile.in
+--- a/browser/app/Makefile.in
++++ b/browser/app/Makefile.in
+@@ -41,17 +41,17 @@ endif
+ PROGRAMS_DEST = $(DIST)/bin
+ 
+ include $(topsrcdir)/config/rules.mk
+ 
+ ifneq (,$(filter-out WINNT,$(OS_ARCH)))
+ 
+ ifdef COMPILE_ENVIRONMENT
+ libs::
+-	cp -p $(MOZ_APP_NAME)$(BIN_SUFFIX) $(DIST)/bin/$(MOZ_APP_NAME)-bin$(BIN_SUFFIX)
++	cp -p $(DIST)/bin/$(MOZ_APP_NAME)$(BIN_SUFFIX) $(DIST)/bin/$(MOZ_APP_NAME)-bin$(BIN_SUFFIX)
+ endif
+ 
+ GARBAGE += $(addprefix $(FINAL_TARGET)/defaults/pref/, firefox.js)
+ 
+ endif
+ 
+ # channel-prefs.js is handled separate from other prefs due to bug 756325
+ # DO NOT change the content of channel-prefs.js without taking the appropriate
+diff --git a/config/makefiles/target_binaries.mk b/config/makefiles/target_binaries.mk
+--- a/config/makefiles/target_binaries.mk
++++ b/config/makefiles/target_binaries.mk
+@@ -2,18 +2,18 @@
+ # vim:set ts=8 sw=8 sts=8 noet:
+ #
+ # This Source Code Form is subject to the terms of the Mozilla Public
+ # 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/.
+ 
+ ifndef NO_DIST_INSTALL
+ 
+-ifneq (,$(strip $(PROGRAM)$(SIMPLE_PROGRAMS)$(RUST_PROGRAMS)))
+-PROGRAMS_EXECUTABLES = $(SIMPLE_PROGRAMS) $(PROGRAM) $(RUST_PROGRAMS)
++ifneq (,$(strip $(SIMPLE_PROGRAMS)$(RUST_PROGRAMS)))
++PROGRAMS_EXECUTABLES = $(SIMPLE_PROGRAMS) $(RUST_PROGRAMS)
+ PROGRAMS_DEST ?= $(FINAL_TARGET)
+ PROGRAMS_TARGET := target
+ INSTALL_TARGETS += PROGRAMS
+ endif
+ 
+ 
+ ifdef SHARED_LIBRARY
+ SHARED_LIBRARY_FILES = $(SHARED_LIBRARY)
+diff --git a/config/rules.mk b/config/rules.mk
+--- a/config/rules.mk
++++ b/config/rules.mk
+@@ -562,17 +562,17 @@ LINKER_OUT=$(subst /,\,$1)
+ else
+ LINKER_OUT=$1
+ endif
+ 
+ #
+ # PROGRAM = Foo
+ # creates OBJS, links with LIBS to create Foo
+ #
+-$(PROGRAM): $(PROGOBJS) $(STATIC_LIBS_DEPS) $(EXTRA_DEPS) $(RESFILE) $(GLOBAL_DEPS)
++$(PROGRAM): $(PROGOBJS) $(STATIC_LIBS_DEPS) $(EXTRA_DEPS) $(RESFILE) $(GLOBAL_DEPS) $(call mkdir_deps,$(FINAL_TARGET))
+ 	$(REPORT_BUILD)
+ 	@$(RM) $@.manifest
+ ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+ 	$(EXPAND_LINK) -NOLOGO -OUT:$(call LINKER_OUT,$@) -PDB:$(LINK_PDBFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
+ ifdef MSMANIFEST_TOOL
+ 	@if test -f $@.manifest; then \
+ 		if test -f '$(srcdir)/$@.manifest'; then \
+ 			echo 'Embedding manifest from $(srcdir)/$@.manifest and $@.manifest'; \
+diff --git a/js/src/shell/moz.build b/js/src/shell/moz.build
+--- a/js/src/shell/moz.build
++++ b/js/src/shell/moz.build
+@@ -59,9 +59,9 @@ if CONFIG['CC_TYPE'] in ('msvc', 'clang-
+ 
+ # Place a GDB Python auto-load file next to the shell executable, both in
+ # the build directory and in the dist/bin directory.
+ DEFINES['topsrcdir'] = '%s/js/src' % TOPSRCDIR
+ FINAL_TARGET_PP_FILES += ['js-gdb.py.in']
+ OBJDIR_FILES.js.src.shell += ['!/dist/bin/js-gdb.py']
+ 
+ # People expect the js shell to wind up in the top-level JS dir.
+-OBJDIR_FILES.js.src += ['!js%s' % CONFIG['BIN_SUFFIX']]
++OBJDIR_FILES.js.src += ['!/dist/bin/js%s' % CONFIG['BIN_SUFFIX']]
+diff --git a/modules/libmar/tests/moz.build b/modules/libmar/tests/moz.build
+--- a/modules/libmar/tests/moz.build
++++ b/modules/libmar/tests/moz.build
+@@ -3,10 +3,10 @@
+ # This Source Code Form is subject to the terms of the Mozilla Public
+ # 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/.
+ 
+ XPCSHELL_TESTS_MANIFESTS += ['unit/xpcshell.ini']
+ 
+ if CONFIG['OS_TARGET'] != 'Android':
+     TEST_HARNESS_FILES.xpcshell.modules.libmar.tests.unit += [
+-        '!../tool/signmar%s' % CONFIG['BIN_SUFFIX'],
++        '!/dist/bin/signmar%s' % CONFIG['BIN_SUFFIX'],
+     ]
+diff --git a/python/mozbuild/mozbuild/backend/recursivemake.py b/python/mozbuild/mozbuild/backend/recursivemake.py
+--- a/python/mozbuild/mozbuild/backend/recursivemake.py
++++ b/python/mozbuild/mozbuild/backend/recursivemake.py
+@@ -1119,17 +1119,17 @@ class RecursiveMakeBackend(CommonBackend
+             interfaces_manifests = ' '.join(interfaces_manifests),
+             xpidl_rules=rules.getvalue(),
+             xpidl_modules=' '.join(xpt_modules),
+             xpt_files=' '.join(sorted(xpt_files - registered_xpt_files)),
+             registered_xpt_files=' '.join(sorted(registered_xpt_files)),
+         ))
+ 
+     def _process_program(self, obj, backend_file):
+-        backend_file.write('PROGRAM = %s\n' % obj.program)
++        backend_file.write('PROGRAM = %s\n' % self._pretty_path(obj.output_path, backend_file))
+         if not obj.cxx_link and not self.environment.bin_suffix:
+             backend_file.write('PROG_IS_C_ONLY_%s := 1\n' % obj.program)
+ 
+     def _process_host_program(self, program, backend_file):
+         backend_file.write('HOST_PROGRAM = %s\n' % program)
+ 
+     def _process_rust_program_base(self, obj, backend_file,
+                                    target_variable,
+diff --git a/python/mozbuild/mozbuild/frontend/data.py b/python/mozbuild/mozbuild/frontend/data.py
+--- a/python/mozbuild/mozbuild/frontend/data.py
++++ b/python/mozbuild/mozbuild/frontend/data.py
+@@ -12,16 +12,17 @@ All data structures of interest are chil
+ Logic for populating these data structures is not defined in this class.
+ Instead, what we have here are dumb container classes. The emitter module
+ contains the code for converting executed mozbuild files into these data
+ structures.
+ """
+ 
+ from __future__ import absolute_import, unicode_literals
+ 
++from mozbuild.frontend.context import ObjDirPath
+ from mozbuild.util import StrictOrderingOnAppendList
+ from mozpack.chrome.manifest import ManifestEntry
+ 
+ import mozpack.path as mozpath
+ from .context import FinalTargetValue
+ 
+ from collections import defaultdict, OrderedDict
+ import itertools
+@@ -81,16 +82,20 @@ class ContextDerived(TreeMetadata):
+ 
+         self._context = context
+ 
+     @property
+     def install_target(self):
+         return self._context['FINAL_TARGET']
+ 
+     @property
++    def installed(self):
++        return self._context['DIST_INSTALL'] is not False
++
++    @property
+     def defines(self):
+         defines = self._context['DEFINES']
+         return Defines(self._context, defines) if defines else None
+ 
+     @property
+     def relobjdir(self):
+         return mozpath.relpath(self.objdir, self.topobjdir)
+ 
+@@ -467,16 +472,23 @@ class BaseProgram(Linkable):
+         Linkable.__init__(self, context)
+ 
+         bin_suffix = context.config.substs.get(self.SUFFIX_VAR, '')
+         if not program.endswith(bin_suffix):
+             program += bin_suffix
+         self.program = program
+         self.is_unit_test = is_unit_test
+ 
++    @property
++    def output_path(self):
++        if self.installed:
++            return ObjDirPath(self._context, '!/' + mozpath.join(self.install_target, self.program))
++        else:
++            return ObjDirPath(self._context, '!' + self.program)
++
+     def __repr__(self):
+         return '<%s: %s/%s>' % (type(self).__name__, self.relobjdir, self.program)
+ 
+ 
+ class Program(BaseProgram):
+     """Context derived container object for PROGRAM"""
+     SUFFIX_VAR = 'BIN_SUFFIX'
+     KIND = 'target'
+diff --git a/python/mozbuild/mozbuild/frontend/emitter.py b/python/mozbuild/mozbuild/frontend/emitter.py
+--- a/python/mozbuild/mozbuild/frontend/emitter.py
++++ b/python/mozbuild/mozbuild/frontend/emitter.py
+@@ -779,17 +779,18 @@ class TreeMetadataEmitter(LoggingMixin):
+                              'GENERATED_FILES: %s') % (symbols_file,), context)
+                     shared_args['symbols_file'] = symbols_file.target_basename
+ 
+             if shared_lib:
+                 lib = SharedLibrary(context, libname, **shared_args)
+                 self._libs[libname].append(lib)
+                 self._linkage.append((context, lib, 'USE_LIBS'))
+                 linkables.append(lib)
+-                generated_files.add(lib.lib_name)
++                if not lib.installed:
++                    generated_files.add(lib.lib_name)
+                 if symbols_file and isinstance(symbols_file, SourcePath):
+                     script = mozpath.join(
+                         mozpath.dirname(mozpath.dirname(__file__)),
+                         'action', 'generate_symbols_file.py')
+                     defines = ()
+                     if lib.defines:
+                         defines = lib.defines.get_defines()
+                     yield GeneratedFile(context, script,
+diff --git a/toolkit/crashreporter/tools/symbolstore.py b/toolkit/crashreporter/tools/symbolstore.py
+--- a/toolkit/crashreporter/tools/symbolstore.py
++++ b/toolkit/crashreporter/tools/symbolstore.py
+@@ -607,31 +607,50 @@ class Dumper:
+ 
+         elapsed = time.time() - t_start
+         print('Finished processing %s in %.2fs' % (file, elapsed),
+               file=sys.stderr)
+ 
+ # Platform-specific subclasses.  For the most part, these just have
+ # logic to determine what files to extract symbols from.
+ 
++def locate_pdb(path):
++    '''Given a path to a binary, attempt to locate the matching pdb file with simple heuristics:
++    * Look for a pdb file with the same base name next to the binary
++    * Look for a pdb file with the same base name in the cwd
++
++    Returns the path to the pdb file if it exists, or None if it could not be located.
++    '''
++    path, ext = os.path.splitext(path)
++    pdb = path + '.pdb'
++    if os.path.isfile(pdb):
++        return pdb
++    # If there's no pdb next to the file, see if there's a pdb with the same root name
++    # in the cwd. We build some binaries directly into dist/bin, but put the pdb files
++    # in the relative objdir, which is the cwd when running this script.
++    base = os.path.basename(pdb)
++    pdb = os.path.join(os.getcwd(), base)
++    if os.path.isfile(pdb):
++        return pdb
++    return None
++
+ class Dumper_Win32(Dumper):
+     fixedFilenameCaseCache = {}
+ 
+     def ShouldProcess(self, file):
+         """This function will allow processing of exe or dll files that have pdb
+         files with the same base name next to them."""
+         if file.endswith(".exe") or file.endswith(".dll"):
+-            path, ext = os.path.splitext(file)
+-            if os.path.isfile(path + ".pdb"):
++            if locate_pdb(file) is not None:
+                 return True
+         return False
+ 
+ 
+     def CopyDebug(self, file, debug_file, guid, code_file, code_id):
+-        file = "%s.pdb" % os.path.splitext(file)[0]
++        file = locate_pdb(file)
+         def compress(path):
+             compressed_file = path[:-1] + '_'
+             # ignore makecab's output
+             makecab = buildconfig.substs['MAKECAB']
+             success = subprocess.call([makecab, "-D",
+                                        "CompressionType=MSZIP",
+                                        path, compressed_file],
+                                       stdout=open(os.devnull, 'w'),
+diff --git a/toolkit/crashreporter/tools/unit-symbolstore.py b/toolkit/crashreporter/tools/unit-symbolstore.py
+--- a/toolkit/crashreporter/tools/unit-symbolstore.py
++++ b/toolkit/crashreporter/tools/unit-symbolstore.py
+@@ -479,18 +479,17 @@ class TestFunctional(HelperMixin, unitte
+             else:
+                 self.dump_syms = os.path.join(self.topsrcdir,
+                                               'toolkit',
+                                               'crashreporter',
+                                               'tools',
+                                               'win32',
+                                               'dump_syms_vc{_MSC_VER}.exe'.format(**buildconfig.substs))
+             self.target_bin = os.path.join(buildconfig.topobjdir,
+-                                           'browser',
+-                                           'app',
++                                           'dist', 'bin',
+                                            'firefox.exe')
+         else:
+             self.dump_syms = os.path.join(buildconfig.topobjdir,
+                                           'dist', 'host', 'bin',
+                                           'dump_syms')
+             self.target_bin = os.path.join(buildconfig.topobjdir,
+                                            'dist', 'bin', 'firefox')
+ 
+@@ -499,26 +498,28 @@ class TestFunctional(HelperMixin, unitte
+         HelperMixin.tearDown(self)
+ 
+     def testSymbolstore(self):
+         if self.skip_test:
+             raise unittest.SkipTest('Skipping test in non-Firefox product')
+         dist_include_manifest = os.path.join(buildconfig.topobjdir,
+                                              '_build_manifests/install/dist_include')
+         dist_include = os.path.join(buildconfig.topobjdir, 'dist/include')
++        browser_app = os.path.join(buildconfig.topobjdir, 'browser/app')
+         output = subprocess.check_output([sys.executable,
+                                           self.script_path,
+                                           '--vcs-info',
+                                           '-s', self.topsrcdir,
+                                           '--install-manifest=%s,%s' % (dist_include_manifest,
+                                                                         dist_include),
+                                           self.dump_syms,
+                                           self.test_dir,
+                                           self.target_bin],
+-                                         stderr=open(os.devnull, 'w'))
++                                         stderr=open(os.devnull, 'w'),
++                                         cwd=browser_app)
+         lines = filter(lambda x: x.strip(), output.splitlines())
+         self.assertEqual(1, len(lines),
+                          'should have one filename in the output')
+         symbol_file = os.path.join(self.test_dir, lines[0])
+         self.assertTrue(os.path.isfile(symbol_file))
+         symlines = open(symbol_file, 'r').readlines()
+         file_lines = [l for l in symlines if l.startswith('FILE')]
+         def check_hg_path(lines, match):

+ 78 - 0
rel-257/ian/patches/1255485-2-61a1.patch

@@ -0,0 +1,78 @@
+# HG changeset patch
+# User Ted Mielczarek <ted@mielczarek.org>
+# Date 1511382606 18000
+# Node ID 6fffc6fbb8c9fab9b61c3fe54894e85e116f30df
+# Parent  adc0e66cba9e0dd113853367ea12ae4a2ed3583d
+bug 1255485 - Remove NSDISTMODE=copy from Makefiles. r=nalexander
+
+MozReview-Commit-ID: GJV2O6zvEx2
+
+diff --git a/browser/app/Makefile.in b/browser/app/Makefile.in
+--- a/browser/app/Makefile.in
++++ b/browser/app/Makefile.in
+@@ -12,20 +12,16 @@ AB_CD = en-US
+ ifndef MOZ_WINCONSOLE
+ ifneq (,$(MOZ_DEBUG)$(MOZ_ASAN))
+ MOZ_WINCONSOLE = 1
+ else
+ MOZ_WINCONSOLE = 0
+ endif
+ endif
+ 
+-# This switches $(INSTALL) to copy mode, like $(SYSINSTALL), so things that
+-# shouldn't get 755 perms need $(IFLAGS1) for either way of calling nsinstall.
+-NSDISTMODE = copy
+-
+ include $(topsrcdir)/config/config.mk
+ 
+ # If we are trying to show an error dialog about the lack of SSE2 support,
+ # make sure that code itself doesn't use SSE2.
+ ifdef MOZ_LINUX_32_SSE2_STARTUP_ERROR
+ CXX := $(filter-out -march=% -msse -msse2 -mfpmath=sse,$(CXX))
+ CXX += -march=pentiumpro
+ endif
+diff --git a/ipc/app/Makefile.in b/ipc/app/Makefile.in
+--- a/ipc/app/Makefile.in
++++ b/ipc/app/Makefile.in
+@@ -5,20 +5,16 @@
+ ifndef MOZ_WINCONSOLE
+ ifdef MOZ_DEBUG
+ MOZ_WINCONSOLE = 1
+ else
+ MOZ_WINCONSOLE = 0
+ endif
+ endif
+ 
+-# This switches $(INSTALL) to copy mode, like $(SYSINSTALL), so things that
+-# shouldn't get 755 perms need $(IFLAGS1) for either way of calling nsinstall.
+-NSDISTMODE = copy
+-
+ include $(topsrcdir)/config/config.mk
+ 
+ include $(topsrcdir)/config/rules.mk
+ 
+ ifneq ($(MOZ_WIDGET_TOOLKIT),android)
+ #LIBS += ../contentproc/$(LIB_PREFIX)plugin-container.$(LIB_SUFFIX)
+ endif
+ 
+diff --git a/ipc/ipdl/test/cxx/app/Makefile.in b/ipc/ipdl/test/cxx/app/Makefile.in
+deleted file mode 100644
+--- a/ipc/ipdl/test/cxx/app/Makefile.in
++++ /dev/null
+@@ -1,5 +0,0 @@
+-# This Source Code Form is subject to the terms of the Mozilla Public
+-# 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/.
+-
+-NSDISTMODE = copy
+diff --git a/js/xpconnect/shell/Makefile.in b/js/xpconnect/shell/Makefile.in
+deleted file mode 100644
+--- a/js/xpconnect/shell/Makefile.in
++++ /dev/null
+@@ -1,6 +0,0 @@
+-#
+-# This Source Code Form is subject to the terms of the Mozilla Public
+-# 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/.
+-
+-NSDISTMODE = copy

+ 31 - 0
rel-257/ian/patches/1255485-3-61a1.patch

@@ -0,0 +1,31 @@
+# HG changeset patch
+# User Ted Mielczarek <ted@mielczarek.org>
+# Date 1511382661 18000
+# Node ID 5888578c22f8dc006cfd6a405c9fc53b2df73b44
+# Parent  be723540f9d92976929304da57c3da2cb33780eb
+bug 1255485 - Remove NSDISTMODE=copy support from config.mk. r=nalexander
+
+MozReview-Commit-ID: L5Pe4NexbJD
+
+diff --git a/config/config.mk b/config/config.mk
+--- a/config/config.mk
++++ b/config/config.mk
+@@ -316,17 +316,17 @@ endif # WINNT
+ 
+ ifeq (,$(CROSS_COMPILE)$(filter-out WINNT, $(OS_ARCH)))
+ INSTALL = $(NSINSTALL) -t
+ 
+ else
+ 
+ # This isn't laid out as conditional directives so that NSDISTMODE can be
+ # target-specific.
+-INSTALL         = $(if $(filter copy, $(NSDISTMODE)), $(NSINSTALL) -t, $(if $(filter absolute_symlink, $(NSDISTMODE)), $(NSINSTALL) -L $(PWD), $(NSINSTALL) -R))
++INSTALL         = $(if $(filter absolute_symlink, $(NSDISTMODE)), $(NSINSTALL) -L $(PWD), $(NSINSTALL) -R)
+ 
+ endif # WINNT
+ 
+ # The default for install_cmd is simply INSTALL
+ install_cmd ?= $(INSTALL) $(1)
+ 
+ # Use nsinstall in copy mode to install files on the system
+ SYSINSTALL	= $(NSINSTALL) -t

+ 38 - 0
rel-257/ian/patches/1255485-4-61a1.patch

@@ -0,0 +1,38 @@
+# HG changeset patch
+# User Ted Mielczarek <ted@mielczarek.org>
+# Date 1511791411 18000
+# Node ID 465358fef0d2f6074595d70918d5393bbbbd77d9
+# Parent  748610a122ba51bb44544eacb95bc14d6b8365d0
+bug 1255485 - force import libraries to be generated in objdir, not dist/bin. r=chmanchester
+
+The MSVC linker winds up generating import libraries when linking some of
+our executables, presumably because they contain functions that are
+__declspec(dllexport). By default the import libraries get written
+alongside the exe, so we force them to be written to the objdir so they don't
+clutter up dist/bin.
+
+MozReview-Commit-ID: 7DTfCo3OdDQ
+
+diff --git a/config/rules.mk b/config/rules.mk
+--- a/config/rules.mk
++++ b/config/rules.mk
+@@ -566,17 +566,18 @@ endif
+ #
+ # PROGRAM = Foo
+ # creates OBJS, links with LIBS to create Foo
+ #
+ $(PROGRAM): $(PROGOBJS) $(STATIC_LIBS_DEPS) $(EXTRA_DEPS) $(RESFILE) $(GLOBAL_DEPS) $(call mkdir_deps,$(FINAL_TARGET))
+ 	$(REPORT_BUILD)
+ 	@$(RM) $@.manifest
+ ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+-	$(EXPAND_LINK) -NOLOGO -OUT:$(call LINKER_OUT,$@) -PDB:$(LINK_PDBFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
++	$(EXPAND_LINK) -NOLOGO -OUT:$(call LINKER_OUT,$@) -PDB:$(LINK_PDBFILE) -IMPLIB:$(basename $(@F)).lib $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
++
+ ifdef MSMANIFEST_TOOL
+ 	@if test -f $@.manifest; then \
+ 		if test -f '$(srcdir)/$@.manifest'; then \
+ 			echo 'Embedding manifest from $(srcdir)/$@.manifest and $@.manifest'; \
+ 			$(MT) -NOLOGO -MANIFEST '$(win_srcdir)/$@.manifest' $@.manifest -OUTPUTRESOURCE:$@\;1; \
+ 		else \
+ 			echo 'Embedding manifest from $@.manifest'; \
+ 			$(MT) -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \

+ 224 - 0
rel-257/ian/patches/1255485-5-61a1.patch

@@ -0,0 +1,224 @@
+# HG changeset patch
+# User Ted Mielczarek <ted@mielczarek.org>
+# Date 1516205959 18000
+# Node ID 02e71426ed3e13eecc04ba8184c18b398dca3f67
+# Parent  c1d6bc7887c3d0311ec0e8b3a1de1856188e23fe
+bug 1255485 - add some tests for building programs in dist/bin. r=nalexander
+
+MozReview-Commit-ID: 94uOsInnWmT
+
+diff --git a/python/mozbuild/mozbuild/test/backend/common.py b/python/mozbuild/mozbuild/test/backend/common.py
+--- a/python/mozbuild/mozbuild/test/backend/common.py
++++ b/python/mozbuild/mozbuild/test/backend/common.py
+@@ -192,16 +192,24 @@ CONFIGS = defaultdict(lambda: {
+         'defines': {},
+         'non_global_defines': [],
+         'substs': {
+             'COMPILE_ENVIRONMENT': '1',
+             'LIB_SUFFIX': '.a',
+             'BIN_SUFFIX': '',
+         },
+     },
++    'program-paths': {
++        'defines': {},
++        'non_global_defines': [],
++        'substs': {
++            'COMPILE_ENVIRONMENT': '1',
++            'BIN_SUFFIX': '.prog',
++        },
++    },
+ })
+ 
+ 
+ class BackendTester(unittest.TestCase):
+     def setUp(self):
+         self._old_env = dict(os.environ)
+         os.environ.pop('MOZ_OBJDIR', None)
+ 
+diff --git a/python/mozbuild/mozbuild/test/backend/data/program-paths/dist-bin/moz.build b/python/mozbuild/mozbuild/test/backend/data/program-paths/dist-bin/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/program-paths/dist-bin/moz.build
+@@ -0,0 +1,4 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++Program('dist-bin')
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/data/program-paths/dist-subdir/moz.build b/python/mozbuild/mozbuild/test/backend/data/program-paths/dist-subdir/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/program-paths/dist-subdir/moz.build
+@@ -0,0 +1,5 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++DIST_SUBDIR = 'foo'
++Program('dist-subdir')
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/data/program-paths/final-target/moz.build b/python/mozbuild/mozbuild/test/backend/data/program-paths/final-target/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/program-paths/final-target/moz.build
+@@ -0,0 +1,5 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++FINAL_TARGET = 'final/target'
++Program('final-target')
+diff --git a/python/mozbuild/mozbuild/test/backend/data/program-paths/moz.build b/python/mozbuild/mozbuild/test/backend/data/program-paths/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/program-paths/moz.build
+@@ -0,0 +1,13 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++@template
++def Program(name):
++    PROGRAM = name
++
++DIRS += [
++    'dist-bin',
++    'dist-subdir',
++    'final-target',
++    'not-installed',
++]
+diff --git a/python/mozbuild/mozbuild/test/backend/data/program-paths/not-installed/moz.build b/python/mozbuild/mozbuild/test/backend/data/program-paths/not-installed/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/program-paths/not-installed/moz.build
+@@ -0,0 +1,5 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++DIST_INSTALL = False
++Program('not-installed')
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/test_recursivemake.py b/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
+--- a/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
++++ b/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
+@@ -1021,11 +1021,30 @@ class TestRecursiveMakeBackend(BackendTe
+         # Only mochitest.js should be in the install manifest.
+         self.assertTrue('testing/mochitest/tests/mochitest.js' in m)
+ 
+         # The path is odd here because we do not normalize at test manifest
+         # processing time.  This is a fragile test because there's currently no
+         # way to iterate the manifest.
+         self.assertFalse('instrumentation/./not_packaged.java' in m)
+ 
++    def test_program_paths(self):
++        """PROGRAMs with various moz.build settings that change the destination should produce
++        the expected paths in backend.mk."""
++        env = self._consume('program-paths', RecursiveMakeBackend)
++
++        expected = [
++            ('dist-bin', '$(DEPTH)/dist/bin/dist-bin.prog'),
++            ('dist-subdir', '$(DEPTH)/dist/bin/foo/dist-subdir.prog'),
++            ('final-target', '$(DEPTH)/final/target/final-target.prog'),
++            ('not-installed', 'not-installed.prog'),
++        ]
++        prefix = 'PROGRAM = '
++        for (subdir, expected_program) in expected:
++            with open(os.path.join(env.topobjdir, subdir, 'backend.mk'), 'rb') as fh:
++                lines = fh.readlines()
++                program = [line.rstrip().split(prefix, 1)[1] for line in lines
++                           if line.startswith(prefix)][0]
++                self.assertEqual(program, expected_program)
++
+ 
+ if __name__ == '__main__':
+     main()
+diff --git a/python/mozbuild/mozbuild/test/frontend/data/program-paths/dist-bin/moz.build b/python/mozbuild/mozbuild/test/frontend/data/program-paths/dist-bin/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/frontend/data/program-paths/dist-bin/moz.build
+@@ -0,0 +1,4 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++Program('dist-bin')
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/frontend/data/program-paths/dist-subdir/moz.build b/python/mozbuild/mozbuild/test/frontend/data/program-paths/dist-subdir/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/frontend/data/program-paths/dist-subdir/moz.build
+@@ -0,0 +1,5 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++DIST_SUBDIR = 'foo'
++Program('dist-subdir')
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/frontend/data/program-paths/final-target/moz.build b/python/mozbuild/mozbuild/test/frontend/data/program-paths/final-target/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/frontend/data/program-paths/final-target/moz.build
+@@ -0,0 +1,5 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++FINAL_TARGET = 'final/target'
++Program('final-target')
+diff --git a/python/mozbuild/mozbuild/test/frontend/data/program-paths/moz.build b/python/mozbuild/mozbuild/test/frontend/data/program-paths/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/frontend/data/program-paths/moz.build
+@@ -0,0 +1,13 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++@template
++def Program(name):
++    PROGRAM = name
++
++DIRS += [
++    'dist-bin',
++    'dist-subdir',
++    'final-target',
++    'not-installed',
++]
+diff --git a/python/mozbuild/mozbuild/test/frontend/data/program-paths/not-installed/moz.build b/python/mozbuild/mozbuild/test/frontend/data/program-paths/not-installed/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/frontend/data/program-paths/not-installed/moz.build
+@@ -0,0 +1,5 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++DIST_INSTALL = False
++Program('not-installed')
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/frontend/test_emitter.py b/python/mozbuild/mozbuild/test/frontend/test_emitter.py
+--- a/python/mozbuild/mozbuild/test/frontend/test_emitter.py
++++ b/python/mozbuild/mozbuild/test/frontend/test_emitter.py
+@@ -658,16 +658,29 @@ class TestEmitterBasic(unittest.TestCase
+                          [mozpath.join(reader.config.topobjdir,
+                                        'test_program1.%s' %
+                                        reader.config.substs['OBJ_SUFFIX'])])
+         self.assertEqual(objs[5].objs,
+                          [mozpath.join(reader.config.topobjdir,
+                                        'test_program2.%s' %
+                                        reader.config.substs['OBJ_SUFFIX'])])
+ 
++    def test_program_paths(self):
++        """Various moz.build settings that change the destination of PROGRAM should be
++        accurately reflected in Program.output_path."""
++        reader = self.reader('program-paths')
++        objs = self.read_topsrcdir(reader)
++        prog_paths = [o.output_path for o in objs if isinstance(o, Program)]
++        self.assertEqual(prog_paths, [
++            '!/dist/bin/dist-bin.prog',
++            '!/dist/bin/foo/dist-subdir.prog',
++            '!/final/target/final-target.prog',
++            '!not-installed.prog',
++        ])
++
+     def test_test_manifest_missing_manifest(self):
+         """A missing manifest file should result in an error."""
+         reader = self.reader('test-manifest-missing-manifest')
+ 
+         with self.assertRaisesRegexp(BuildReaderError, 'IOError: Missing files'):
+             self.read_topsrcdir(reader)
+ 
+     def test_empty_test_manifest_rejected(self):

+ 45 - 0
rel-257/ian/patches/1255485-6-61a1.patch

@@ -0,0 +1,45 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1521493652 25200
+# Node ID 7862033a42ab4689c373b64bd363db081ffaee0d
+# Parent  b742821457c98bb767cd5b3bbfd155f274569521
+Bug 1255485 - Don't assume target path is srcdir relative when locating a program's manifest on windows. r=ted
+
+MozReview-Commit-ID: L5BVxWGtpeN
+
+diff --git a/config/rules.mk b/config/rules.mk
+--- a/config/rules.mk
++++ b/config/rules.mk
+@@ -570,26 +570,26 @@ endif
+ $(PROGRAM): $(PROGOBJS) $(STATIC_LIBS_DEPS) $(EXTRA_DEPS) $(RESFILE) $(GLOBAL_DEPS) $(call mkdir_deps,$(FINAL_TARGET))
+ 	$(REPORT_BUILD)
+ 	@$(RM) $@.manifest
+ ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+ 	$(EXPAND_LINK) -NOLOGO -OUT:$(call LINKER_OUT,$@) -PDB:$(LINK_PDBFILE) -IMPLIB:$(basename $(@F)).lib $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
+ 
+ ifdef MSMANIFEST_TOOL
+ 	@if test -f $@.manifest; then \
+-		if test -f '$(srcdir)/$@.manifest'; then \
+-			echo 'Embedding manifest from $(srcdir)/$@.manifest and $@.manifest'; \
+-			$(MT) -NOLOGO -MANIFEST '$(win_srcdir)/$@.manifest' $@.manifest -OUTPUTRESOURCE:$@\;1; \
++		if test -f '$(srcdir)/$(notdir $@).manifest'; then \
++			echo 'Embedding manifest from $(srcdir)/$(notdir $@).manifest and $@.manifest'; \
++			$(MT) -NOLOGO -MANIFEST '$(win_srcdir)/$(notdir $@).manifest' $@.manifest -OUTPUTRESOURCE:$@\;1; \
+ 		else \
+ 			echo 'Embedding manifest from $@.manifest'; \
+ 			$(MT) -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
+ 		fi; \
+-	elif test -f '$(srcdir)/$@.manifest'; then \
+-		echo 'Embedding manifest from $(srcdir)/$@.manifest'; \
+-		$(MT) -NOLOGO -MANIFEST '$(win_srcdir)/$@.manifest' -OUTPUTRESOURCE:$@\;1; \
++	elif test -f '$(srcdir)/$(notdir $@).manifest'; then \
++		echo 'Embedding manifest from $(srcdir)/$(notdir $@).manifest'; \
++		$(MT) -NOLOGO -MANIFEST '$(win_srcdir)/$(notdir $@).manifest' -OUTPUTRESOURCE:$@\;1; \
+ 	fi
+ endif	# MSVC with manifest tool
+ ifdef MOZ_PROFILE_GENERATE
+ # touch it a few seconds into the future to work around FAT's
+ # 2-second granularity
+ 	touch -t `date +%Y%m%d%H%M.%S -d 'now+5seconds'` pgo.relink
+ endif
+ else # !WINNT || GNU_CC

+ 156 - 0
rel-257/ian/patches/1270882-66a1.patch

@@ -0,0 +1,156 @@
+# HG changeset patch
+# User Arfrever Frehtes Taifersar Arahesis <Arfrever@Apache.Org>
+# Date 1543532530 0
+#      Thu Nov 29 23:02:10 2018 +0000
+# Node ID c69cf0bb19cd8d0814011546f5e3e2e6185eb0cd
+# Parent  cdce3f34a2c85cff860d437090e454d8ef575d5e
+Bug 1270882 - Enable support for SQLite custom FTS3 tokenizers at run time. r=mak
+
+Do not require that SQLite has been built with support for custom FTS3
+tokenizers enabled by default. This allows to use system SQLite in
+distributions which provide SQLite configured in this way (which is SQLite
+upstream's default configuration due to security concerns).
+
+Requires exposing the sqlite3_db_config symbol in bundled SQLite.
+
+Disable no longer needed setting of SQLITE_ENABLE_FTS3_TOKENIZER macro in
+bundled SQLite build.
+
+diff --git a/db/sqlite3/src/moz.build b/db/sqlite3/src/moz.build
+--- a/db/sqlite3/src/moz.build
++++ b/db/sqlite3/src/moz.build
+@@ -53,20 +53,16 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'wind
+ # -DSQLITE_ENABLE_LOCKING_STYLE=1 to help with AFP folders
+ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
+     DEFINES['SQLITE_ENABLE_LOCKING_STYLE'] = 1
+ 
+ # sqlite defaults this to on on __APPLE_ but it breaks on newer iOS SDKs
+ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'uikit':
+     DEFINES['SQLITE_ENABLE_LOCKING_STYLE'] = 0
+ 
+-# Thunderbird needs the 2-argument version of fts3_tokenizer()
+-if CONFIG['MOZ_THUNDERBIRD'] or CONFIG['MOZ_SUITE']:
+-    DEFINES['SQLITE_ENABLE_FTS3_TOKENIZER'] = 1
+-
+ # Turn on SQLite's assertions in debug builds.
+ if CONFIG['MOZ_DEBUG']:
+     DEFINES['SQLITE_DEBUG'] = 1
+     DEFINES['SQLITE_ENABLE_API_ARMOR'] = True
+ 
+ if CONFIG['OS_TARGET'] == 'Android':
+     # default to user readable only to fit Android security model
+     DEFINES['SQLITE_DEFAULT_FILE_PERMISSIONS'] = '0600'
+diff --git a/db/sqlite3/src/sqlite.symbols b/db/sqlite3/src/sqlite.symbols
+--- a/db/sqlite3/src/sqlite.symbols
++++ b/db/sqlite3/src/sqlite.symbols
+@@ -40,16 +40,17 @@ sqlite3_complete
+ sqlite3_complete16
+ sqlite3_config
+ sqlite3_create_collation
+ sqlite3_create_collation16
+ sqlite3_create_function
+ sqlite3_create_function16
+ sqlite3_create_module
+ sqlite3_data_count
++sqlite3_db_config
+ sqlite3_db_filename
+ sqlite3_db_handle
+ sqlite3_db_mutex
+ sqlite3_db_status
+ sqlite3_declare_vtab
+ sqlite3_enable_load_extension
+ sqlite3_enable_shared_cache
+ sqlite3_errcode
+diff --git a/storage/moz.build b/storage/moz.build
+--- a/storage/moz.build
++++ b/storage/moz.build
+@@ -101,16 +101,20 @@ FINAL_LIBRARY = 'xul'
+ #
+ # Note: On Windows our sqlite build assumes we use jemalloc.  If you disable
+ # MOZ_STORAGE_MEMORY on Windows, you will also need to change the "ifdef
+ # MOZ_MEMORY" options in db/sqlite3/src/Makefile.in.
+ if CONFIG['MOZ_MEMORY'] and not CONFIG['MOZ_SYSTEM_SQLITE']:
+     if CONFIG['OS_TARGET'] != 'Android':
+         DEFINES['MOZ_STORAGE_MEMORY'] = True
+ 
++# Thunderbird needs the 2-argument version of fts3_tokenizer()
++if CONFIG['MOZ_THUNDERBIRD'] or CONFIG['MOZ_SUITE']:
++    DEFINES['MOZ_SQLITE_FTS3_TOKENIZER'] = 1
++
+ # This is the default value.  If we ever change it when compiling sqlite, we
+ # will need to change it here as well.
+ DEFINES['SQLITE_MAX_LIKE_PATTERN_LENGTH'] = 50000
+ 
+ # See Sqlite moz.build for reasoning about TEMP_STORE.
+ # For system sqlite we cannot use the compile time option, so we use a pragma.
+ if CONFIG['MOZ_SYSTEM_SQLITE'] and (CONFIG['OS_TARGET'] == 'Android'
+                                     or CONFIG['HAVE_64BIT_BUILD']):
+diff --git a/storage/mozStorageConnection.cpp b/storage/mozStorageConnection.cpp
+--- a/storage/mozStorageConnection.cpp
++++ b/storage/mozStorageConnection.cpp
+@@ -598,16 +598,21 @@ nsresult Connection::initialize() {
+ 
+   // in memory database requested, sqlite uses a magic file name
+   int srv = ::sqlite3_open_v2(":memory:", &mDBConn, mFlags, GetVFSName());
+   if (srv != SQLITE_OK) {
+     mDBConn = nullptr;
+     return convertResultCode(srv);
+   }
+ 
++#ifdef MOZ_SQLITE_FTS3_TOKENIZER
++  srv = ::sqlite3_db_config(mDBConn, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
++  MOZ_ASSERT(srv == SQLITE_OK, "SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
++#endif
++
+   // Do not set mDatabaseFile or mFileURL here since this is a "memory"
+   // database.
+ 
+   nsresult rv = initializeInternal();
+   NS_ENSURE_SUCCESS(rv, rv);
+ 
+   return NS_OK;
+ }
+@@ -632,16 +637,21 @@ nsresult Connection::initialize(nsIFile 
+ 
+   int srv = ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path).get(), &mDBConn,
+                               mFlags, vfs);
+   if (srv != SQLITE_OK) {
+     mDBConn = nullptr;
+     return convertResultCode(srv);
+   }
+ 
++#ifdef MOZ_SQLITE_FTS3_TOKENIZER
++  srv = ::sqlite3_db_config(mDBConn, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
++  MOZ_ASSERT(srv == SQLITE_OK, "SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
++#endif
++
+   // Do not set mFileURL here since this is database does not have an associated
+   // URL.
+   mDatabaseFile = aDatabaseFile;
+ 
+   rv = initializeInternal();
+   NS_ENSURE_SUCCESS(rv, rv);
+ 
+   return NS_OK;
+@@ -661,16 +671,21 @@ nsresult Connection::initialize(nsIFileU
+   NS_ENSURE_SUCCESS(rv, rv);
+ 
+   int srv = ::sqlite3_open_v2(spec.get(), &mDBConn, mFlags, GetVFSName());
+   if (srv != SQLITE_OK) {
+     mDBConn = nullptr;
+     return convertResultCode(srv);
+   }
+ 
++#ifdef MOZ_SQLITE_FTS3_TOKENIZER
++  srv = ::sqlite3_db_config(mDBConn, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
++  MOZ_ASSERT(srv == SQLITE_OK, "SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
++#endif
++
+   // Set both mDatabaseFile and mFileURL here.
+   mFileURL = aFileURL;
+   mDatabaseFile = databaseFile;
+ 
+   rv = initializeInternal();
+   NS_ENSURE_SUCCESS(rv, rv);
+ 
+   return NS_OK;

+ 131 - 0
rel-257/ian/patches/1301547-63a1.patch

@@ -0,0 +1,131 @@
+# HG changeset patch
+# User David Keeler <dkeeler@mozilla.com>
+# Date 1531783815 25200
+#      Mon Jul 16 16:30:15 2018 -0700
+# Node ID bbe392227b7d6376bb99843e781e7bd056ddeaba
+# Parent  4d5ec33dc1fcfc58f491a849426c1b64702c551b
+bug 1301547 - remove ancient workaround in client certificate code r=franziskus
+
+Apparently a prehistoric server implementation would send a
+certificate_authorities field that didn't include the outer DER SEQUENCE tag, so
+PSM attempted to detect this and work around it. Telemetry indicates this is
+unnecessary now: https://mzl.la/2Lbi1Lz
+
+diff --git a/security/manager/ssl/nsNSSIOLayer.cpp b/security/manager/ssl/nsNSSIOLayer.cpp
+--- a/security/manager/ssl/nsNSSIOLayer.cpp
++++ b/security/manager/ssl/nsNSSIOLayer.cpp
+@@ -1805,92 +1805,35 @@ static SECStatus nsConvertCANamesToStrin
+   MOZ_ASSERT(caNameStrings);
+   MOZ_ASSERT(caNames);
+   if (!arena.get() || !caNameStrings || !caNames) {
+     PR_SetError(SEC_ERROR_INVALID_ARGS, 0);
+     return SECFailure;
+   }
+ 
+   SECItem* dername;
+-  SECStatus rv;
+-  int headerlen;
+-  uint32_t contentlen;
+-  SECItem newitem;
+   int n;
+   char* namestring;
+ 
+   for (n = 0; n < caNames->nnames; n++) {
+-    newitem.data = nullptr;
+     dername = &caNames->names[n];
+-
+-    rv = DER_Lengths(dername, &headerlen, &contentlen);
+-
+-    if (rv != SECSuccess) {
+-      goto loser;
+-    }
+-
+-    if (headerlen + contentlen != dername->len) {
+-      // This must be from an enterprise 2.x server, which sent
+-      // incorrectly formatted der without the outer wrapper of type and
+-      // length. Fix it up by adding the top level header.
+-      if (dername->len <= 127) {
+-        newitem.data = (unsigned char*)malloc(dername->len + 2);
+-        if (!newitem.data) {
+-          goto loser;
+-        }
+-        newitem.data[0] = (unsigned char)0x30;
+-        newitem.data[1] = (unsigned char)dername->len;
+-        (void)memcpy(&newitem.data[2], dername->data, dername->len);
+-      } else if (dername->len <= 255) {
+-        newitem.data = (unsigned char*)malloc(dername->len + 3);
+-        if (!newitem.data) {
+-          goto loser;
+-        }
+-        newitem.data[0] = (unsigned char)0x30;
+-        newitem.data[1] = (unsigned char)0x81;
+-        newitem.data[2] = (unsigned char)dername->len;
+-        (void)memcpy(&newitem.data[3], dername->data, dername->len);
+-      } else {
+-        // greater than 256, better be less than 64k
+-        newitem.data = (unsigned char*)malloc(dername->len + 4);
+-        if (!newitem.data) {
+-          goto loser;
+-        }
+-        newitem.data[0] = (unsigned char)0x30;
+-        newitem.data[1] = (unsigned char)0x82;
+-        newitem.data[2] = (unsigned char)((dername->len >> 8) & 0xff);
+-        newitem.data[3] = (unsigned char)(dername->len & 0xff);
+-        memcpy(&newitem.data[4], dername->data, dername->len);
+-      }
+-      dername = &newitem;
+-    }
+-
+     namestring = CERT_DerNameToAscii(dername);
+     if (!namestring) {
+       // XXX - keep going until we fail to convert the name
+       caNameStrings[n] = const_cast<char*>("");
+     } else {
+       caNameStrings[n] = PORT_ArenaStrdup(arena.get(), namestring);
+       PR_Free(namestring);  // CERT_DerNameToAscii() uses PR_Malloc().
+       if (!caNameStrings[n]) {
+-        goto loser;
++        return SECFailure;
+       }
+     }
+-
+-    if (newitem.data) {
+-      free(newitem.data);
+-    }
+   }
+ 
+   return SECSuccess;
+-loser:
+-  if (newitem.data) {
+-    free(newitem.data);
+-  }
+-  return SECFailure;
+ }
+ 
+ // Possible behaviors for choosing a cert for client auth.
+ enum class UserCertChoice {
+   // Ask the user to choose a cert.
+   Ask = 0,
+   // Automatically choose a cert.
+   Auto = 1,
+diff --git a/security/nss.symbols b/security/nss.symbols
+--- a/security/nss.symbols
++++ b/security/nss.symbols
+@@ -158,17 +158,16 @@ DER_AsciiToTime_Util
+ DER_DecodeTimeChoice_Util
+ DER_Encode
+ DER_EncodeTimeChoice_Util
+ DER_Encode_Util
+ DER_GeneralizedTimeToTime
+ DER_GeneralizedTimeToTime_Util
+ DER_GetInteger
+ DER_GetInteger_Util
+-DER_Lengths
+ DER_SetUInteger
+ DER_UTCTimeToTime_Util
+ DSAU_DecodeDerSigToLen
+ DSAU_EncodeDerSigWithLen
+ DTLS_GetHandshakeTimeout
+ DTLS_ImportFD
+ HASH_Begin
+ HASH_Create

+ 86 - 0
rel-257/ian/patches/1336712-65a1.patch

@@ -0,0 +1,86 @@
+# HG changeset patch
+# User Chris Peterson <cpeterson@mozilla.com>
+# Date 1541718719 0
+# Node ID e006dd6e8fbd62dd57538294ac29e3489cb823ae
+# Parent  8da2ef9cfccf26b58ae73db01777ce8cabbf2541
+Bug 1336712 - toolkit: Drop test checks for OS X <= 10.8 and Windows XP. r=kmag
+
+Depends on D6584
+
+Differential Revision: https://phabricator.services.mozilla.com/D6585
+
+diff --git a/toolkit/content/aboutSupport.js b/toolkit/content/aboutSupport.js
+--- a/toolkit/content/aboutSupport.js
++++ b/toolkit/content/aboutSupport.js
+@@ -57,20 +57,16 @@ var snapshotFormatters = {
+       case 1:
+       case 2:
+       case 4:
+       case 6:
+       case 7:
+       case 8:
+         statusText = strings.GetStringFromName("multiProcessStatus." + data.autoStartStatus);
+         break;
+-
+-      case 10:
+-        statusText = (Services.appinfo.OS == "Darwin" ? "OS X 10.6 - 10.8" : "Windows XP");
+-        break;
+     }
+ 
+     $("multiprocess-box").textContent = strings.formatStringFromName("multiProcessWindows",
+       [data.numRemoteWindows, data.numTotalWindows, statusText], 3);
+ 
+     if (data.remoteAutoStart) {
+       $("contentprocesses-box").textContent = data.currentContentProcesses +
+                                               "/" +
+diff --git a/toolkit/content/tests/chrome/test_bug624329.xul b/toolkit/content/tests/chrome/test_bug624329.xul
+--- a/toolkit/content/tests/chrome/test_bug624329.xul
++++ b/toolkit/content/tests/chrome/test_bug624329.xul
+@@ -49,23 +49,21 @@ function childFocused() {
+     // maximizing the window is a simple way to ensure that the menu is near
+     // the right edge of the screen.
+ 
+     listenOnce("resize", childResized);
+     win.maximize();
+ }
+ 
+ function childResized() {
+-    const isOSXLion = navigator.userAgent.includes("Mac OS X 10.7");
+-    const isOSXMtnLion = navigator.userAgent.includes("Mac OS X 10.8");
+     const isOSXMavericks = navigator.userAgent.includes("Mac OS X 10.9");
+     const isOSXYosemite = navigator.userAgent.includes("Mac OS X 10.10");
+-    if (isOSXLion || isOSXMtnLion || isOSXMavericks || isOSXYosemite) {
++    if (isOSXMavericks || isOSXYosemite) {
+         todo_is(win.windowState, win.STATE_MAXIMIZED,
+-                "A resize before being maximized breaks this test on 10.7 and 10.8 and 10.9 and 10.10");
++                "A resize before being maximized breaks this test on 10.9 and 10.10");
+         finish();
+         return;
+     }
+ 
+     is(win.windowState, win.STATE_MAXIMIZED,
+        "window should be maximized");
+ 
+     isnot(win.innerWidth, 300,
+diff --git a/toolkit/locales/en-US/chrome/global/aboutSupport.properties b/toolkit/locales/en-US/chrome/global/aboutSupport.properties
+--- a/toolkit/locales/en-US/chrome/global/aboutSupport.properties
++++ b/toolkit/locales/en-US/chrome/global/aboutSupport.properties
+@@ -132,18 +132,16 @@ multiProcessWindows = %1$S/%2$S (%3$S)
+ multiProcessStatus.0 = Enabled by user
+ multiProcessStatus.1 = Enabled by default
+ multiProcessStatus.2 = Disabled
+ multiProcessStatus.4 = Disabled by accessibility tools
+ multiProcessStatus.5 = Disabled by lack of graphics hardware acceleration on Mac OS X
+ multiProcessStatus.6 = Disabled by unsupported text input
+ multiProcessStatus.7 = Disabled by add-ons
+ multiProcessStatus.8 = Disabled forcibly
+-# No longer in use (bug 1296353) but we might bring this back.
+-multiProcessStatus.9 = Disabled by graphics hardware acceleration on Windows XP
+ multiProcessStatus.unknown = Unknown status
+ 
+ asyncPanZoom = Asynchronous Pan/Zoom
+ apzNone = none
+ wheelEnabled = wheel input enabled
+ touchEnabled = touch input enabled
+ dragEnabled = scrollbar drag enabled
+ keyboardEnabled = keyboard enabled

+ 95 - 0
rel-257/ian/patches/1340588-61a1.patch

@@ -0,0 +1,95 @@
+# HG changeset patch
+# User Nathan Froyd <froydnj@mozilla.com>
+# Date 1520949960 18000
+# Node ID 30dc6c484d42504bb586b7b02cf6561dbd50136e
+# Parent  cf81252a02b56669955158f4e4ab3bc7bfdc59b4
+Bug 1340588 - enable clang-cl to generate depfiles directly, rather than using a wrapper; r=build-peer
+
+We use a wrapper script when compiling with MSVC to parse the
+/showIncludes output and thereby generate a Makefile dependency
+fragment.  This fragment enables us to do correct and faster incremental
+builds.  But the cost of invoking the wrapper script can be significant;
+it's an extra process or two to launch for every single compilation.
+
+Instead, let's have clang-cl generate the dependencies directly, which
+should be somewhat faster.
+
+diff --git a/config/config.mk b/config/config.mk
+--- a/config/config.mk
++++ b/config/config.mk
+@@ -115,18 +115,21 @@ else
+   win_srcdir := $(srcdir)
+   BUILD_TOOLS = $(MOZILLA_DIR)/build/unix
+ endif
+ 
+ CONFIG_TOOLS	= $(MOZ_BUILD_ROOT)/config
+ AUTOCONF_TOOLS	= $(MOZILLA_DIR)/build/autoconf
+ 
+ ifdef _MSC_VER
++# clang-cl is smart enough to generate dependencies directly.
++ifndef CLANG_CL
+ CC_WRAPPER ?= $(call py_action,cl)
+ CXX_WRAPPER ?= $(call py_action,cl)
++endif # CLANG_CL
+ endif # _MSC_VER
+ 
+ CC := $(CC_WRAPPER) $(CC)
+ CXX := $(CXX_WRAPPER) $(CXX)
+ MKDIR ?= mkdir
+ SLEEP ?= sleep
+ TOUCH ?= touch
+ 
+diff --git a/js/src/old-configure.in b/js/src/old-configure.in
+--- a/js/src/old-configure.in
++++ b/js/src/old-configure.in
+@@ -1606,16 +1606,23 @@ dnl =
+ dnl = Build depencency options
+ dnl =
+ dnl ========================================================
+ MOZ_ARG_HEADER(Build dependencies)
+ 
+ if test "$GNU_CC" -a "$GNU_CXX"; then
+   _DEPEND_CFLAGS='-MD -MP -MF $(MDDEPDIR)/$(@F).pp'
+ else
++  # clang-cl doesn't accept the normal -MD -MP -MF options that clang does, but
++  # the underlying cc1 binary understands how to generate dependency files.
++  # These options are based on analyzing what the normal clang driver sends to
++  # cc1 when given the "correct" dependency options.
++  if test -n "$CLANG_CL"; then
++   _DEPEND_CFLAGS='-Xclang -MP -Xclang -MG -Xclang -dependency-file -Xclang $(MDDEPDIR)/$(@F).pp -Xclang -MT -Xclang $@'
++  fi
+   dnl Don't override this for MSVC
+   if test -z "$_WIN32_MSVC"; then
+     _USE_CPP_INCLUDE_FLAG=
+     _DEFINES_CFLAGS='$(ACDEFINES) -D_JS_CONFDEFS_H_ -DMOZILLA_CLIENT'
+     _DEFINES_CXXFLAGS='$(ACDEFINES) -D_JS_CONFDEFS_H_ -DMOZILLA_CLIENT'
+   else
+     echo '#include <stdio.h>' > dummy-hello.c
+     changequote(,)
+diff --git a/old-configure.in b/old-configure.in
+--- a/old-configure.in
++++ b/old-configure.in
+@@ -3697,16 +3697,23 @@ dnl = Build depencency options
+ dnl =
+ dnl ========================================================
+ MOZ_ARG_HEADER(Build dependencies)
+ 
+ if test "$COMPILE_ENVIRONMENT"; then
+ if test "$GNU_CC" -a "$GNU_CXX"; then
+   _DEPEND_CFLAGS='-MD -MP -MF $(MDDEPDIR)/$(@F).pp'
+ else
++  # clang-cl doesn't accept the normal -MD -MP -MF options that clang does, but
++  # the underlying cc1 binary understands how to generate dependency files.
++  # These options are based on analyzing what the normal clang driver sends to
++  # cc1 when given the "correct" dependency options.
++  if test -n "$CLANG_CL"; then
++   _DEPEND_CFLAGS='-Xclang -MP -Xclang -MG -Xclang -dependency-file -Xclang $(MDDEPDIR)/$(@F).pp -Xclang -MT -Xclang $@'
++  fi
+   dnl Don't override this for MSVC
+   if test -z "$_WIN32_MSVC"; then
+     _USE_CPP_INCLUDE_FLAG=
+     _DEFINES_CFLAGS='$(ACDEFINES) -D_MOZILLA_CONFIG_H_ -DMOZILLA_CLIENT'
+     _DEFINES_CXXFLAGS='$(ACDEFINES) -D_MOZILLA_CONFIG_H_ -DMOZILLA_CLIENT'
+   else
+     echo '#include <stdio.h>' > dummy-hello.c
+     changequote(,)

+ 59 - 0
rel-257/ian/patches/1341222-1-63a1.patch

@@ -0,0 +1,59 @@
+# HG changeset patch
+# User Mike Hommey <mh+mozilla@glandium.org>
+# Date 1534299246 -32400
+# Node ID eb76188a858d82efa7b1854dcfc6d83a7f75d13f
+# Parent  680d247fee2f07206eb0847ad5517db83e6fa545
+Bug 1341222 - Allow !- and %-prefixed paths in include paths processed by gyp. r=froydnj
+
+diff --git a/python/mozbuild/mozbuild/frontend/gyp_reader.py b/python/mozbuild/mozbuild/frontend/gyp_reader.py
+--- a/python/mozbuild/mozbuild/frontend/gyp_reader.py
++++ b/python/mozbuild/mozbuild/frontend/gyp_reader.py
+@@ -262,30 +262,34 @@ def process_gyp_result(gyp_result, gyp_d
+                 if include.startswith(product_dir_dist):
+                     # special-case includes of <(PRODUCT_DIR)/dist/ to match
+                     # handle_copies above. This is used for NSS' exports.
+                     include = '!/dist/include/' + include[len(product_dir_dist):]
+                 elif include.startswith(config.topobjdir):
+                     # NSPR_INCLUDE_DIR gets passed into the NSS build this way.
+                     include = '!/' + mozpath.relpath(include, config.topobjdir)
+                 else:
+-                  # moz.build expects all LOCAL_INCLUDES to exist, so ensure they do.
+-                  #
+-                  # NB: gyp files sometimes have actual absolute paths (e.g.
+-                  # /usr/include32) and sometimes paths that moz.build considers
+-                  # absolute, i.e. starting from topsrcdir. There's no good way
+-                  # to tell them apart here, and the actual absolute paths are
+-                  # likely bogus. In any event, actual absolute paths will be
+-                  # filtered out by trying to find them in topsrcdir.
+-                  if include.startswith('/'):
+-                      resolved = mozpath.abspath(mozpath.join(config.topsrcdir, include[1:]))
+-                  else:
+-                      resolved = mozpath.abspath(mozpath.join(mozpath.dirname(build_file), include))
+-                  if not os.path.exists(resolved):
+-                      continue
++                    # moz.build expects all LOCAL_INCLUDES to exist, so ensure they do.
++                    #
++                    # NB: gyp files sometimes have actual absolute paths (e.g.
++                    # /usr/include32) and sometimes paths that moz.build considers
++                    # absolute, i.e. starting from topsrcdir. There's no good way
++                    # to tell them apart here, and the actual absolute paths are
++                    # likely bogus. In any event, actual absolute paths will be
++                    # filtered out by trying to find them in topsrcdir.
++                    #
++                    # We do allow !- and %-prefixed paths, assuming they come
++                    # from moz.build and will be handled the same way as if they
++                    # were given to LOCAL_INCLUDES in moz.build.
++                    if include.startswith('/'):
++                        resolved = mozpath.abspath(mozpath.join(config.topsrcdir, include[1:]))
++                    elif not include.startswith(('!', '%')):
++                        resolved = mozpath.abspath(mozpath.join(mozpath.dirname(build_file), include))
++                    if not include.startswith(('!', '%')) and not os.path.exists(resolved):
++                        continue
+                 context['LOCAL_INCLUDES'] += [include]
+ 
+             context['ASFLAGS'] = target_conf.get('asflags_mozilla', [])
+             if use_defines_in_asflags and defines:
+                 context['ASFLAGS'] += ['-D' + d for d in defines]
+             flags = target_conf.get('cflags_mozilla', [])
+             if flags:
+                 suffix_map = {

+ 31 - 0
rel-257/ian/patches/1341222-2-63a1.patch

@@ -0,0 +1,31 @@
+# HG changeset patch
+# User Mike Hommey <mh+mozilla@glandium.org>
+# Date 1534299320 -32400
+# Node ID b0a7377f4f600a81faf8951d374945dc7882c6f4
+# Parent  7e756d780e398b0707cd0fddd1c6dbb2c5802db6
+Bug 1341222 - Avoid m4 breaking the sed expressions that set NSPR_INCLUDE_DIR and NSPR_LIB_DIR. r=froydnj
+
+diff --git a/build/autoconf/nspr-build.m4 b/build/autoconf/nspr-build.m4
+--- a/build/autoconf/nspr-build.m4
++++ b/build/autoconf/nspr-build.m4
+@@ -151,18 +151,18 @@ if test -n "$MOZ_SYSTEM_NSPR" -o -n "$NS
+                 AC_MSG_ERROR([system NSPR does not support PR_STATIC_ASSERT or including prtypes.h does not provide it]))
+     AC_TRY_COMPILE([#include "prtypes.h"],
+                 [#ifndef PR_UINT64
+                  #error PR_UINT64 not defined or requires including prtypes.h
+                  #endif],
+                 ,
+                 AC_MSG_ERROR([system NSPR does not support PR_UINT64 or including prtypes.h does not provide it]))
+     CFLAGS=$_SAVE_CFLAGS
+-    NSPR_INCLUDE_DIR=`echo ${NSPR_CFLAGS} | sed -e 's/.*-I\([^ ]*\).*/\1/'`
+-    NSPR_LIB_DIR=`echo ${NSPR_LIBS} | sed -e 's/.*-L\([^ ]*\).*/\1/'`
++    NSPR_INCLUDE_DIR=`echo ${NSPR_CFLAGS} | sed -e 's/.*-I\([[^ ]]*\).*/\1/'`
++    NSPR_LIB_DIR=`echo ${NSPR_LIBS} | sed -e 's/.*-L\([[^ ]]*\).*/\1/'`
+ elif test -z "$JS_POSIX_NSPR"; then
+     NSPR_INCLUDE_DIR="${DIST}/include/nspr"
+     NSPR_CFLAGS="-I${NSPR_INCLUDE_DIR}"
+     if test -n "$GNU_CC"; then
+         if test -n "$MOZ_FOLD_LIBS"; then
+            NSPR_LIB_DIR=${DIST}/lib
+         else
+            NSPR_LIB_DIR=${DIST}/bin

+ 59 - 0
rel-257/ian/patches/1341222-3-63a1.patch

@@ -0,0 +1,59 @@
+# HG changeset patch
+# User Mike Hommey <mh+mozilla@glandium.org>
+# Date 1534299454 -32400
+# Node ID f3c1b09b9477b6f03fc0ecce5568401d7161ce8b
+# Parent  b0a7377f4f600a81faf8951d374945dc7882c6f4
+Bug 1341222 - Fix building in-tree NSS against system NSPR. r=froydnj
+
+
+diff --git a/security/moz.build b/security/moz.build
+--- a/security/moz.build
++++ b/security/moz.build
+@@ -52,17 +52,17 @@ else:
+         Library('nss')
+         USE_LIBS += [
+             'nss3',
+             'nssutil3',
+             'smime3',
+             'sqlite',
+             'ssl3',
+         ]
+-        gyp_vars['nspr_libs'] = 'nspr4 plc4 plds4'
++        gyp_vars['nspr_libs'] = 'nspr'
+ 
+     # This disables building some NSS tools.
+     gyp_vars['mozilla_client'] = 1
+     # We run shlibsign as part of packaging, not build.
+     gyp_vars['sign_libs'] = 0
+     gyp_vars['python'] = CONFIG['PYTHON']
+     # The NSS gyp files do not have a default for this.
+     gyp_vars['nss_dist_dir'] = '$PRODUCT_DIR/dist'
+@@ -80,18 +80,25 @@ else:
+     # pkg-config won't reliably find zlib on our builders, so just force it.
+     # System zlib is only used for modutil and signtool unless
+     # SSL zlib is enabled, which we are disabling immediately below this.
+     gyp_vars['zlib_libs'] = '-lz'
+     gyp_vars['ssl_enable_zlib'] = 0
+     # System sqlite here is the in-tree mozsqlite.
+     gyp_vars['use_system_sqlite'] = 1
+     gyp_vars['sqlite_libs'] = 'sqlite'
+-    gyp_vars['nspr_include_dir'] = CONFIG['NSPR_INCLUDE_DIR']
+-    gyp_vars['nspr_lib_dir'] = CONFIG['NSPR_LIB_DIR']
++
++    if CONFIG['MOZ_SYSTEM_NSPR']:
++        gyp_vars['nspr_include_dir'] = '%' + CONFIG['NSPR_INCLUDE_DIR']
++        gyp_vars['nspr_lib_dir'] = '%' + CONFIG['NSPR_LIB_DIR']
++    else:
++        gyp_vars['nspr_include_dir'] = '!/dist/include/nspr'
++        gyp_vars['nspr_lib_dir'] = ''  # gyp wants a value, but we don't need
++                                       # it to be valid.
++
+     # The Python scripts that detect clang need it to be set as CC
+     # in the environment, which isn't true here. I don't know that
+     # setting that would be harmful, but we already have this information
+     # anyway.
+     if CONFIG['CC_TYPE'] in ('clang', 'clang-cl'):
+         gyp_vars['cc_is_clang'] = 1
+     if CONFIG['GCC_USE_GNU_LD']:
+         gyp_vars['cc_use_gnu_ld'] = 1
+

+ 224 - 0
rel-257/ian/patches/1351078-67a1.patch

@@ -0,0 +1,224 @@
+# HG changeset patch
+# User Felipe Gomes <felipc@gmail.com>
+# Date 1550854286 0
+# Node ID f79d064a028c5f7898da39a72e5573ec7c1b2fd2
+# Parent  ff454130893adb9d281626354e02a7ffe0dacd39
+Bug 1351078 - Remove unused Battery.jsm. r=Yoric
+
+Differential Revision: https://phabricator.services.mozilla.com/D20756
+
+diff --git a/browser/base/content/test/static/browser_all_files_referenced.js b/browser/base/content/test/static/browser_all_files_referenced.js
+--- a/browser/base/content/test/static/browser_all_files_referenced.js
++++ b/browser/base/content/test/static/browser_all_files_referenced.js
+@@ -141,18 +141,16 @@ var whitelist = [
+   // Bug 1348533
+   {file: "chrome://mozapps/skin/downloads/buttons.png", platforms: ["macosx"]},
+   {file: "chrome://mozapps/skin/downloads/downloadButtons.png", platforms: ["linux", "win"]},
+   // Bug 1348558
+   {file: "chrome://mozapps/skin/update/downloadButtons.png",
+    platforms: ["linux"]},
+   // Bug 1348559
+   {file: "chrome://pippki/content/resetpassword.xul"},
+-  // Bug 1351078
+-  {file: "resource://gre/modules/Battery.jsm"},
+   // Bug 1337345
+   {file: "resource://gre/modules/Manifest.jsm"},
+   // Bug 1351097
+   {file: "resource://gre/modules/accessibility/AccessFu.jsm"},
+   // Bug 1356043
+   {file: "resource://gre/modules/PerfMeasurement.jsm"},
+   // Bug 1356045
+   {file: "chrome://global/content/test-ipc.xul"},
+diff --git a/toolkit/modules/Battery.jsm b/toolkit/modules/Battery.jsm
+deleted file mode 100644
+--- a/toolkit/modules/Battery.jsm
++++ /dev/null
+@@ -1,69 +0,0 @@
+-// -*- Mode: javascript; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+-// This Source Code Form is subject to the terms of the Mozilla Public
+-// 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";
+-
+-/** This module wraps around navigator.getBattery (https://developer.mozilla.org/en-US/docs/Web/API/Navigator.getBattery).
+-  * and provides a framework for spoofing battery values in test code.
+-  * To spoof the battery values, set `Debugging.fake = true` after exporting this with a BackstagePass,
+-  * after which you can spoof a property yb setting the relevant property of the BatteryManager object.
+-  */
+-var EXPORTED_SYMBOLS = ["GetBattery", "Battery"];
+-
+-ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm", this);
+-
+-// Load Services, for the BatteryManager API
+-ChromeUtils.defineModuleGetter(this, "Services",
+-  "resource://gre/modules/Services.jsm");
+-
+-// Values for the fake battery. See the documentation of Navigator.battery for the meaning of each field.
+-var gFakeBattery = {
+-  charging: false,
+-  chargingTime: 0,
+-  dischargingTime: Infinity,
+-  level: 1,
+-};
+-
+-// BackendPass-exported object for toggling spoofing
+-var Debugging = {
+-  /**
+-   * If `false`, use the DOM Battery implementation.
+-   * Set it to `true` if you need to fake battery values
+-   * for testing or debugging purposes.
+-   */
+-  fake: false
+-};
+-
+-var GetBattery = function() {
+-  return new Services.appShell.hiddenDOMWindow.Promise(function(resolve, reject) {
+-    // Return fake values if spoofing is enabled, otherwise fetch the real values from the BatteryManager API
+-    if (Debugging.fake) {
+-      resolve(gFakeBattery);
+-      return;
+-    }
+-    Services.appShell.hiddenDOMWindow.navigator.getBattery().then(resolve, reject);
+-  });
+-};
+-
+-var Battery = {};
+-
+-for (let k of ["charging", "chargingTime", "dischargingTime", "level"]) {
+-  let prop = k;
+-  Object.defineProperty(this.Battery, prop, {
+-    get() {
+-      // Return fake value if spoofing is enabled, otherwise fetch the real value from the BatteryManager API
+-      if (Debugging.fake) {
+-        return gFakeBattery[prop];
+-      }
+-      return Services.appShell.hiddenDOMWindow.navigator.battery[prop];
+-    },
+-    set(fakeSetting) {
+-      if (!Debugging.fake) {
+-        throw new Error("Tried to set fake battery value when battery spoofing was disabled");
+-      }
+-      gFakeBattery[prop] = fakeSetting;
+-    }
+-  });
+-}
+diff --git a/toolkit/modules/moz.build b/toolkit/modules/moz.build
+--- a/toolkit/modules/moz.build
++++ b/toolkit/modules/moz.build
+@@ -171,17 +171,16 @@ EXTRA_JS_MODULES += [
+     'addons/WebNavigationContent.js',
+     'addons/WebNavigationFrames.jsm',
+     'addons/WebRequest.jsm',
+     'addons/WebRequestCommon.jsm',
+     'addons/WebRequestContent.js',
+     'addons/WebRequestUpload.jsm',
+     'AppMenuNotifications.jsm',
+     'AsyncPrefs.jsm',
+-    'Battery.jsm',
+     'BinarySearch.jsm',
+     'BrowserUtils.jsm',
+     'CanonicalJSON.jsm',
+     'CertUtils.jsm',
+     'CharsetMenu.jsm',
+     'ClientID.jsm',
+     'Color.jsm',
+     'Console.jsm',
+diff --git a/toolkit/modules/tests/browser/browser.ini b/toolkit/modules/tests/browser/browser.ini
+--- a/toolkit/modules/tests/browser/browser.ini
++++ b/toolkit/modules/tests/browser/browser.ini
+@@ -22,17 +22,16 @@ support-files =
+   file_script_bad.js
+   file_script_redirect.js
+   file_script_xhr.js
+   head.js
+   WebRequest_dynamic.sjs
+   WebRequest_redirection.sjs
+ 
+ [browser_AsyncPrefs.js]
+-[browser_Battery.js]
+ [browser_BrowserUtils.js]
+ [browser_Deprecated.js]
+ [browser_Finder.js]
+ [browser_Finder_hidden_textarea.js]
+ [browser_Finder_offscreen_text.js]
+ [browser_Finder_overflowed_textarea.js]
+ [browser_Finder_pointer_events_none.js]
+ [browser_Finder_vertical_text.js]
+diff --git a/toolkit/modules/tests/browser/browser_Battery.js b/toolkit/modules/tests/browser/browser_Battery.js
+deleted file mode 100644
+--- a/toolkit/modules/tests/browser/browser_Battery.js
++++ /dev/null
+@@ -1,51 +0,0 @@
+-/* This Source Code Form is subject to the terms of the Mozilla Public
+- * 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";
+-var {GetBattery, Debugging} = ChromeUtils.import("resource://gre/modules/Battery.jsm", {});
+-ChromeUtils.import("resource://gre/modules/Services.jsm", this);
+-
+-function test() {
+-  waitForExplicitFinish();
+-
+-  is(Debugging.fake, false, "Battery spoofing is initially false");
+-
+-  GetBattery().then(function(battery) {
+-    for (let k of ["charging", "chargingTime", "dischargingTime", "level"]) {
+-      let backup = battery[k];
+-      try {
+-        battery[k] = "__magic__";
+-      } catch (e) {
+-        // We are testing that we cannot set battery to new values
+-        // when "use strict" is enabled, this throws a TypeError
+-        if (e.name != "TypeError")
+-          throw e;
+-      }
+-      is(battery[k], backup, "Setting battery " + k + " preference without spoofing enabled should fail");
+-    }
+-
+-    Debugging.fake = true;
+-
+-    // reload again to get the fake one
+-    GetBattery().then(function(battery) {
+-      battery.charging = true;
+-      battery.chargingTime = 100;
+-      battery.level = 0.5;
+-      ok(battery.charging, "Test for charging setter");
+-      is(battery.chargingTime, 100, "Test for chargingTime setter");
+-      is(battery.level, 0.5, "Test for level setter");
+-
+-      battery.charging = false;
+-      battery.dischargingTime = 50;
+-      battery.level = 0.7;
+-      ok(!battery.charging, "Test for charging setter");
+-      is(battery.dischargingTime, 50, "Test for dischargingTime setter");
+-      is(battery.level, 0.7, "Test for level setter");
+-
+-      // Resetting the value to make the test run successful
+-      // for multiple runs in same browser session.
+-      Debugging.fake = false;
+-      finish();
+-    });
+-  });
+-}
+diff --git a/tools/lint/eslint/modules.json b/tools/lint/eslint/modules.json
+--- a/tools/lint/eslint/modules.json
++++ b/tools/lint/eslint/modules.json
+@@ -8,17 +8,16 @@
+   "addonutils.js": ["AddonUtils"],
+   "ajv-4.1.1.js": ["Ajv"],
+   "AlertsHelper.jsm": [],
+   "AppData.jsm": ["makeFakeAppDir"],
+   "AppInfo.jsm": ["newAppInfo", "getAppInfo", "updateAppInfo"],
+   "async.js": ["Async"],
+   "AsyncSpellCheckTestHelper.jsm": ["onSpellCheck"],
+   "AutoMigrate.jsm": ["AutoMigrate"],
+-  "Battery.jsm": ["GetBattery", "Battery"],
+   "blocklist-clients.js": ["AddonBlocklistClient", "GfxBlocklistClient", "OneCRLBlocklistClient", "PluginBlocklistClient"],
+   "blocklist-updater.js": ["checkVersions", "addTestBlocklistClient"],
+   "bogus_element_type.jsm": [],
+   "bookmark_repair.js": ["BookmarkRepairRequestor", "BookmarkRepairResponder"],
+   "bookmark_validator.js": ["BookmarkValidator", "BookmarkProblemData"],
+   "bookmarks.js": ["BookmarksEngine", "PlacesItem", "Bookmark", "BookmarkFolder", "BookmarkQuery", "Livemark", "BookmarkSeparator", "BufferedBookmarksEngine"],
+   "bookmarks.jsm": ["PlacesItem", "Bookmark", "Separator", "Livemark", "BookmarkFolder", "DumpBookmarks"],
+   "BootstrapMonitor.jsm": ["monitor"],

+ 49 - 0
rel-257/ian/patches/1362858-1partial-56a1.patch

@@ -0,0 +1,49 @@
+# HG changeset patch
+# User Evelyn Hung <jj.evelyn@gmail.com>
+# Date 1497258988 -28800
+# Node ID eaf99ba3813aa82632262ba4fc0438a7e2574af6
+# Parent  2cba736ec8d443921b3bb16ceb36dbd1b3efe8ac
+Bug 1362858 - Part 1: make word boundary check more consistent.r=Ehsan
+
+We use ClassifyCharacter for detecting all possibilities of word
+boudaries when building mRealWords but not when building soft text.
+This inconsistency leads us repeatedly checking the same set of words
+in some cases.
+
+diff --git a/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp b/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
+--- a/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
++++ b/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
+@@ -580,21 +580,30 @@ static inline bool IsBRElement(nsINode* 
+  */
+ static bool TextNodeContainsDOMWordSeparator(nsINode* aNode,
+                                              int32_t aBeforeOffset,
+                                              int32_t* aSeparatorOffset) {
+   // aNode is actually an nsIContent, since it's eTEXT
+   nsIContent* content = static_cast<nsIContent*>(aNode);
+   const nsTextFragment* textFragment = content->GetText();
+   NS_ASSERTION(textFragment, "Where is our text?");
+-  for (int32_t i = std::min(aBeforeOffset, int32_t(textFragment->GetLength())) - 1; i >= 0; --i) {
+-    if (IsDOMWordSeparator(textFragment->CharAt(i))) {
++  nsString text;
++  int32_t end = std::min(aBeforeOffset, int32_t(textFragment->GetLength()));
++  bool ok = textFragment->AppendTo(text, 0, end, mozilla::fallible);
++  if(!ok)
++    return false;
++
++  WordSplitState state(nullptr, text, 0, end);
++  for (int32_t i = end - 1; i >= 0; --i) {
++    if (IsDOMWordSeparator(textFragment->CharAt(i)) ||
++        state.ClassifyCharacter(i, true) == CHAR_CLASS_SEPARATOR) {
+       // Be greedy, find as many separators as we can
+       for (int32_t j = i - 1; j >= 0; --j) {
+-        if (IsDOMWordSeparator(textFragment->CharAt(j))) {
++        if (IsDOMWordSeparator(textFragment->CharAt(j)) ||
++            state.ClassifyCharacter(j, true) == CHAR_CLASS_SEPARATOR) {
+           i = j;
+         } else {
+           break;
+         }
+       }
+       *aSeparatorOffset = i;
+       return true;
+     }

File diff suppressed because it is too large
+ 90558 - 0
rel-257/ian/patches/1371485-1-63a1.patch


+ 6775 - 0
rel-257/ian/patches/1371485-2-63a1.patch

@@ -0,0 +1,6775 @@
+# HG changeset patch
+# User Dan Minor <dminor@mozilla.com>
+# Date 1529693837 14400
+# Node ID a30385fdddc3fa7d0847dc8d19a5c3a768e5be71
+# Parent  bd25e1381dc0662d15a5127f838840384c245958
+Bug 1371485 - Remove unnecessary gyp files from webrtc; r=chmanchester
+
+Tags: #secure-revision
+
+Bug #: 1371485
+
+Differential Revision: https://phabricator.services.mozilla.com/D1799
+
+diff --git a/media/webrtc/trunk/build/all.gyp b/media/webrtc/trunk/build/all.gyp
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/all.gyp
++++ /dev/null
+@@ -1,716 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-{
+-  'targets': [
+-    {
+-      'target_name': 'All',
+-      'type': 'none',
+-      'xcode_create_dependents_test_runner': 1,
+-      'dependencies': [
+-        'some.gyp:*',
+-        '../base/base.gyp:*',
+-        '../content/content.gyp:*',
+-        '../crypto/crypto.gyp:*',
+-        '../media/media.gyp:*',
+-        '../net/net.gyp:*',
+-        '../sdch/sdch.gyp:*',
+-        '../sql/sql.gyp:*',
+-        '../testing/gmock.gyp:*',
+-        '../testing/gtest.gyp:*',
+-        '../third_party/bzip2/bzip2.gyp:*',
+-        '../third_party/libxml/libxml.gyp:*',
+-        '../third_party/sqlite/sqlite.gyp:*',
+-        '../third_party/zlib/zlib.gyp:*',
+-        '../ui/ui.gyp:*',
+-        '../webkit/support/webkit_support.gyp:*',
+-        'temp_gyp/googleurl.gyp:*',
+-      ],
+-      'conditions': [
+-        ['OS!="ios"', {
+-          'dependencies': [
+-            '../cc/cc_tests.gyp:*',
+-            '../chrome/chrome.gyp:*',
+-            '../gpu/gpu.gyp:*',
+-            '../gpu/tools/tools.gyp:*',
+-            '../ipc/ipc.gyp:*',
+-            '../jingle/jingle.gyp:*',
+-            '../ppapi/ppapi.gyp:*',
+-            '../ppapi/ppapi_internal.gyp:*',
+-            '../printing/printing.gyp:*',
+-            '../skia/skia.gyp:*',
+-            '../sync/sync.gyp:*',
+-            '../third_party/cacheinvalidation/cacheinvalidation.gyp:*',
+-            '../third_party/cld/cld.gyp:*',
+-            '../third_party/codesighs/codesighs.gyp:*',
+-            '../third_party/ffmpeg/ffmpeg.gyp:*',
+-            '../third_party/iccjpeg/iccjpeg.gyp:*',
+-            '../third_party/libpng/libpng.gyp:*',
+-            '../third_party/libusb/libusb.gyp:*',
+-            '../third_party/libwebp/libwebp.gyp:*',
+-            '../third_party/libxslt/libxslt.gyp:*',
+-            '../third_party/lzma_sdk/lzma_sdk.gyp:*',
+-            '../third_party/mesa/mesa.gyp:*',
+-            '../third_party/modp_b64/modp_b64.gyp:*',
+-            '../third_party/npapi/npapi.gyp:*',
+-            '../third_party/ots/ots.gyp:*',
+-            '../third_party/qcms/qcms.gyp:*',
+-            '../third_party/re2/re2.gyp:re2',
+-            '../third_party/WebKit/Source/WebKit/chromium/All.gyp:*',
+-            '../v8/tools/gyp/v8.gyp:*',
+-            '../webkit/compositor_bindings/compositor_bindings_tests.gyp:*',
+-            '../webkit/webkit.gyp:*',
+-            '<(libjpeg_gyp_path):*',
+-          ],
+-        }],
+-        ['os_posix==1 and OS!="android" and OS!="ios"', {
+-          'dependencies': [
+-            '../third_party/yasm/yasm.gyp:*#host',
+-          ],
+-        }],
+-        ['OS=="mac" or OS=="ios" or OS=="win"', {
+-          'dependencies': [
+-            '../third_party/nss/nss.gyp:*',
+-           ],
+-        }],
+-        ['OS=="win" or OS=="ios" or OS=="linux"', {
+-          'dependencies': [
+-            '../breakpad/breakpad.gyp:*',
+-           ],
+-        }],
+-        ['OS=="mac"', {
+-          'dependencies': [
+-            '../third_party/ocmock/ocmock.gyp:*',
+-          ],
+-        }],
+-        ['OS=="linux"', {
+-          'dependencies': [
+-            '../courgette/courgette.gyp:*',
+-            '../dbus/dbus.gyp:*',
+-            '../sandbox/sandbox.gyp:*',
+-          ],
+-          'conditions': [
+-            ['branding=="Chrome"', {
+-              'dependencies': [
+-                '../chrome/chrome.gyp:linux_packages_<(channel)',
+-              ],
+-            }],
+-            ['chromeos==0', {
+-              'dependencies': [
+-                '../third_party/cros_dbus_cplusplus/cros_dbus_cplusplus.gyp:*',
+-              ],
+-            }],
+-          ],
+-        }],
+-        ['(toolkit_uses_gtk==1) and (build_with_mozilla==0)', {
+-          'dependencies': [
+-            '../tools/gtk_clipboard_dump/gtk_clipboard_dump.gyp:*',
+-            '../tools/xdisplaycheck/xdisplaycheck.gyp:*',
+-          ],
+-        }],
+-        ['OS=="win"', {
+-          'conditions': [
+-            ['win_use_allocator_shim==1', {
+-              'dependencies': [
+-                '../base/allocator/allocator.gyp:*',
+-              ],
+-            }],
+-          ],
+-          'dependencies': [
+-            '../chrome_frame/chrome_frame.gyp:*',
+-            '../cloud_print/cloud_print.gyp:*',
+-            '../courgette/courgette.gyp:*',
+-            '../rlz/rlz.gyp:*',
+-            '../sandbox/sandbox.gyp:*',
+-            '../third_party/angle/src/build_angle.gyp:*',
+-            '../third_party/bsdiff/bsdiff.gyp:*',
+-            '../third_party/bspatch/bspatch.gyp:*',
+-            '../third_party/gles2_book/gles2_book.gyp:*',
+-            '../tools/memory_watcher/memory_watcher.gyp:*',
+-          ],
+-        }, {
+-          'dependencies': [
+-            '../third_party/libevent/libevent.gyp:*',
+-          ],
+-        }],
+-        ['toolkit_views==1', {
+-          'dependencies': [
+-            '../ui/views/controls/webview/webview.gyp:*',
+-            '../ui/views/views.gyp:*',
+-          ],
+-        }],
+-        ['use_aura==1', {
+-          'dependencies': [
+-            '../ash/ash.gyp:*',
+-            '../ui/aura/aura.gyp:*',
+-            '../ui/oak/oak.gyp:*',
+-          ],
+-        }],
+-        ['remoting==1', {
+-          'dependencies': [
+-            '../remoting/remoting.gyp:*',
+-          ],
+-        }],
+-        ['use_openssl==0', {
+-          'dependencies': [
+-            '../net/third_party/nss/ssl.gyp:*',
+-          ],
+-        }],
+-      ],
+-    }, # target_name: All
+-    {
+-      'target_name': 'All_syzygy',
+-      'type': 'none',
+-      'conditions': [
+-        ['OS=="win" and fastbuild==0', {
+-            'dependencies': [
+-              '../chrome/installer/mini_installer_syzygy.gyp:*',
+-            ],
+-          },
+-        ],
+-      ],
+-    }, # target_name: All_syzygy
+-    {
+-      'target_name': 'chromium_builder_tests',
+-      'type': 'none',
+-      'dependencies': [
+-        '../base/base.gyp:base_unittests',
+-        '../crypto/crypto.gyp:crypto_unittests',
+-        '../media/media.gyp:media_unittests',
+-        '../net/net.gyp:net_unittests',
+-        '../sql/sql.gyp:sql_unittests',
+-        '../ui/ui.gyp:ui_unittests',
+-        'temp_gyp/googleurl.gyp:googleurl_unittests',
+-      ],
+-      'conditions': [
+-        ['OS!="ios"', {
+-          'dependencies': [
+-            '../cc/cc_tests.gyp:cc_unittests',
+-            '../chrome/chrome.gyp:browser_tests',
+-            '../chrome/chrome.gyp:interactive_ui_tests',
+-            '../chrome/chrome.gyp:safe_browsing_tests',
+-            '../chrome/chrome.gyp:sync_integration_tests',
+-            '../chrome/chrome.gyp:unit_tests',
+-            '../cloud_print/cloud_print.gyp:cloud_print_unittests',
+-            '../content/content.gyp:content_browsertests',
+-            '../content/content.gyp:content_unittests',
+-            '../gpu/gpu.gyp:gpu_unittests',
+-            '../gpu/gles2_conform_support/gles2_conform_support.gyp:gles2_conform_support',
+-            '../ipc/ipc.gyp:ipc_tests',
+-            '../jingle/jingle.gyp:jingle_unittests',
+-            '../ppapi/ppapi_internal.gyp:ppapi_unittests',
+-            '../printing/printing.gyp:printing_unittests',
+-            '../remoting/remoting.gyp:remoting_unittests',
+-            '../sync/sync.gyp:sync_unit_tests',
+-            '../third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_unittests',
+-            '../third_party/libphonenumber/libphonenumber.gyp:libphonenumber_unittests',
+-            '../webkit/compositor_bindings/compositor_bindings_tests.gyp:webkit_compositor_bindings_unittests',
+-          ],
+-        }],
+-        ['OS=="win"', {
+-          'dependencies': [
+-            '../chrome/chrome.gyp:installer_util_unittests',
+-            '../chrome/chrome.gyp:mini_installer_test',
+-            # mini_installer_tests depends on mini_installer. This should be
+-            # defined in installer.gyp.
+-            '../chrome/installer/mini_installer.gyp:mini_installer',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_net_tests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_perftests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_reliability_tests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_tests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_unittests',
+-            '../chrome_frame/chrome_frame.gyp:npchrome_frame',
+-            '../courgette/courgette.gyp:courgette_unittests',
+-            '../sandbox/sandbox.gyp:sbox_integration_tests',
+-            '../sandbox/sandbox.gyp:sbox_unittests',
+-            '../sandbox/sandbox.gyp:sbox_validation_tests',
+-            '../webkit/webkit.gyp:pull_in_copy_TestNetscapePlugIn',
+-            '../ui/views/views.gyp:views_unittests',
+-            '../webkit/webkit.gyp:test_shell_common',
+-           ],
+-        }],
+-        ['OS=="linux"', {
+-          'dependencies': [
+-            '../sandbox/sandbox.gyp:sandbox_linux_unittests',
+-          ],
+-        }],
+-      ],
+-    }, # target_name: chromium_builder_tests
+-    {
+-      'target_name': 'chromium_2010_builder_tests',
+-      'type': 'none',
+-      'dependencies': [
+-        'chromium_builder_tests',
+-      ],
+-    }, # target_name: chromium_2010_builder_tests
+-  ],
+-  'conditions': [
+-    ['OS!="ios"', {
+-      'targets': [
+-        {
+-          'target_name': 'chromium_builder_nacl_win_integration',
+-          'type': 'none',
+-          'dependencies': [
+-            'chromium_builder_qa', # needed for pyauto
+-            'chromium_builder_tests',
+-          ],
+-        }, # target_name: chromium_builder_nacl_win_integration
+-        {
+-          'target_name': 'chromium_builder_perf',
+-          'type': 'none',
+-          'dependencies': [
+-            'chromium_builder_qa', # needed for pyauto
+-            '../chrome/chrome.gyp:performance_browser_tests',
+-            '../chrome/chrome.gyp:performance_ui_tests',
+-            '../chrome/chrome.gyp:sync_performance_tests',
+-          ],
+-        }, # target_name: chromium_builder_perf
+-        {
+-          'target_name': 'chromium_gpu_builder',
+-          'type': 'none',
+-          'dependencies': [
+-            '../chrome/chrome.gyp:gpu_tests',
+-            '../chrome/chrome.gyp:performance_browser_tests',
+-            '../chrome/chrome.gyp:performance_ui_tests',
+-            '../gpu/gpu.gyp:gl_tests',
+-          ],
+-          'conditions': [
+-            ['internal_gles2_conform_tests', {
+-              'dependencies': [
+-                '../gpu/gles2_conform_test/gles2_conform_test.gyp:gles2_conform_test',
+-              ],
+-            }], # internal_gles2_conform
+-          ],
+-        }, # target_name: chromium_gpu_builder
+-        {
+-          'target_name': 'chromium_gpu_debug_builder',
+-          'type': 'none',
+-          'dependencies': [
+-            '../chrome/chrome.gyp:gpu_tests',
+-            '../gpu/gpu.gyp:gl_tests',
+-          ],
+-          'conditions': [
+-            ['internal_gles2_conform_tests', {
+-              'dependencies': [
+-                '../gpu/gles2_conform_test/gles2_conform_test.gyp:gles2_conform_test',
+-              ],
+-            }], # internal_gles2_conform
+-          ],
+-        }, # target_name: chromium_gpu_debug_builder
+-        {
+-          'target_name': 'chromium_builder_qa',
+-          'type': 'none',
+-          'dependencies': [
+-            '../chrome/chrome.gyp:chromedriver',
+-            # Dependencies of pyauto_functional tests.
+-            '../remoting/remoting.gyp:remoting_webapp',
+-          ],
+-# not needed for Mozilla
+-#          'conditions': [
+-#            # If you change this condition, make sure you also change it
+-#            # in chrome_tests.gypi
+-#            ['enable_automation==1 and (OS=="mac" or OS=="win" or (os_posix==1 and target_arch==python_arch))', {
+-#              'dependencies': [
+-#                '../chrome/chrome.gyp:pyautolib',
+-#              ],
+-#            }],
+-            ['OS=="mac"', {
+-              'dependencies': [
+-                '../remoting/remoting.gyp:remoting_me2me_host_archive',
+-              ],
+-            }],
+-            ['OS=="win" and component != "shared_library" and wix_exists == "True" and sas_dll_exists == "True"', {
+-              'dependencies': [
+-                '../remoting/remoting.gyp:remoting_host_installation',
+-              ],
+-            }],
+-          ],
+-        }, # target_name: chromium_builder_qa
+-        {
+-          'target_name': 'chromium_builder_perf_av',
+-          'type': 'none',
+-          'dependencies': [
+-            'chromium_builder_qa',  # needed for perf pyauto tests
+-            '../webkit/webkit.gyp:pull_in_DumpRenderTree',  # to run layout tests
+-          ],
+-        },  # target_name: chromium_builder_perf_av
+-      ],  # targets
+-    }],
+-    ['OS=="mac"', {
+-      'targets': [
+-        {
+-          # Target to build everything plus the dmg.  We don't put the dmg
+-          # in the All target because developers really don't need it.
+-          'target_name': 'all_and_dmg',
+-          'type': 'none',
+-          'dependencies': [
+-            'All',
+-            '../chrome/chrome.gyp:build_app_dmg',
+-          ],
+-        },
+-        # These targets are here so the build bots can use them to build
+-        # subsets of a full tree for faster cycle times.
+-        {
+-          'target_name': 'chromium_builder_dbg',
+-          'type': 'none',
+-          'dependencies': [
+-            '../cc/cc_tests.gyp:cc_unittests',
+-            '../chrome/chrome.gyp:browser_tests',
+-            '../chrome/chrome.gyp:interactive_ui_tests',
+-            '../chrome/chrome.gyp:safe_browsing_tests',
+-            '../chrome/chrome.gyp:sync_integration_tests',
+-            '../chrome/chrome.gyp:unit_tests',
+-            '../cloud_print/cloud_print.gyp:cloud_print_unittests',
+-            '../content/content.gyp:content_browsertests',
+-            '../content/content.gyp:content_unittests',
+-            '../ui/ui.gyp:ui_unittests',
+-            '../gpu/gpu.gyp:gpu_unittests',
+-            '../ipc/ipc.gyp:ipc_tests',
+-            '../jingle/jingle.gyp:jingle_unittests',
+-            '../media/media.gyp:media_unittests',
+-            '../ppapi/ppapi_internal.gyp:ppapi_unittests',
+-            '../printing/printing.gyp:printing_unittests',
+-            '../remoting/remoting.gyp:remoting_unittests',
+-            '../rlz/rlz.gyp:*',
+-            '../sql/sql.gyp:sql_unittests',
+-            '../sync/sync.gyp:sync_unit_tests',
+-            '../third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_unittests',
+-            '../third_party/libphonenumber/libphonenumber.gyp:libphonenumber_unittests',
+-            '../webkit/compositor_bindings/compositor_bindings_tests.gyp:webkit_compositor_bindings_unittests',
+-            'temp_gyp/googleurl.gyp:googleurl_unittests',
+-          ],
+-        },
+-        {
+-          'target_name': 'chromium_builder_rel',
+-          'type': 'none',
+-          'dependencies': [
+-            '../cc/cc_tests.gyp:cc_unittests',
+-            '../chrome/chrome.gyp:browser_tests',
+-            '../chrome/chrome.gyp:performance_browser_tests',
+-            '../chrome/chrome.gyp:performance_ui_tests',
+-            '../chrome/chrome.gyp:safe_browsing_tests',
+-            '../chrome/chrome.gyp:sync_integration_tests',
+-            '../chrome/chrome.gyp:unit_tests',
+-            '../cloud_print/cloud_print.gyp:cloud_print_unittests',
+-            '../content/content.gyp:content_browsertests',
+-            '../content/content.gyp:content_unittests',
+-            '../ui/ui.gyp:ui_unittests',
+-            '../gpu/gpu.gyp:gpu_unittests',
+-            '../ipc/ipc.gyp:ipc_tests',
+-            '../jingle/jingle.gyp:jingle_unittests',
+-            '../media/media.gyp:media_unittests',
+-            '../ppapi/ppapi_internal.gyp:ppapi_unittests',
+-            '../printing/printing.gyp:printing_unittests',
+-            '../remoting/remoting.gyp:remoting_unittests',
+-            '../sql/sql.gyp:sql_unittests',
+-            '../sync/sync.gyp:sync_unit_tests',
+-            '../third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_unittests',
+-            '../third_party/libphonenumber/libphonenumber.gyp:libphonenumber_unittests',
+-            '../webkit/compositor_bindings/compositor_bindings_tests.gyp:webkit_compositor_bindings_unittests',
+-            'temp_gyp/googleurl.gyp:googleurl_unittests',
+-          ],
+-        },
+-        {
+-          'target_name': 'chromium_builder_dbg_tsan_mac',
+-          'type': 'none',
+-          'dependencies': [
+-            '../base/base.gyp:base_unittests',
+-            '../cloud_print/cloud_print.gyp:cloud_print_unittests',
+-            '../crypto/crypto.gyp:crypto_unittests',
+-            'temp_gyp/googleurl.gyp:googleurl_unittests',
+-            '../net/net.gyp:net_unittests',
+-            '../ipc/ipc.gyp:ipc_tests',
+-            '../jingle/jingle.gyp:jingle_unittests',
+-            '../media/media.gyp:media_unittests',
+-            '../printing/printing.gyp:printing_unittests',
+-            '../remoting/remoting.gyp:remoting_unittests',
+-            '../third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_unittests',
+-            '../third_party/libphonenumber/libphonenumber.gyp:libphonenumber_unittests',
+-          ],
+-        },
+-        {
+-          'target_name': 'chromium_builder_asan_mac',
+-          'type': 'none',
+-          'dependencies': [
+-            '../chrome/chrome.gyp:chrome',
+-            '../net/net.gyp:dns_fuzz_stub',
+-            '../webkit/webkit.gyp:pull_in_DumpRenderTree',
+-          ],
+-        },
+-        {
+-          'target_name': 'chromium_builder_dbg_valgrind_mac',
+-          'type': 'none',
+-          'dependencies': [
+-            '../base/base.gyp:base_unittests',
+-            '../cloud_print/cloud_print.gyp:cloud_print_unittests',
+-            '../crypto/crypto.gyp:crypto_unittests',
+-            '../ipc/ipc.gyp:ipc_tests',
+-            '../media/media.gyp:media_unittests',
+-            '../net/net.gyp:net_unittests',
+-            '../printing/printing.gyp:printing_unittests',
+-            '../remoting/remoting.gyp:remoting_unittests',
+-            '../chrome/chrome.gyp:safe_browsing_tests',
+-            '../chrome/chrome.gyp:unit_tests',
+-            '../content/content.gyp:content_unittests',
+-            '../ui/ui.gyp:ui_unittests',
+-            '../jingle/jingle.gyp:jingle_unittests',
+-            '../sql/sql.gyp:sql_unittests',
+-            '../sync/sync.gyp:sync_unit_tests',
+-            '../third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_unittests',
+-            '../third_party/libphonenumber/libphonenumber.gyp:libphonenumber_unittests',
+-            'temp_gyp/googleurl.gyp:googleurl_unittests',
+-          ],
+-        },
+-      ],  # targets
+-    }], # OS="mac"
+-    ['OS=="win"', {
+-      'targets': [
+-        # These targets are here so the build bots can use them to build
+-        # subsets of a full tree for faster cycle times.
+-        {
+-          'target_name': 'chromium_builder',
+-          'type': 'none',
+-          'dependencies': [
+-            '../cc/cc_tests.gyp:cc_unittests',
+-            '../chrome/chrome.gyp:browser_tests',
+-            '../chrome/chrome.gyp:installer_util_unittests',
+-            '../chrome/chrome.gyp:interactive_ui_tests',
+-            '../chrome/chrome.gyp:mini_installer_test',
+-            '../chrome/chrome.gyp:performance_browser_tests',
+-            '../chrome/chrome.gyp:performance_ui_tests',
+-            '../chrome/chrome.gyp:safe_browsing_tests',
+-            '../chrome/chrome.gyp:sync_integration_tests',
+-            '../chrome/chrome.gyp:unit_tests',
+-            '../cloud_print/cloud_print.gyp:cloud_print_unittests',
+-            '../content/content.gyp:content_browsertests',
+-            '../content/content.gyp:content_unittests',
+-            # mini_installer_tests depends on mini_installer. This should be
+-            # defined in installer.gyp.
+-            '../chrome/installer/mini_installer.gyp:mini_installer',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_net_tests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_perftests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_reliability_tests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_tests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_unittests',
+-            '../chrome_frame/chrome_frame.gyp:npchrome_frame',
+-            '../courgette/courgette.gyp:courgette_unittests',
+-            '../ui/ui.gyp:ui_unittests',
+-            '../gpu/gpu.gyp:gpu_unittests',
+-            '../ipc/ipc.gyp:ipc_tests',
+-            '../jingle/jingle.gyp:jingle_unittests',
+-            '../media/media.gyp:media_unittests',
+-            '../ppapi/ppapi_internal.gyp:ppapi_unittests',
+-            '../printing/printing.gyp:printing_unittests',
+-            '../remoting/remoting.gyp:remoting_unittests',
+-            '../sql/sql.gyp:sql_unittests',
+-            '../sync/sync.gyp:sync_unit_tests',
+-            '../third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_unittests',
+-            '../third_party/libphonenumber/libphonenumber.gyp:libphonenumber_unittests',
+-            '../ui/views/views.gyp:views_unittests',
+-            '../webkit/compositor_bindings/compositor_bindings_tests.gyp:webkit_compositor_bindings_unittests',
+-            '../webkit/webkit.gyp:pull_in_copy_TestNetscapePlugIn',
+-            'temp_gyp/googleurl.gyp:googleurl_unittests',
+-          ],
+-        },
+-        {
+-          'target_name': 'chromium_builder_win_cf',
+-          'type': 'none',
+-          'dependencies': [
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_net_tests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_perftests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_reliability_tests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_tests',
+-            '../chrome_frame/chrome_frame.gyp:chrome_frame_unittests',
+-            '../chrome_frame/chrome_frame.gyp:npchrome_frame',
+-          ],
+-        },
+-        {
+-          'target_name': 'chromium_builder_dbg_tsan_win',
+-          'type': 'none',
+-          'dependencies': [
+-            '../base/base.gyp:base_unittests',
+-            '../cloud_print/cloud_print.gyp:cloud_print_unittests',
+-            '../content/content.gyp:content_unittests',
+-            '../crypto/crypto.gyp:crypto_unittests',
+-            '../ipc/ipc.gyp:ipc_tests',
+-            '../jingle/jingle.gyp:jingle_unittests',
+-            '../media/media.gyp:media_unittests',
+-            '../net/net.gyp:net_unittests',
+-            '../printing/printing.gyp:printing_unittests',
+-            '../remoting/remoting.gyp:remoting_unittests',
+-            '../sql/sql.gyp:sql_unittests',
+-            '../third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_unittests',
+-            '../third_party/libphonenumber/libphonenumber.gyp:libphonenumber_unittests',
+-            'temp_gyp/googleurl.gyp:googleurl_unittests',
+-          ],
+-        },
+-        {
+-          'target_name': 'chromium_builder_dbg_drmemory_win',
+-          'type': 'none',
+-          'dependencies': [
+-            '../base/base.gyp:base_unittests',
+-            '../chrome/chrome.gyp:unit_tests',
+-            '../cloud_print/cloud_print.gyp:cloud_print_unittests',
+-            '../content/content.gyp:content_unittests',
+-            '../crypto/crypto.gyp:crypto_unittests',
+-            '../ipc/ipc.gyp:ipc_tests',
+-            '../jingle/jingle.gyp:jingle_unittests',
+-            '../media/media.gyp:media_unittests',
+-            '../net/net.gyp:net_unittests',
+-            '../printing/printing.gyp:printing_unittests',
+-            '../remoting/remoting.gyp:remoting_unittests',
+-            '../sql/sql.gyp:sql_unittests',
+-            '../third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_unittests',
+-            '../third_party/libphonenumber/libphonenumber.gyp:libphonenumber_unittests',
+-            'temp_gyp/googleurl.gyp:googleurl_unittests',
+-          ],
+-        },
+-        {
+-          'target_name': 'webkit_builder_win',
+-          'type': 'none',
+-          'dependencies': [
+-            '../webkit/webkit.gyp:test_shell',
+-            '../webkit/webkit.gyp:test_shell_tests',
+-            '../webkit/webkit.gyp:pull_in_webkit_unit_tests',
+-            '../webkit/webkit.gyp:pull_in_DumpRenderTree',
+-          ],
+-        },
+-        {
+-          'target_name': 'chromium_builder_qa_nacl_win64',
+-          'type': 'none',
+-          'dependencies': [
+-            'chromium_builder_qa', # needed for pyauto
+-            '../chrome/chrome.gyp:chrome_nacl_win64',
+-          ],
+-        }, # target_name: chromium_builder_qa_nacl_win64
+-      ],  # targets
+-      'conditions': [
+-        ['branding=="Chrome"', {
+-          'targets': [
+-            {
+-              'target_name': 'chrome_official_builder',
+-              'type': 'none',
+-              'dependencies': [
+-                '../chrome/chrome.gyp:chromedriver',
+-                '../chrome/chrome.gyp:crash_service',
+-                '../chrome/chrome.gyp:crash_service_win64',
+-                '../chrome/chrome.gyp:performance_ui_tests',
+-                '../chrome/chrome.gyp:policy_templates',
+-                '../chrome/chrome.gyp:pyautolib',
+-                '../chrome/chrome.gyp:reliability_tests',
+-                '../chrome/chrome.gyp:automated_ui_tests',
+-                '../chrome/installer/mini_installer.gyp:mini_installer',
+-                '../chrome_frame/chrome_frame.gyp:npchrome_frame',
+-                '../courgette/courgette.gyp:courgette',
+-                '../courgette/courgette.gyp:courgette64',
+-                '../cloud_print/cloud_print.gyp:cloud_print',
+-                '../remoting/remoting.gyp:remoting_webapp',
+-                '../third_party/adobe/flash/flash_player.gyp:flash_player',
+-                '../third_party/widevine/cdm/widevine_cdm.gyp:widevinecdmplugin',
+-              ],
+-              'conditions': [
+-                ['internal_pdf', {
+-                  'dependencies': [
+-                    '../pdf/pdf.gyp:pdf',
+-                  ],
+-                }], # internal_pdf
+-                ['component != "shared_library" and wix_exists == "True" and \
+-                    sas_dll_exists == "True"', {
+-                  'dependencies': [
+-                    '../remoting/remoting.gyp:remoting_host_installation',
+-                  ],
+-                }], # component != "shared_library"
+-              ]
+-            },
+-          ], # targets
+-        }], # branding=="Chrome"
+-       ], # conditions
+-    }], # OS="win"
+-    ['use_aura==1', {
+-      'targets': [
+-        {
+-          'target_name': 'aura_builder',
+-          'type': 'none',
+-          'dependencies': [
+-            '../cc/cc_tests.gyp:cc_unittests',
+-            '../chrome/chrome.gyp:browser_tests',
+-            '../chrome/chrome.gyp:chrome',
+-            '../chrome/chrome.gyp:interactive_ui_tests',
+-            '../chrome/chrome.gyp:unit_tests',
+-            '../content/content.gyp:content_browsertests',
+-            '../content/content.gyp:content_unittests',
+-            '../ppapi/ppapi_internal.gyp:ppapi_unittests',
+-            '../remoting/remoting.gyp:remoting_unittests',
+-            '../ui/aura/aura.gyp:*',
+-            '../ui/compositor/compositor.gyp:*',
+-            '../ui/ui.gyp:ui_unittests',
+-            '../ui/views/views.gyp:views',
+-            '../ui/views/views.gyp:views_unittests',
+-            '../webkit/compositor_bindings/compositor_bindings_tests.gyp:webkit_compositor_bindings_unittests',
+-            '../webkit/webkit.gyp:pull_in_webkit_unit_tests',
+-          ],
+-          'conditions': [
+-            ['OS=="win"', {
+-              # Remove this when we have the real compositor.
+-              'copies': [
+-                {
+-                  'destination': '<(PRODUCT_DIR)',
+-                  'files': ['../third_party/directxsdk/files/dlls/D3DX10d_43.dll']
+-                },
+-              ],
+-              'dependencies': [
+-                '../content/content.gyp:content_unittests',
+-                '../chrome/chrome.gyp:crash_service',
+-                '../chrome/chrome.gyp:crash_service_win64',
+-              ],
+-            }],
+-            ['use_ash==1', {
+-              'dependencies': [
+-                '../ash/ash.gyp:ash_shell',
+-                '../ash/ash.gyp:ash_unittests',
+-              ],
+-            }],
+-            ['OS=="linux"', {
+-              # Tests that currently only work on Linux.
+-              'dependencies': [
+-                '../base/base.gyp:base_unittests',
+-                '../content/content.gyp:content_unittests',
+-                '../ipc/ipc.gyp:ipc_tests',
+-                '../sql/sql.gyp:sql_unittests',
+-                '../sync/sync.gyp:sync_unit_tests',
+-              ],
+-            }],
+-            ['OS=="mac"', {
+-              # Exclude dependencies that are not currently implemented.
+-              'dependencies!': [
+-                '../chrome/chrome.gyp:chrome',
+-                '../chrome/chrome.gyp:unit_tests',
+-                '../ui/views/views.gyp:views_unittests',
+-              ],
+-            }],
+-            ['chromeos==1', {
+-              'dependencies': [
+-                '../chromeos/chromeos.gyp:chromeos_unittests',
+-              ],
+-            }],
+-          ],
+-        },
+-      ],  # targets
+-    }], # "use_aura==1"
+-    ['test_isolation_mode != "noop"', {
+-      'targets': [
+-        {
+-          'target_name': 'chromium_swarm_tests',
+-          'type': 'none',
+-          'dependencies': [
+-            '../base/base.gyp:base_unittests_run',
+-            '../chrome/chrome.gyp:browser_tests_run',
+-            '../chrome/chrome.gyp:unit_tests_run',
+-            '../net/net.gyp:net_unittests_run',
+-          ],
+-        }, # target_name: chromium_swarm_tests
+-      ],
+-    }],
+-  ], # conditions
+-}
+diff --git a/media/webrtc/trunk/build/all_android.gyp b/media/webrtc/trunk/build/all_android.gyp
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/all_android.gyp
++++ /dev/null
+@@ -1,115 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This is all.gyp file for Android to prevent breakage in Android and other
+-# platform; It will be churning a lot in the short term and eventually be merged
+-# into all.gyp.
+-
+-{
+-  'variables': {
+-    # A hook that can be overridden in other repositories to add additional
+-    # compilation targets to 'All'
+-    'android_app_targets%': [],
+-  },
+-  'targets': [
+-    {
+-      'target_name': 'All',
+-      'type': 'none',
+-      'dependencies': [
+-        '../content/content.gyp:content_shell_apk',
+-        '<@(android_app_targets)',
+-        'android_builder_tests',
+-        '../android_webview/android_webview.gyp:android_webview_apk',
+-        '../chrome/chrome.gyp:chromium_testshell',
+-      ],
+-    }, # target_name: All
+-    {
+-      # The current list of tests for android.  This is temporary
+-      # until the full set supported.  If adding a new test here,
+-      # please also add it to build/android/run_tests.py, else the
+-      # test is not run.
+-      #
+-      # WARNING:
+-      # Do not add targets here without communicating the implications
+-      # on tryserver triggers and load.  Discuss with jrg please.
+-      'target_name': 'android_builder_tests',
+-      'type': 'none',
+-      'dependencies': [
+-        '../base/android/jni_generator/jni_generator.gyp:jni_generator_tests',
+-        '../base/base.gyp:base_unittests',
+-        '../cc/cc_tests.gyp:cc_unittests',
+-        '../chrome/chrome.gyp:unit_tests',
+-        '../content/content.gyp:content_shell_test_apk',
+-        '../content/content.gyp:content_unittests',
+-        '../gpu/gpu.gyp:gpu_unittests',
+-        '../ipc/ipc.gyp:ipc_tests',
+-        '../media/media.gyp:media_unittests',
+-        '../net/net.gyp:net_unittests',
+-        '../sql/sql.gyp:sql_unittests',
+-        '../sync/sync.gyp:sync_unit_tests',
+-        '../third_party/WebKit/Source/WebKit/chromium/All.gyp:*',
+-        '../tools/android/device_stats_monitor/device_stats_monitor.gyp:device_stats_monitor',
+-        '../tools/android/fake_dns/fake_dns.gyp:fake_dns',
+-        '../tools/android/forwarder2/forwarder.gyp:forwarder2',
+-        '../tools/android/md5sum/md5sum.gyp:md5sum',
+-        '../ui/ui.gyp:ui_unittests',
+-        # From here down: not added to run_tests.py yet.
+-        '../jingle/jingle.gyp:jingle_unittests',
+-        # Required by ui_unittests.
+-        # TODO(wangxianzhu): It'd better let ui_unittests depend on it, but
+-        # this would cause circular gyp dependency which needs refactoring the
+-        # gyps to resolve.
+-        '../chrome/chrome_resources.gyp:packed_resources',
+-      ],
+-      'conditions': [
+-        ['linux_breakpad==1', {
+-          'dependencies': [
+-            '../breakpad/breakpad.gyp:breakpad_unittests',
+-          ],
+-        }],
+-        ['"<(gtest_target_type)"=="shared_library"', {
+-          'dependencies': [
+-            # The first item is simply the template.  We add as a dep
+-            # to make sure it builds in ungenerated form.  TODO(jrg):
+-            # once stable, transition to a test-only (optional)
+-            # target.
+-            '../testing/android/native_test.gyp:native_test_apk',
+-            # Unit test bundles packaged as an apk.
+-            '../base/base.gyp:base_unittests_apk',
+-            '../cc/cc_tests.gyp:cc_unittests_apk',
+-            '../chrome/chrome.gyp:unit_tests_apk',
+-            '../content/content.gyp:content_unittests_apk',
+-            '../gpu/gpu.gyp:gpu_unittests_apk',
+-            '../ipc/ipc.gyp:ipc_tests_apk',
+-            '../media/media.gyp:media_unittests_apk',
+-            '../net/net.gyp:net_unittests_apk',
+-            '../sql/sql.gyp:sql_unittests_apk',
+-            '../sync/sync.gyp:sync_unit_tests_apk',
+-            '../ui/ui.gyp:ui_unittests_apk',
+-            '../android_webview/android_webview.gyp:android_webview_test_apk',
+-            '../chrome/chrome.gyp:chromium_testshell_test_apk',
+-          ],
+-        }],
+-      ],
+-    },
+-    {
+-      # Experimental / in-progress targets that are expected to fail
+-      # but we still try to compile them on bots (turning the stage
+-      # orange, not red).
+-      'target_name': 'android_experimental',
+-      'type': 'none',
+-      'dependencies': [
+-      ],
+-    },
+-    {
+-      # In-progress targets that are expected to fail and are NOT run
+-      # on any bot.
+-      'target_name': 'android_in_progress',
+-      'type': 'none',
+-      'dependencies': [
+-        '../content/content.gyp:content_browsertests',
+-      ],
+-    },
+-  ],  # targets
+-}
+diff --git a/media/webrtc/trunk/build/android/cpufeatures.gypi b/media/webrtc/trunk/build/android/cpufeatures.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/android/cpufeatures.gypi
++++ /dev/null
+@@ -1,6 +0,0 @@
+-# This Source Code Form is subject to the terms of the Mozilla Public
+-# 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/.
+-
+-#dummy gypi: contents should be discarded due to an enclosing 'conditions:' element.
+-{}
+diff --git a/media/webrtc/trunk/build/apk_test.gypi b/media/webrtc/trunk/build/apk_test.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/apk_test.gypi
++++ /dev/null
+@@ -1,75 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This file is meant to be included into a target to provide a rule
+-# to build APK based test suites.
+-#
+-# To use this, create a gyp target with the following form:
+-# {
+-#   'target_name': 'test_suite_name_apk',
+-#   'type': 'none',
+-#   'variables': {
+-#     'test_suite_name': 'test_suite_name',  # string
+-#     'input_shlib_path' : '/path/to/test_suite.so',  # string
+-#     'input_jars_paths': ['/path/to/test_suite.jar', ... ],  # list
+-#   },
+-#   'includes': ['path/to/this/gypi/file'],
+-# }
+-#
+-
+-{
+-  'variables': {
+-    'input_jars_paths': [
+-      # Needed by ChromeNativeTestActivity.java.
+-      '<(PRODUCT_DIR)/lib.java/chromium_base.jar',
+-    ],
+-  },
+-  'target_conditions': [
+-    ['_toolset == "target"', {
+-      'conditions': [
+-        ['OS == "android" and gtest_target_type == "shared_library"', {
+-          'actions': [{
+-            'action_name': 'apk_<(test_suite_name)',
+-            'message': 'Building <(test_suite_name) test apk.',
+-            'inputs': [
+-              '<(DEPTH)/testing/android/AndroidManifest.xml',
+-              '<(DEPTH)/testing/android/generate_native_test.py',
+-              '<(input_shlib_path)',
+-              '>@(input_jars_paths)',
+-            ],
+-            'outputs': [
+-              '<(PRODUCT_DIR)/<(test_suite_name)_apk/<(test_suite_name)-debug.apk',
+-            ],
+-            'action': [
+-              '<(DEPTH)/testing/android/generate_native_test.py',
+-              '--native_library',
+-              '<(input_shlib_path)',
+-              '--jars',
+-              '">@(input_jars_paths)"',
+-              '--output',
+-              '<(PRODUCT_DIR)/<(test_suite_name)_apk',
+-              '--strip-binary=<(android_strip)',
+-              '--app_abi',
+-              '<(android_app_abi)',
+-              '--ant-args',
+-              '-DPRODUCT_DIR=<(ant_build_out)',
+-              '--ant-args',
+-              '-DANDROID_SDK=<(android_sdk)',
+-              '--ant-args',
+-              '-DANDROID_SDK_ROOT=<(android_sdk_root)',
+-              '--ant-args',
+-              '-DANDROID_SDK_TOOLS=<(android_sdk_tools)',
+-              '--ant-args',
+-              '-DANDROID_SDK_VERSION=<(android_sdk_version)',
+-              '--ant-args',
+-              '-DANDROID_GDBSERVER=<(android_gdbserver)',
+-              '--ant-args',
+-              '-DCHROMIUM_SRC=<(ant_build_out)/../..',
+-            ],
+-          }],
+-        }],  # 'OS == "android" and gtest_target_type == "shared_library"
+-      ],  # conditions
+-    }],
+-  ],  # target_conditions
+-}
+diff --git a/media/webrtc/trunk/build/common.gypi b/media/webrtc/trunk/build/common.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/common.gypi
++++ /dev/null
+@@ -1,3668 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# IMPORTANT:
+-# Please don't directly include this file if you are building via gyp_chromium,
+-# since gyp_chromium is automatically forcing its inclusion.
+-{
+-  # Variables expected to be overriden on the GYP command line (-D) or by
+-  # ~/.gyp/include.gypi.
+-  'variables': {
+-    # Putting a variables dict inside another variables dict looks kind of
+-    # weird.  This is done so that 'host_arch', 'chromeos', etc are defined as
+-    # variables within the outer variables dict here.  This is necessary
+-    # to get these variables defined for the conditions within this variables
+-    # dict that operate on these variables.
+-    'variables': {
+-      'variables': {
+-        'variables': {
+-          'variables': {
+-            # Whether we're building a ChromeOS build.
+-            'chromeos%': 0,
+-
+-            # Whether or not we are using the Aura windowing framework.
+-            'use_aura%': 0,
+-
+-            # Whether or not we are building the Ash shell.
+-            'use_ash%': 0,
+-          },
+-          # Copy conditionally-set variables out one scope.
+-          'chromeos%': '<(chromeos)',
+-          'use_aura%': '<(use_aura)',
+-          'use_ash%': '<(use_ash)',
+-
+-          # Whether we are using Views Toolkit
+-          'toolkit_views%': 0,
+-
+-          # Use OpenSSL instead of NSS. Under development: see http://crbug.com/62803
+-          'use_openssl%': 0,
+-
+-          'use_ibus%': 0,
+-
+-          # Disable viewport meta tag by default.
+-          'enable_viewport%': 0,
+-
+-          # Enable HiDPI support.
+-          'enable_hidpi%': 0,
+-
+-          # Enable touch optimized art assets and metrics.
+-          'enable_touch_ui%': 0,
+-
+-          # Is this change part of the android upstream bringup?
+-          # Allows us to *temporarily* disable certain things for
+-          # staging.  Only set to 1 in a GYP_DEFINES.
+-          'android_upstream_bringup%': 0,
+-
+-          # Override buildtype to select the desired build flavor.
+-          # Dev - everyday build for development/testing
+-          # Official - release build (generally implies additional processing)
+-          # TODO(mmoss) Once 'buildtype' is fully supported (e.g. Windows gyp
+-          # conversion is done), some of the things which are now controlled by
+-          # 'branding', such as symbol generation, will need to be refactored
+-          # based on 'buildtype' (i.e. we don't care about saving symbols for
+-          # non-Official # builds).
+-          'buildtype%': 'Dev',
+-
+-          'conditions': [
+-            # ChromeOS implies ash.
+-            ['chromeos==1', {
+-              'use_ash%': 1,
+-              'use_aura%': 1,
+-            }],
+-
+-            # For now, Windows builds that |use_aura| should also imply using
+-            # ash. This rule should be removed for the future when Windows is
+-            # using the aura windows without the ash interface.
+-            ['use_aura==1 and OS=="win"', {
+-              'use_ash%': 1,
+-            }],
+-            ['use_ash==1', {
+-              'use_aura%': 1,
+-            }],
+-
+-            # A flag for BSD platforms
+-            ['OS=="dragonfly" or OS=="freebsd" or OS=="netbsd" or \
+-              OS=="openbsd"', {
+-              'os_bsd%': 1,
+-            }, {
+-              'os_bsd%': 0,
+-            }],
+-          ],
+-        },
+-        # Copy conditionally-set variables out one scope.
+-        'chromeos%': '<(chromeos)',
+-        'use_aura%': '<(use_aura)',
+-        'use_ash%': '<(use_ash)',
+-        'os_bsd%': '<(os_bsd)',
+-        'use_openssl%': '<(use_openssl)',
+-        'use_ibus%': '<(use_ibus)',
+-        'enable_viewport%': '<(enable_viewport)',
+-        'enable_hidpi%': '<(enable_hidpi)',
+-        'enable_touch_ui%': '<(enable_touch_ui)',
+-        'android_upstream_bringup%': '<(android_upstream_bringup)',
+-        'buildtype%': '<(buildtype)',
+-
+-        # Sets whether we're building with the Android SDK/NDK (and hence with
+-        # Ant, value 0), or as part of the Android system (and hence with the
+-        # Android build system, value 1).
+-        'android_build_type%': 0,
+-
+-        # Compute the architecture that we're building on.
+-        'conditions': [
+-          ['OS=="win" or OS=="ios"', {
+-            'host_arch%': 'ia32',
+-          }, {
+-            # This handles the Unix platforms for which there is some support.
+-            # Anything else gets passed through, which probably won't work very
+-            # well; such hosts should pass an explicit target_arch to gyp.
+-            'host_arch%':
+-              '<!(uname -m | sed -e "s/i.86/ia32/;s/x86_64/x64/;s/amd64/x64/;s/arm.*/arm/;s/i86pc/ia32/")',
+-          }],
+-
+-          # Set default value of toolkit_views based on OS.
+-          ['OS=="win" or chromeos==1 or use_aura==1', {
+-            'toolkit_views%': 1,
+-          }, {
+-            'toolkit_views%': 0,
+-          }],
+-
+-          # Set toolkit_uses_gtk for the Chromium browser on Linux.
+-          ['(OS=="linux" or OS=="solaris" or os_bsd==1) and use_aura==0', {
+-            'toolkit_uses_gtk%': 1,
+-          }, {
+-            'toolkit_uses_gtk%': 0,
+-          }],
+-
+-          # Enable HiDPI on Mac OS and Chrome OS.
+-          ['OS=="mac" or chromeos==1', {
+-            'enable_hidpi%': 1,
+-          }],
+-
+-          # Enable touch UI on Metro.
+-          ['OS=="win"', {
+-            'enable_touch_ui%': 1,
+-          }],
+-        ],
+-      },
+-
+-      # Copy conditionally-set variables out one scope.
+-      'chromeos%': '<(chromeos)',
+-      'host_arch%': '<(host_arch)',
+-      'toolkit_views%': '<(toolkit_views)',
+-      'toolkit_uses_gtk%': '<(toolkit_uses_gtk)',
+-      'use_aura%': '<(use_aura)',
+-      'use_ash%': '<(use_ash)',
+-      'os_bsd%': '<(os_bsd)',
+-      'use_openssl%': '<(use_openssl)',
+-      'use_ibus%': '<(use_ibus)',
+-      'enable_viewport%': '<(enable_viewport)',
+-      'enable_hidpi%': '<(enable_hidpi)',
+-      'enable_touch_ui%': '<(enable_touch_ui)',
+-      'android_upstream_bringup%': '<(android_upstream_bringup)',
+-      'android_build_type%': '<(android_build_type)',
+-
+-      # We used to provide a variable for changing how libraries were built.
+-      # This variable remains until we can clean up all the users.
+-      # This needs to be one nested variables dict in so that dependent
+-      # gyp files can make use of it in their outer variables.  (Yikes!)
+-      # http://code.google.com/p/chromium/issues/detail?id=83308
+-      'library%': 'static_library',
+-
+-      # Override branding to select the desired branding flavor.
+-      'branding%': 'Chromium',
+-
+-      'buildtype%': '<(buildtype)',
+-
+-      # Default architecture we're building for is the architecture we're
+-      # building on.
+-      'target_arch%': '<(host_arch)',
+-
+-      # This variable tells WebCore.gyp and JavaScriptCore.gyp whether they are
+-      # are built under a chromium full build (1) or a webkit.org chromium
+-      # build (0).
+-      'inside_chromium_build%': 1,
+-
+-      # Set to 1 to enable fast builds. It disables debug info for fastest
+-      # compilation.
+-      'fastbuild%': 0,
+-
+-      # Set to 1 to enable dcheck in release without having to use the flag.
+-      'dcheck_always_on%': 0,
+-
+-      # Disable file manager component extension by default.
+-      'file_manager_extension%': 0,
+-
+-      # Python version.
+-      'python_ver%': '2.6',
+-
+-      # Set ARM version (for libyuv)
+-      'arm_version%': 6,
+-
+-      # Set ARM-v7 compilation flags
+-      'armv7%': 0,
+-
+-      # Set Neon compilation flags (only meaningful if armv7==1).
+-      'arm_neon%': 1,
+-      'arm_neon_optional%': 0,
+-
+-      # The system root for cross-compiles. Default: none.
+-      'sysroot%': '',
+-
+-      # The system libdir used for this ABI.
+-      'system_libdir%': 'lib',
+-
+-      # On Linux, we build with sse2 for Chromium builds.
+-      'disable_sse2%': 0,
+-
+-      # Use libjpeg-turbo as the JPEG codec used by Chromium.
+-      'use_libjpeg_turbo%': 1,
+-
+-      # Use system libjpeg. Note that the system's libjepg will be used even if
+-      # use_libjpeg_turbo is set.
+-      'use_system_libjpeg%': 0,
+-
+-      # Use system libvpx
+-      'use_system_libvpx%': 0,
+-
+-      # Variable 'component' is for cases where we would like to build some
+-      # components as dynamic shared libraries but still need variable
+-      # 'library' for static libraries.
+-      # By default, component is set to whatever library is set to and
+-      # it can be overriden by the GYP command line or by ~/.gyp/include.gypi.
+-      'component%': 'static_library',
+-
+-      # Set to select the Title Case versions of strings in GRD files.
+-      'use_titlecase_in_grd_files%': 0,
+-
+-      # Use translations provided by volunteers at launchpad.net.  This
+-      # currently only works on Linux.
+-      'use_third_party_translations%': 0,
+-
+-      # Remoting compilation is enabled by default. Set to 0 to disable.
+-      'remoting%': 1,
+-
+-      # Configuration policy is enabled by default. Set to 0 to disable.
+-      'configuration_policy%': 1,
+-
+-      # Safe browsing is compiled in by default. Set to 0 to disable.
+-      'safe_browsing%': 1,
+-
+-      # Speech input is compiled in by default. Set to 0 to disable.
+-      'input_speech%': 1,
+-
+-      # Notifications are compiled in by default. Set to 0 to disable.
+-      'notifications%' : 1,
+-
+-      # If this is set, the clang plugins used on the buildbot will be used.
+-      # Run tools/clang/scripts/update.sh to make sure they are compiled.
+-      # This causes 'clang_chrome_plugins_flags' to be set.
+-      # Has no effect if 'clang' is not set as well.
+-      'clang_use_chrome_plugins%': 1,
+-
+-      # Enable building with ASAN (Clang's -faddress-sanitizer option).
+-      # -faddress-sanitizer only works with clang, but asan=1 implies clang=1
+-      # See https://sites.google.com/a/chromium.org/dev/developers/testing/addresssanitizer
+-      'asan%': 0,
+-
+-      # Enable building with TSAN (Clang's -fthread-sanitizer option).
+-      # -fthread-sanitizer only works with clang, but tsan=1 implies clang=1
+-      # See http://clang.llvm.org/docs/ThreadSanitizer.html
+-      'tsan%': 0,
+-
+-      # Use a modified version of Clang to intercept allocated types and sizes
+-      # for allocated objects. clang_type_profiler=1 implies clang=1.
+-      # See http://dev.chromium.org/developers/deep-memory-profiler/cpp-object-type-identifier
+-      # TODO(dmikurube): Support mac.  See http://crbug.com/123758#c11
+-      'clang_type_profiler%': 0,
+-
+-      # Set to true to instrument the code with function call logger.
+-      # See src/third_party/cygprofile/cyg-profile.cc for details.
+-      'order_profiling%': 0,
+-
+-      # Use the provided profiled order file to link Chrome image with it.
+-      # This makes Chrome faster by better using CPU cache when executing code.
+-      # This is known as PGO (profile guided optimization).
+-      # See https://sites.google.com/a/google.com/chrome-msk/dev/boot-speed-up-effort
+-      'order_text_section%' : "",
+-
+-      # Set to 1 compile with -fPIC cflag on linux. This is a must for shared
+-      # libraries on linux x86-64 and arm, plus ASLR.
+-      'linux_fpic%': 1,
+-
+-      # Whether one-click signin is enabled or not.
+-      'enable_one_click_signin%': 0,
+-
+-      # Enable Web Intents support in WebKit.
+-      'enable_web_intents%': 1,
+-
+-      # Enable Chrome browser extensions
+-      'enable_extensions%': 1,
+-
+-      # Enable browser automation.
+-      'enable_automation%': 1,
+-
+-      # Enable printing support and UI.
+-      'enable_printing%': 1,
+-
+-      # Enable Web Intents web content registration via HTML element
+-      # and WebUI managing such registrations.
+-      'enable_web_intents_tag%': 0,
+-
+-      # Webrtc compilation is enabled by default. Set to 0 to disable.
+-      'enable_webrtc%': 1,
+-
+-      # PPAPI by default does not support plugins making calls off the main
+-      # thread. Set to 1 to turn on experimental support for out-of-process
+-      # plugins to make call of the main thread.
+-      'enable_pepper_threading%': 0,
+-
+-      # Enables use of the session service, which is enabled by default.
+-      # Support for disabling depends on the platform.
+-      'enable_session_service%': 1,
+-
+-      # Enables theme support, which is enabled by default.  Support for
+-      # disabling depends on the platform.
+-      'enable_themes%': 1,
+-
+-      # Uses OEM-specific wallpaper resources on Chrome OS.
+-      'use_oem_wallpaper%': 0,
+-
+-      # Enables support for background apps.
+-      'enable_background%': 1,
+-
+-      # Enable the task manager by default.
+-      'enable_task_manager%': 1,
+-
+-      # Enable FTP support by default.
+-      'disable_ftp_support%': 0,
+-
+-      # XInput2 multitouch support is disabled by default (use_xi2_mt=0).
+-      # Setting to non-zero value enables XI2 MT. When XI2 MT is enabled,
+-      # the input value also defines the required XI2 minor minimum version.
+-      # For example, use_xi2_mt=2 means XI2.2 or above version is required.
+-      'use_xi2_mt%': 0,
+-
+-      # Use of precompiled headers on Windows.
+-      #
+-      # This is on by default in VS 2010, but off by default for VS
+-      # 2008 because of complications that it can cause with our
+-      # trybots etc.
+-      #
+-      # This variable may be explicitly set to 1 (enabled) or 0
+-      # (disabled) in ~/.gyp/include.gypi or via the GYP command line.
+-      # This setting will override the default.
+-      #
+-      # Note that a setting of 1 is probably suitable for most or all
+-      # Windows developers using VS 2008, since precompiled headers
+-      # provide a build speedup of 20-25%.  There are a couple of
+-      # small workarounds you may need to use when using VS 2008 (but
+-      # not 2010), see
+-      # http://code.google.com/p/chromium/wiki/WindowsPrecompiledHeaders
+-      # for details.
+-      'chromium_win_pch%': 0,
+-
+-      # Set this to true when building with Clang.
+-      # See http://code.google.com/p/chromium/wiki/Clang for details.
+-      'clang%': 0,
+-
+-      # Enable plug-in installation by default.
+-      'enable_plugin_installation%': 1,
+-
+-      # Enable protector service by default.
+-      'enable_protector_service%': 1,
+-
+-      # Specifies whether to use canvas_skia.cc in place of platform
+-      # specific implementations of gfx::Canvas. Affects text drawing in the
+-      # Chrome UI.
+-      # TODO(asvitkine): Enable this on all platforms and delete this flag.
+-      #                  http://crbug.com/105550
+-      'use_canvas_skia%': 0,
+-
+-      # Set to "tsan", "memcheck", or "drmemory" to configure the build to work
+-      # with one of those tools.
+-      'build_for_tool%': '',
+-
+-      # Whether tests targets should be run, archived or just have the
+-      # dependencies verified. All the tests targets have the '_run' suffix,
+-      # e.g. base_unittests_run runs the target base_unittests. The test target
+-      # always calls tools/swarm_client/isolate.py. See the script's --help for
+-      # more information and the valid --mode values. Meant to be overriden with
+-      # GYP_DEFINES.
+-      # TODO(maruel): Converted the default from 'check' to 'noop' so work can
+-      # be done while the builders are being reconfigured to check out test data
+-      # files.
+-      'test_isolation_mode%': 'noop',
+-      # It must not be '<(PRODUCT_DIR)' alone, the '/' is necessary otherwise
+-      # gyp will remove duplicate flags, causing isolate.py to be confused.
+-      'test_isolation_outdir%': '<(PRODUCT_DIR)/isolate',
+-
+-       # Force rlz to use chrome's networking stack.
+-      'force_rlz_use_chrome_net%': 1,
+-
+-      'sas_dll_path%': '<(DEPTH)/third_party/platformsdk_win7/files/redist/x86',
+-      'wix_path%': '<(DEPTH)/third_party/wix',
+-
+-      'conditions': [
+-        # TODO(epoger): Figure out how to set use_skia=1 for Mac outside of
+-        # the 'conditions' clause.  Initial attempts resulted in chromium and
+-        # webkit disagreeing on its setting.
+-        ['OS=="mac"', {
+-          'use_skia%': 1,
+-        }, {
+-          'use_skia%': 1,
+-        }],
+-
+-        # A flag for POSIX platforms
+-        ['OS=="win"', {
+-          'os_posix%': 0,
+-        }, {
+-          'os_posix%': 1,
+-        }],
+-
+-        # NSS usage.
+-        ['(OS=="linux" or OS=="solaris" or os_bsd==1) and use_openssl==0', {
+-          'use_nss%': 1,
+-        }, {
+-          'use_nss%': 0,
+-        }],
+-
+-        # Flags to use X11 on non-Mac POSIX platforms
+-        ['OS=="win" or OS=="mac" or OS=="ios" or OS=="android"', {
+-          'use_glib%': 0,
+-          'use_x11%': 0,
+-        }, {
+-          'use_glib%': 1,
+-          'use_x11%': 1,
+-        }],
+-
+-        # We always use skia text rendering in Aura on Windows, since GDI
+-        # doesn't agree with our BackingStore.
+-        # TODO(beng): remove once skia text rendering is on by default.
+-        ['use_aura==1 and OS=="win"', {
+-          'enable_skia_text%': 1,
+-        }],
+-
+-        # A flag to enable or disable our compile-time dependency
+-        # on gnome-keyring. If that dependency is disabled, no gnome-keyring
+-        # support will be available. This option is useful
+-        # for Linux distributions and for Aura.
+-        ['chromeos==1 or use_aura==1', {
+-          'use_gnome_keyring%': 0,
+-        }, {
+-          'use_gnome_keyring%': 1,
+-        }],
+-
+-        ['toolkit_uses_gtk==1 or OS=="mac" or OS=="ios"', {
+-          # GTK+, Mac and iOS want Title Case strings
+-          'use_titlecase_in_grd_files%': 1,
+-        }],
+-
+-        # Enable file manager extension on Chrome OS.
+-        ['chromeos==1', {
+-          'file_manager_extension%': 1,
+-        }, {
+-          'file_manager_extension%': 0,
+-        }],
+-
+-        ['OS=="win" or OS=="mac" or (OS=="linux" and use_aura==0)', {
+-          'enable_one_click_signin%': 1,
+-        }],
+-
+-        ['OS=="android"', {
+-          'enable_extensions%': 0,
+-          'enable_printing%': 0,
+-          'enable_themes%': 0,
+-          'enable_webrtc%': 0,
+-          'proprietary_codecs%': 1,
+-          'remoting%': 0,
+-        }],
+-
+-        ['OS=="ios"', {
+-          'configuration_policy%': 0,
+-          'disable_ftp_support%': 1,
+-          'enable_automation%': 0,
+-          'enable_extensions%': 0,
+-          'enable_printing%': 0,
+-          'enable_themes%': 0,
+-          'enable_webrtc%': 0,
+-          'notifications%': 0,
+-          'remoting%': 0,
+-        }],
+-
+-        # Use GPU accelerated cross process image transport by default
+-        # on linux builds with the Aura window manager
+-        ['use_aura==1 and OS=="linux"', {
+-          'ui_compositor_image_transport%': 1,
+-        }, {
+-          'ui_compositor_image_transport%': 0,
+-        }],
+-
+-        # Turn precompiled headers on by default for VS 2010.
+-        ['OS=="win" and MSVS_VERSION=="2010" and buildtype!="Official"', {
+-          'chromium_win_pch%': 1
+-        }],
+-
+-        ['use_aura==1 or chromeos==1 or OS=="android"', {
+-          'enable_plugin_installation%': 0,
+-        }, {
+-          'enable_plugin_installation%': 1,
+-        }],
+-
+-        ['OS=="android" or OS=="ios"', {
+-          'enable_protector_service%': 0,
+-        }, {
+-          'enable_protector_service%': 1,
+-        }],
+-
+-        # linux_use_gold_binary: whether to use the binary checked into
+-        # third_party/gold.
+-        ['OS=="linux"', {
+-          'linux_use_gold_binary%': 1,
+-        }, {
+-          'linux_use_gold_binary%': 0,
+-        }],
+-
+-        # linux_use_gold_flags: whether to use build flags that rely on gold.
+-        # On by default for x64 Linux.  Temporarily off for ChromeOS as
+-        # it failed on a buildbot.
+-        ['OS=="linux" and chromeos==0', {
+-          'linux_use_gold_flags%': 1,
+-        }, {
+-          'linux_use_gold_flags%': 0,
+-        }],
+-
+-        ['OS=="android"', {
+-          'enable_captive_portal_detection%': 0,
+-        }, {
+-          'enable_captive_portal_detection%': 1,
+-        }],
+-
+-        # Enable Skia UI text drawing incrementally on different platforms.
+-        # http://crbug.com/105550
+-        #
+-        # On Aura, this allows per-tile painting to be used in the browser
+-        # compositor.
+-        ['OS!="mac" and OS!="android"', {
+-          'use_canvas_skia%': 1,
+-        }],
+-
+-        ['chromeos==1', {
+-          # When building for ChromeOS we dont want Chromium to use libjpeg_turbo.
+-          'use_libjpeg_turbo%': 0,
+-        }],
+-
+-        ['OS=="android"', {
+-          # When building as part of the Android system, use system libraries
+-          # where possible to reduce ROM size.
+-          'use_system_libjpeg%': '<(android_build_type)',
+-        }],
+-      ],
+-
+-      # Set this to 1 to use the Google-internal file containing
+-      # official API keys for Google Chrome even in a developer build.
+-      # Setting this variable explicitly to 1 will cause your build to
+-      # fail if the internal file is missing.
+-      #
+-      # Set this to 0 to not use the internal file, even when it
+-      # exists in your checkout.
+-      #
+-      # Leave set to 2 to have this variable implicitly set to 1 if
+-      # you have src/google_apis/internal/google_chrome_api_keys.h in
+-      # your checkout, and implicitly set to 0 if not.
+-      #
+-      # Note that official builds always behave as if this variable
+-      # was explicitly set to 1, i.e. they always use official keys,
+-      # and will fail to build if the internal file is missing.
+-      'use_official_google_api_keys%': 2,
+-
+-      # Set these to bake the specified API keys and OAuth client
+-      # IDs/secrets into your build.
+-      #
+-      # If you create a build without values baked in, you can instead
+-      # set environment variables to provide the keys at runtime (see
+-      # src/google_apis/google_api_keys.h for details).  Features that
+-      # require server-side APIs may fail to work if no keys are
+-      # provided.
+-      #
+-      # Note that if you are building an official build or if
+-      # use_official_google_api_keys has been set to 1 (explicitly or
+-      # implicitly), these values will be ignored and the official
+-      # keys will be used instead.
+-      'google_api_key%': '',
+-      'google_default_client_id%': '',
+-      'google_default_client_secret%': '',
+-    },
+-
+-    # Copy conditionally-set variables out one scope.
+-    'branding%': '<(branding)',
+-    'buildtype%': '<(buildtype)',
+-    'target_arch%': '<(target_arch)',
+-    'host_arch%': '<(host_arch)',
+-    'library%': 'static_library',
+-    'toolkit_views%': '<(toolkit_views)',
+-    'ui_compositor_image_transport%': '<(ui_compositor_image_transport)',
+-    'use_aura%': '<(use_aura)',
+-    'use_ash%': '<(use_ash)',
+-    'use_openssl%': '<(use_openssl)',
+-    'use_ibus%': '<(use_ibus)',
+-    'use_nss%': '<(use_nss)',
+-    'os_bsd%': '<(os_bsd)',
+-    'os_posix%': '<(os_posix)',
+-    'use_glib%': '<(use_glib)',
+-    'toolkit_uses_gtk%': '<(toolkit_uses_gtk)',
+-    'use_skia%': '<(use_skia)',
+-    'use_x11%': '<(use_x11)',
+-    'use_gnome_keyring%': '<(use_gnome_keyring)',
+-    'linux_fpic%': '<(linux_fpic)',
+-    'enable_pepper_threading%': '<(enable_pepper_threading)',
+-    'chromeos%': '<(chromeos)',
+-    'enable_viewport%': '<(enable_viewport)',
+-    'enable_hidpi%': '<(enable_hidpi)',
+-    'enable_touch_ui%': '<(enable_touch_ui)',
+-    'use_xi2_mt%':'<(use_xi2_mt)',
+-    'file_manager_extension%': '<(file_manager_extension)',
+-    'inside_chromium_build%': '<(inside_chromium_build)',
+-    'fastbuild%': '<(fastbuild)',
+-    'dcheck_always_on%': '<(dcheck_always_on)',
+-    'python_ver%': '<(python_ver)',
+-    'arm_version%': '<(arm_version)',
+-    'armv7%': '<(armv7)',
+-    'arm_neon%': '<(arm_neon)',
+-    'arm_neon_optional%': '<(arm_neon_optional)',
+-    'sysroot%': '<(sysroot)',
+-    'system_libdir%': '<(system_libdir)',
+-    'component%': '<(component)',
+-    'use_titlecase_in_grd_files%': '<(use_titlecase_in_grd_files)',
+-    'use_third_party_translations%': '<(use_third_party_translations)',
+-    'remoting%': '<(remoting)',
+-    'enable_one_click_signin%': '<(enable_one_click_signin)',
+-    'enable_webrtc%': '<(enable_webrtc)',
+-    'chromium_win_pch%': '<(chromium_win_pch)',
+-    'configuration_policy%': '<(configuration_policy)',
+-    'safe_browsing%': '<(safe_browsing)',
+-    'input_speech%': '<(input_speech)',
+-    'notifications%': '<(notifications)',
+-    'clang_use_chrome_plugins%': '<(clang_use_chrome_plugins)',
+-    'asan%': '<(asan)',
+-    'tsan%': '<(tsan)',
+-    'clang_type_profiler%': '<(clang_type_profiler)',
+-    'order_profiling%': '<(order_profiling)',
+-    'order_text_section%': '<(order_text_section)',
+-    'enable_extensions%': '<(enable_extensions)',
+-    'enable_web_intents%': '<(enable_web_intents)',
+-    'enable_web_intents_tag%': '<(enable_web_intents_tag)',
+-    'enable_plugin_installation%': '<(enable_plugin_installation)',
+-    'enable_protector_service%': '<(enable_protector_service)',
+-    'enable_session_service%': '<(enable_session_service)',
+-    'enable_themes%': '<(enable_themes)',
+-    'use_oem_wallpaper%': '<(use_oem_wallpaper)',
+-    'enable_background%': '<(enable_background)',
+-    'linux_use_gold_binary%': '<(linux_use_gold_binary)',
+-    'linux_use_gold_flags%': '<(linux_use_gold_flags)',
+-    'use_canvas_skia%': '<(use_canvas_skia)',
+-    'test_isolation_mode%': '<(test_isolation_mode)',
+-    'test_isolation_outdir%': '<(test_isolation_outdir)',
+-    'enable_automation%': '<(enable_automation)',
+-    'enable_printing%': '<(enable_printing)',
+-    'enable_captive_portal_detection%': '<(enable_captive_portal_detection)',
+-    'disable_ftp_support%': '<(disable_ftp_support)',
+-    'force_rlz_use_chrome_net%': '<(force_rlz_use_chrome_net)',
+-    'enable_task_manager%': '<(enable_task_manager)',
+-    'sas_dll_path%': '<(sas_dll_path)',
+-    'wix_path%': '<(wix_path)',
+-    'android_upstream_bringup%': '<(android_upstream_bringup)',
+-    'use_libjpeg_turbo%': '<(use_libjpeg_turbo)',
+-    'use_system_libjpeg%': '<(use_system_libjpeg)',
+-    'android_build_type%': '<(android_build_type)',
+-    'use_official_google_api_keys%': '<(use_official_google_api_keys)',
+-    'google_api_key%': '<(google_api_key)',
+-    'google_default_client_id%': '<(google_default_client_id)',
+-    'google_default_client_secret%': '<(google_default_client_secret)',
+-
+-    # Use system yasm instead of bundled one.
+-    'use_system_yasm%': 0,
+-
+-    # Default to enabled PIE; this is important for ASLR but we may need to be
+-    # able to turn it off for various reasons.
+-    'linux_disable_pie%': 0,
+-
+-    # The release channel that this build targets. This is used to restrict
+-    # channel-specific build options, like which installer packages to create.
+-    # The default is 'all', which does no channel-specific filtering.
+-    'channel%': 'all',
+-
+-    # Override chromium_mac_pch and set it to 0 to suppress the use of
+-    # precompiled headers on the Mac.  Prefix header injection may still be
+-    # used, but prefix headers will not be precompiled.  This is useful when
+-    # using distcc to distribute a build to compile slaves that don't
+-    # share the same compiler executable as the system driving the compilation,
+-    # because precompiled headers rely on pointers into a specific compiler
+-    # executable's image.  Setting this to 0 is needed to use an experimental
+-    # Linux-Mac cross compiler distcc farm.
+-    'chromium_mac_pch%': 1,
+-
+-    # The default value for mac_strip in target_defaults. This cannot be
+-    # set there, per the comment about variable% in a target_defaults.
+-    'mac_strip_release%': 1,
+-
+-    # Set to 1 to enable code coverage.  In addition to build changes
+-    # (e.g. extra CFLAGS), also creates a new target in the src/chrome
+-    # project file called "coverage".
+-    # Currently ignored on Windows.
+-    'coverage%': 0,
+-
+-    # Set to 1 to force Visual C++ to use legacy debug information format /Z7.
+-    # This is useful for parallel compilation tools which can't support /Zi.
+-    # Only used on Windows.
+-    'win_z7%' : 0,
+-
+-    # Although base/allocator lets you select a heap library via an
+-    # environment variable, the libcmt shim it uses sometimes gets in
+-    # the way.  To disable it entirely, and switch to normal msvcrt, do e.g.
+-    #  'win_use_allocator_shim': 0,
+-    #  'win_release_RuntimeLibrary': 2
+-    # to ~/.gyp/include.gypi, gclient runhooks --force, and do a release build.
+-    'win_use_allocator_shim%': 1, # 1 = shim allocator via libcmt; 0 = msvcrt
+-
+-    # Whether usage of OpenMAX is enabled.
+-    'enable_openmax%': 0,
+-
+-    # Whether proprietary audio/video codecs are assumed to be included with
+-    # this build (only meaningful if branding!=Chrome).
+-    'proprietary_codecs%': 0,
+-
+-    # TODO(bradnelson): eliminate this when possible.
+-    # To allow local gyp files to prevent release.vsprops from being included.
+-    # Yes(1) means include release.vsprops.
+-    # Once all vsprops settings are migrated into gyp, this can go away.
+-    'msvs_use_common_release%': 1,
+-
+-    # TODO(bradnelson): eliminate this when possible.
+-    # To allow local gyp files to override additional linker options for msvs.
+-    # Yes(1) means set use the common linker options.
+-    'msvs_use_common_linker_extras%': 1,
+-
+-    # TODO(sgk): eliminate this if possible.
+-    # It would be nicer to support this via a setting in 'target_defaults'
+-    # in chrome/app/locales/locales.gypi overriding the setting in the
+-    # 'Debug' configuration in the 'target_defaults' dict below,
+-    # but that doesn't work as we'd like.
+-    'msvs_debug_link_incremental%': '2',
+-
+-    # Needed for some of the largest modules.
+-    'msvs_debug_link_nonincremental%': '1',
+-
+-    # Turns on Use Library Dependency Inputs for linking chrome.dll on Windows
+-    # to get incremental linking to be faster in debug builds.
+-    'incremental_chrome_dll%': '0',
+-
+-    # The default settings for third party code for treating
+-    # warnings-as-errors. Ideally, this would not be required, however there
+-    # is some third party code that takes a long time to fix/roll. So, this
+-    # flag allows us to have warnings as errors in general to prevent
+-    # regressions in most modules, while working on the bits that are
+-    # remaining.
+-    'win_third_party_warn_as_error%': 'true',
+-
+-    # This is the location of the sandbox binary. Chrome looks for this before
+-    # running the zygote process. If found, and SUID, it will be used to
+-    # sandbox the zygote process and, thus, all renderer processes.
+-    'linux_sandbox_path%': '',
+-
+-    # Set this to true to enable SELinux support.
+-    'selinux%': 0,
+-
+-    # Clang stuff.
+-    'clang%': '<(clang)',
+-    'make_clang_dir%': 'third_party/llvm-build/Release+Asserts',
+-
+-    # These two variables can be set in GYP_DEFINES while running
+-    # |gclient runhooks| to let clang run a plugin in every compilation.
+-    # Only has an effect if 'clang=1' is in GYP_DEFINES as well.
+-    # Example:
+-    #     GYP_DEFINES='clang=1 clang_load=/abs/path/to/libPrintFunctionNames.dylib clang_add_plugin=print-fns' gclient runhooks
+-
+-    'clang_load%': '',
+-    'clang_add_plugin%': '',
+-
+-    # The default type of gtest.
+-    'gtest_target_type%': 'executable',
+-
+-    # Enable sampling based profiler.
+-    # See http://google-perftools.googlecode.com/svn/trunk/doc/cpuprofile.html
+-    'profiling%': '0',
+-
+-    # Enable strict glibc debug mode.
+-    'glibcxx_debug%': 0,
+-
+-    # Override whether we should use Breakpad on Linux. I.e. for Chrome bot.
+-    'linux_breakpad%': 0,
+-    # And if we want to dump symbols for Breakpad-enabled builds.
+-    'linux_dump_symbols%': 0,
+-    # And if we want to strip the binary after dumping symbols.
+-    'linux_strip_binary%': 0,
+-    # Strip the test binaries needed for Linux reliability tests.
+-    'linux_strip_reliability_tests%': 0,
+-
+-    # Enable TCMalloc.
+-    'linux_use_tcmalloc%': 1,
+-
+-    # Disable TCMalloc's debugallocation.
+-    'linux_use_debugallocation%': 0,
+-
+-    # Disable TCMalloc's heapchecker.
+-    'linux_use_heapchecker%': 0,
+-
+-    # Disable shadow stack keeping used by heapcheck to unwind the stacks
+-    # better.
+-    'linux_keep_shadow_stacks%': 0,
+-
+-    # Set to 1 to link against libgnome-keyring instead of using dlopen().
+-    'linux_link_gnome_keyring%': 0,
+-    # Set to 1 to link against gsettings APIs instead of using dlopen().
+-    'linux_link_gsettings%': 0,
+-
+-    # Set Thumb compilation flags.
+-    'arm_thumb%': 0,
+-
+-    # Set ARM fpu compilation flags (only meaningful if armv7==1 and
+-    # arm_neon==0).
+-    'arm_fpu%': 'vfpv3',
+-
+-    # Set ARM float abi compilation flag.
+-    'arm_float_abi%': 'softfp',
+-
+-    # Enable new NPDevice API.
+-    'enable_new_npdevice_api%': 0,
+-
+-    # Enable EGLImage support in OpenMAX
+-    'enable_eglimage%': 1,
+-
+-    # Enable a variable used elsewhere throughout the GYP files to determine
+-    # whether to compile in the sources for the GPU plugin / process.
+-    'enable_gpu%': 1,
+-
+-    # .gyp files or targets should set chromium_code to 1 if they build
+-    # Chromium-specific code, as opposed to external code.  This variable is
+-    # used to control such things as the set of warnings to enable, and
+-    # whether warnings are treated as errors.
+-    'chromium_code%': 0,
+-
+-    'release_valgrind_build%': 0,
+-
+-    # TODO(thakis): Make this a blacklist instead, http://crbug.com/101600
+-    'enable_wexit_time_destructors%': 0,
+-
+-    # Set to 1 to compile with the built in pdf viewer.
+-    'internal_pdf%': 0,
+-
+-    # Set to 1 to compile with the OpenGL ES 2.0 conformance tests.
+-    'internal_gles2_conform_tests%': 0,
+-
+-    # NOTE: When these end up in the Mac bundle, we need to replace '-' for '_'
+-    # so Cocoa is happy (http://crbug.com/20441).
+-    'locales': [
+-      'am', 'ar', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'en-GB',
+-      'en-US', 'es-419', 'es', 'et', 'fa', 'fi', 'fil', 'fr', 'gu', 'he',
+-      'hi', 'hr', 'hu', 'id', 'it', 'ja', 'kn', 'ko', 'lt', 'lv',
+-      'ml', 'mr', 'ms', 'nb', 'nl', 'pl', 'pt-BR', 'pt-PT', 'ro', 'ru',
+-      'sk', 'sl', 'sr', 'sv', 'sw', 'ta', 'te', 'th', 'tr', 'uk',
+-      'vi', 'zh-CN', 'zh-TW',
+-    ],
+-
+-    # Pseudo locales are special locales which are used for testing and
+-    # debugging. They don't get copied to the final app. For more info,
+-    # check out https://sites.google.com/a/chromium.org/dev/Home/fake-bidi
+-    'pseudo_locales': [
+-      'fake-bidi',
+-    ],
+-
+-    'grit_defines': [],
+-
+-    # If debug_devtools is set to 1, JavaScript files for DevTools are
+-    # stored as is and loaded from disk. Otherwise, a concatenated file
+-    # is stored in resources.pak. It is still possible to load JS files
+-    # from disk by passing --debug-devtools cmdline switch.
+-    'debug_devtools%': 0,
+-
+-    # The Java Bridge is not compiled in by default.
+-    'java_bridge%': 0,
+-
+-    # Code signing for iOS binaries.  The bots need to be able to disable this.
+-    'chromium_ios_signing%': 1,
+-
+-    # This flag is only used when disable_nacl==0 and disables all those
+-    # subcomponents which would require the installation of a native_client
+-    # untrusted toolchain.
+-    'disable_nacl_untrusted%': 0,
+-
+-    # Disable Dart by default.
+-    'enable_dart%': 0,
+-
+-    # The desired version of Windows SDK can be set in ~/.gyp/include.gypi.
+-    'msbuild_toolset%': '',
+-
+-    # Native Client is enabled by default.
+-    'disable_nacl%': 0,
+-
+-    # Whether to build full debug version for Debug configuration on Android.
+-    # Compared to full debug version, the default Debug configuration on Android
+-    # has no full v8 debug, has size optimization and linker gc section, so that
+-    # we can build a debug version with acceptable size and performance.
+-    'android_full_debug%': 0,
+-
+-    # Sets the default version name and code for Android app, by default we
+-    # do a developer build.
+-    'android_app_version_name%': 'Developer Build',
+-    'android_app_version_code%': 0,
+-
+-    'sas_dll_exists': 0, # '<!(<(PYTHON) <(DEPTH)/build/dir_exists.py <(sas_dll_path))',
+-    'wix_exists': 0, # '<!(<(PYTHON) <(DEPTH)/build/dir_exists.py <(wix_path))',
+-
+-    'windows_sdk_default_path': '<(DEPTH)/third_party/platformsdk_win8/files',
+-#    'directx_sdk_default_path': '<(DEPTH)/third_party/directxsdk/files',
+-    'windows_sdk_path%': '<(windows_sdk_default_path)',
+-
+-    'conditions': [
+-      #['"<!(<(PYTHON) <(DEPTH)/build/dir_exists.py <(windows_sdk_default_path))"=="True"', {
+-      #  'windows_sdk_path%': '<(windows_sdk_default_path)',
+-      #}, {
+-      #  'windows_sdk_path%': 'C:/Program Files (x86)/Windows Kits/8.0',
+-      #}],
+-      #['OS=="win" and "<!(<(PYTHON) <(DEPTH)/build/dir_exists.py <(directx_sdk_default_path))"=="True"', {
+-      #  'directx_sdk_path%': '<(directx_sdk_default_path)',
+-      #}, {
+-      #  'directx_sdk_path%': '$(DXSDK_DIR)',
+-      #}],
+-      # If use_official_google_api_keys is already set (to 0 or 1), we
+-      # do none of the implicit checking.  If it is set to 1 and the
+-      # internal keys file is missing, the build will fail at compile
+-      # time.  If it is set to 0 and keys are not provided by other
+-      # means, a warning will be printed at compile time.
+-      ['use_official_google_api_keys==2', {
+-        'use_official_google_api_keys%':
+-            '<!(<(PYTHON) <(DEPTH)/google_apis/build/check_internal.py <(DEPTH)/google_apis/internal/google_chrome_api_keys.h)',
+-      }],
+-      ['os_posix==1 and OS!="mac" and OS!="ios"', {
+-        # Figure out the python architecture to decide if we build pyauto.
+-	# disabled for mozilla because windows != mac and this runs a shell script
+-	#        'python_arch%': '<!(<(DEPTH)/build/linux/python_arch.sh <(sysroot)/usr/<(system_libdir)/libpython<(python_ver).so.1.0)',
+-        'conditions': [
+-          # TODO(glider): set clang to 1 earlier for ASan and TSan builds so
+-          # that it takes effect here.
+-          # disabled for Mozilla since it doesn't use this, and 'msys' messes $(CXX) up
+-          ['build_with_mozilla==0 and clang==0 and asan==0 and tsan==0', {
+-            # This will set gcc_version to XY if you are running gcc X.Y.*.
+-            'gcc_version%': '<!(<(PYTHON) <(DEPTH)/build/compiler_version.py)',
+-          }, {
+-            'gcc_version%': 0,
+-          }],
+-          ['branding=="Chrome"', {
+-            'linux_breakpad%': 1,
+-          }],
+-          # All Chrome builds have breakpad symbols, but only process the
+-          # symbols from official builds.
+-          ['(branding=="Chrome" and buildtype=="Official")', {
+-            'linux_dump_symbols%': 1,
+-          }],
+-        ],
+-      }],  # os_posix==1 and OS!="mac" and OS!="ios"
+-      ['OS=="ios"', {
+-        'disable_nacl%': 1,
+-        'enable_gpu%': 0,
+-        'icu_use_data_file_flag%': 1,
+-        'use_system_bzip2%': 1,
+-        'use_system_libxml%': 1,
+-        'use_system_sqlite%': 1,
+-
+-        # The Mac SDK is set for iOS builds and passed through to Mac
+-        # sub-builds. This allows the Mac sub-build SDK in an iOS build to be
+-        # overridden from the command line the same way it is for a Mac build.
+-        'mac_sdk%': '<!(<(PYTHON) <(DEPTH)/build/mac/find_sdk.py 10.6)',
+-
+-        # iOS SDK and deployment target support.  The iOS 5.0 SDK is actually
+-        # what is required, but the value is left blank so when it is set in
+-        # the project files it will be the "current" iOS SDK.  Forcing 5.0
+-        # even though it is "current" causes Xcode to spit out a warning for
+-        # every single project file for not using the "current" SDK.
+-        'ios_sdk%': '',
+-        'ios_sdk_path%': '',
+-        'ios_deployment_target%': '4.3',
+-
+-        'conditions': [
+-          # ios_product_name is set to the name of the .app bundle as it should
+-          # appear on disk.
+-          ['branding=="Chrome"', {
+-            'ios_product_name%': 'Chrome',
+-          }, { # else: branding!="Chrome"
+-            'ios_product_name%': 'Chromium',
+-          }],
+-          ['branding=="Chrome" and buildtype=="Official"', {
+-            'ios_breakpad%': 1,
+-          }, { # else: branding!="Chrome" or buildtype!="Official"
+-            'ios_breakpad%': 0,
+-          }],
+-        ],
+-      }],  # OS=="ios"
+-      ['OS=="android"', {
+-        # Location of Android NDK.
+-        'variables': {
+-          'variables': {
+-            'variables': {
+-              'android_ndk_root%': '<!(/bin/echo -n $ANDROID_NDK_ROOT)',
+-            },
+-            'android_ndk_root%': '<(android_ndk_root)',
+-            'conditions': [
+-              ['target_arch == "ia32"', {
+-                'android_app_abi%': 'x86',
+-                'android_ndk_sysroot%': '<(android_ndk_root)/platforms/android-9/arch-x86',
+-              }],
+-              ['target_arch=="arm"', {
+-                'android_ndk_sysroot%': '<(android_ndk_root)/platforms/android-9/arch-arm',
+-                'conditions': [
+-                  ['armv7==0', {
+-                    'android_app_abi%': 'armeabi',
+-                  }, {
+-                    'android_app_abi%': 'armeabi-v7a',
+-                  }],
+-                ],
+-              }],
+-              ['target_arch=="arm64"', {
+-                'android_app_abi%': 'arm64-v8a',
+-                'android_ndk_sysroot%': '<(android_ndk_root)/platforms/android-21/arch-arm64',
+-              }],
+-            ],
+-          },
+-          'android_ndk_root%': '<(android_ndk_root)',
+-          'android_app_abi%': '<(android_app_abi)',
+-          'android_ndk_sysroot%': '<(android_ndk_sysroot)',
+-        },
+-        'android_ndk_root%': '<(android_ndk_root)',
+-        'android_ndk_sysroot': '<(android_ndk_sysroot)',
+-        'android_ndk_include': '<(android_ndk_sysroot)/usr/include',
+-        'android_ndk_lib': '<(android_ndk_sysroot)/usr/lib',
+-        'android_app_abi%': '<(android_app_abi)',
+-
+-        # Location of the "strip" binary, used by both gyp and scripts.
+-        'android_strip%' : '<!(/bin/echo -n <(android_toolchain)/*-strip)',
+-
+-        # Provides an absolute path to PRODUCT_DIR (e.g. out/Release). Used
+-        # to specify the output directory for Ant in the Android build.
+-        'ant_build_out': '`cd <(PRODUCT_DIR) && pwd -P`',
+-
+-        # Uses Android's crash report system
+-        'linux_breakpad%': 0,
+-
+-        # Always uses openssl.
+-        'use_openssl%': 1,
+-
+-        'proprietary_codecs%': '<(proprietary_codecs)',
+-        'enable_task_manager%': 0,
+-        'safe_browsing%': 0,
+-        'configuration_policy%': 0,
+-        'input_speech%': 0,
+-        'enable_web_intents%': 0,
+-        'enable_automation%': 0,
+-        'java_bridge%': 1,
+-        'build_ffmpegsumo%': 0,
+-        'linux_use_tcmalloc%': 0,
+-
+-        # Disable Native Client.
+-        'disable_nacl%': 1,
+-
+-        # Android does not support background apps.
+-        'enable_background%': 0,
+-
+-        # Sessions are store separately in the Java side.
+-        'enable_session_service%': 0,
+-
+-        # Set to 1 once we have a notification system for Android.
+-        # http://crbug.com/115320
+-        'notifications%': 0,
+-
+-        'p2p_apis%' : 0,
+-
+-        # TODO(jrg): when 'gtest_target_type'=='shared_library' and
+-        # OS==android, make all gtest_targets depend on
+-        # testing/android/native_test.gyp:native_test_apk.
+-        'gtest_target_type%': 'shared_library',
+-
+-        # Uses system APIs for decoding audio and video.
+-        'use_libffmpeg%': '0',
+-
+-        # Always use the chromium skia. The use_system_harfbuzz needs to
+-        # match use_system_skia.
+-        'use_system_skia%': '0',
+-        'use_system_harfbuzz%': '0',
+-
+-        # Configure crash reporting and build options based on release type.
+-        'conditions': [
+-          ['buildtype=="Official"', {
+-            # Only report crash dumps for Official builds.
+-            'linux_breakpad%': 1,
+-          }, {
+-            'linux_breakpad%': 0,
+-          }],
+-        ],
+-
+-        # When building as part of the Android system, use system libraries
+-        # where possible to reduce ROM size.
+-        # TODO(steveblock): Investigate using the system version of sqlite.
+-        'use_system_sqlite%': 0,  # '<(android_build_type)',
+-        'use_system_expat%': '<(android_build_type)',
+-        'use_system_icu%': '<(android_build_type)',
+-        'use_system_stlport%': '<(android_build_type)',
+-
+-        # Copy it out one scope.
+-        'android_build_type%': '<(android_build_type)',
+-      }],  # OS=="android"
+-      ['OS=="mac"', {
+-        'variables': {
+-          # Mac OS X SDK and deployment target support.  The SDK identifies
+-          # the version of the system headers that will be used, and
+-          # corresponds to the MAC_OS_X_VERSION_MAX_ALLOWED compile-time
+-          # macro.  "Maximum allowed" refers to the operating system version
+-          # whose APIs are available in the headers.  The deployment target
+-          # identifies the minimum system version that the built products are
+-          # expected to function on.  It corresponds to the
+-          # MAC_OS_X_VERSION_MIN_REQUIRED compile-time macro.  To ensure these
+-          # macros are available, #include <AvailabilityMacros.h>.  Additional
+-          # documentation on these macros is available at
+-          # http://developer.apple.com/mac/library/technotes/tn2002/tn2064.html#SECTION3
+-          # Chrome normally builds with the Mac OS X 10.6 SDK and sets the
+-          # deployment target to 10.6.  Other projects, such as O3D, may
+-          # override these defaults.
+-
+-          # Normally, mac_sdk_min is used to find an SDK that Xcode knows
+-          # about that is at least the specified version. In official builds,
+-          # the SDK must match mac_sdk_min exactly. If the SDK is installed
+-          # someplace that Xcode doesn't know about, set mac_sdk_path to the
+-          # path to the SDK; when set to a non-empty string, SDK detection
+-          # based on mac_sdk_min will be bypassed entirely.
+-          'mac_sdk_min%': '10.6',
+-          'mac_sdk_path%': '',
+-
+-          'mac_deployment_target%': '10.6',
+-        },
+-
+-        'mac_sdk_min': '<(mac_sdk_min)',
+-        'mac_sdk_path': '<(mac_sdk_path)',
+-        'mac_deployment_target': '<(mac_deployment_target)',
+-
+-        # Enable clang on mac by default!
+-        'clang%': 1,
+-
+-        # Compile in Breakpad support by default so that it can be
+-        # tested, even if it is not enabled by default at runtime.
+-        'mac_breakpad_compiled_in%': 1,
+-        'conditions': [
+-          # mac_product_name is set to the name of the .app bundle as it should
+-          # appear on disk.  This duplicates data from
+-          # chrome/app/theme/chromium/BRANDING and
+-          # chrome/app/theme/google_chrome/BRANDING, but is necessary to get
+-          # these names into the build system.
+-          ['branding=="Chrome"', {
+-            'mac_product_name%': 'Google Chrome',
+-          }, { # else: branding!="Chrome"
+-            'mac_product_name%': 'Chromium',
+-          }],
+-
+-          ['branding=="Chrome" and buildtype=="Official"', {
+-            'mac_sdk%': '<!(<(PYTHON) <(DEPTH)/build/mac/find_sdk.py --verify <(mac_sdk_min) --sdk_path=<(mac_sdk_path))',
+-            # Enable uploading crash dumps.
+-            'mac_breakpad_uploads%': 1,
+-            # Enable dumping symbols at build time for use by Mac Breakpad.
+-            'mac_breakpad%': 1,
+-            # Enable Keystone auto-update support.
+-            'mac_keystone%': 1,
+-          }, { # else: branding!="Chrome" or buildtype!="Official"
+-            'mac_sdk%': '<!(<(PYTHON) <(DEPTH)/build/mac/find_sdk.py <(mac_sdk_min))',
+-            'mac_breakpad_uploads%': 0,
+-            'mac_breakpad%': 0,
+-            'mac_keystone%': 0,
+-          }],
+-        ],
+-      }],  # OS=="mac"
+-
+-      ['OS=="win"', {
+-        'conditions': [
+-          ['component=="shared_library"', {
+-            'win_use_allocator_shim%': 0,
+-          }],
+-          ['component=="shared_library" and "<(GENERATOR)"=="ninja"', {
+-            # Only enabled by default for ninja because it's buggy in VS.
+-            # Not enabled for component=static_library because some targets
+-            # are too large and the toolchain fails due to the size of the
+-            # .obj files.
+-            'incremental_chrome_dll%': 1,
+-          }],
+-          # Don't do incremental linking for large modules on 32-bit.
+-          ['MSVS_OS_BITS==32', {
+-            'msvs_large_module_debug_link_mode%': '1',  # No
+-          },{
+-            'msvs_large_module_debug_link_mode%': '2',  # Yes
+-          }],
+-          ['MSVS_VERSION=="2010e" or MSVS_VERSION=="2008e" or MSVS_VERSION=="2005e"', {
+-            'msvs_express%': 1,
+-            'secure_atl%': 0,
+-          },{
+-            'msvs_express%': 0,
+-            'secure_atl%': 1,
+-          }],
+-        ],
+-        'nacl_win64_defines': [
+-          # This flag is used to minimize dependencies when building
+-          # Native Client loader for 64-bit Windows.
+-          'NACL_WIN64',
+-        ],
+-      }],
+-
+-      ['os_posix==1 and chromeos==0 and OS!="android"', {
+-        'use_cups%': 1,
+-      }, {
+-        'use_cups%': 0,
+-      }],
+-
+-      # Native Client glibc toolchain is enabled by default except on arm.
+-      ['target_arch=="arm"', {
+-        'disable_glibc%': 1,
+-      }, {
+-        'disable_glibc%': 0,
+-      }],
+-
+-      # Disable SSE2 when building for ARM or MIPS.
+-      ['target_arch=="arm" or target_arch=="mipsel"', {
+-        'disable_sse2%': 1,
+-      }, {
+-        'disable_sse2%': '<(disable_sse2)',
+-      }],
+-
+-      # Set the relative path from this file to the GYP file of the JPEG
+-      # library used by Chromium.
+-      ['use_system_libjpeg==1 or use_libjpeg_turbo==0', {
+-        # Configuration for using the system libjeg is here.
+-        'libjpeg_gyp_path': '../third_party/libjpeg/libjpeg.gyp',
+-      }, {
+-        'libjpeg_gyp_path': '../third_party/libjpeg_turbo/libjpeg.gyp',
+-      }],
+-
+-      # Options controlling the use of GConf (the classic GNOME configuration
+-      # system) and GIO, which contains GSettings (the new GNOME config system).
+-      ['chromeos==1', {
+-        'use_gconf%': 0,
+-        'use_gio%': 0,
+-      }, {
+-        'use_gconf%': 1,
+-        'use_gio%': 1,
+-      }],
+-
+-      # Set up -D and -E flags passed into grit.
+-      ['branding=="Chrome"', {
+-        # TODO(mmoss) The .grd files look for _google_chrome, but for
+-        # consistency they should look for google_chrome_build like C++.
+-        'grit_defines': ['-D', '_google_chrome',
+-                         '-E', 'CHROMIUM_BUILD=google_chrome'],
+-      }, {
+-        'grit_defines': ['-D', '_chromium',
+-                         '-E', 'CHROMIUM_BUILD=chromium'],
+-      }],
+-      ['chromeos==1', {
+-        'grit_defines': ['-D', 'chromeos', '-D', 'scale_factors=2x'],
+-      }],
+-      ['toolkit_views==1', {
+-        'grit_defines': ['-D', 'toolkit_views'],
+-      }],
+-      ['use_aura==1', {
+-        'grit_defines': ['-D', 'use_aura'],
+-      }],
+-      ['use_ash==1', {
+-        'grit_defines': ['-D', 'use_ash'],
+-      }],
+-      ['use_nss==1', {
+-        'grit_defines': ['-D', 'use_nss'],
+-      }],
+-      ['file_manager_extension==1', {
+-        'grit_defines': ['-D', 'file_manager_extension'],
+-      }],
+-      ['remoting==1', {
+-        'grit_defines': ['-D', 'remoting'],
+-      }],
+-      ['use_titlecase_in_grd_files==1', {
+-        'grit_defines': ['-D', 'use_titlecase'],
+-      }],
+-      ['use_third_party_translations==1', {
+-        'grit_defines': ['-D', 'use_third_party_translations'],
+-        'locales': [
+-          'ast', 'bs', 'ca@valencia', 'en-AU', 'eo', 'eu', 'gl', 'hy', 'ia',
+-          'ka', 'ku', 'kw', 'ms', 'ug'
+-        ],
+-      }],
+-      ['OS=="android"', {
+-        'grit_defines': ['-D', 'android'],
+-      }],
+-      ['OS=="mac"', {
+-        'grit_defines': ['-D', 'scale_factors=2x'],
+-      }],
+-      ['OS == "ios"', {
+-        'grit_defines': [
+-          # define for iOS specific resources.
+-          '-D', 'ios',
+-          # iOS uses a whitelist to filter resources.
+-          '-w', '<(DEPTH)/build/ios/grit_whitelist.txt'
+-        ],
+-      }],
+-      ['enable_extensions==1', {
+-        'grit_defines': ['-D', 'enable_extensions'],
+-      }],
+-      ['enable_printing==1', {
+-        'grit_defines': ['-D', 'enable_printing'],
+-      }],
+-      ['enable_themes==1', {
+-        'grit_defines': ['-D', 'enable_themes'],
+-      }],
+-      ['use_oem_wallpaper==1', {
+-        'grit_defines': ['-D', 'use_oem_wallpaper'],
+-      }],
+-      ['clang_use_chrome_plugins==1 and OS!="win"', {
+-        'clang_chrome_plugins_flags': [
+-          '<!@(<(DEPTH)/tools/clang/scripts/plugin_flags.sh)'
+-        ],
+-      }],
+-
+-      ['enable_web_intents_tag==1', {
+-        'grit_defines': ['-D', 'enable_web_intents_tag'],
+-      }],
+-
+-      ['asan==1', {
+-        'clang%': 1,
+-      }],
+-      ['asan==1 and OS=="mac"', {
+-        # See http://crbug.com/145503.
+-        'component': "static_library",
+-      }],
+-      ['tsan==1', {
+-        'clang%': 1,
+-      }],
+-
+-      ['OS=="linux" and clang_type_profiler==1', {
+-        'clang%': 1,
+-        'clang_use_chrome_plugins%': 0,
+-        'make_clang_dir%': 'third_party/llvm-allocated-type/Linux_x64',
+-      }],
+-
+-      # On valgrind bots, override the optimizer settings so we don't inline too
+-      # much and make the stacks harder to figure out.
+-      #
+-      # TODO(rnk): Kill off variables that no one else uses and just implement
+-      # them under a build_for_tool== condition.
+-      ['build_for_tool=="memcheck" or build_for_tool=="tsan"', {
+-        # gcc flags
+-        'mac_debug_optimization': '1',
+-        'mac_release_optimization': '1',
+-        'release_optimize': '1',
+-        'no_gc_sections': 1,
+-        'debug_extra_cflags': '-g -fno-inline -fno-omit-frame-pointer '
+-                              '-fno-builtin -fno-optimize-sibling-calls',
+-        'release_extra_cflags': '-g -fno-inline -fno-omit-frame-pointer '
+-                                '-fno-builtin -fno-optimize-sibling-calls',
+-
+-        # MSVS flags for TSan on Pin and Windows.
+-        'win_debug_RuntimeChecks': '0',
+-        'win_debug_disable_iterator_debugging': '1',
+-        'win_debug_Optimization': '1',
+-        'win_debug_InlineFunctionExpansion': '0',
+-        'win_release_InlineFunctionExpansion': '0',
+-        'win_release_OmitFramePointers': '0',
+-
+-        'linux_use_tcmalloc': 1,
+-        'release_valgrind_build': 1,
+-        'werror': '',
+-        'component': 'static_library',
+-        'use_system_zlib': 0,
+-      }],
+-
+-      # Build tweaks for DrMemory.
+-      # TODO(rnk): Combine with tsan config to share the builder.
+-      # http://crbug.com/108155
+-      ['build_for_tool=="drmemory"', {
+-        # These runtime checks force initialization of stack vars which blocks
+-        # DrMemory's uninit detection.
+-        'win_debug_RuntimeChecks': '0',
+-        # Iterator debugging is slow.
+-        'win_debug_disable_iterator_debugging': '1',
+-        # Try to disable optimizations that mess up stacks in a release build.
+-        'win_release_InlineFunctionExpansion': '0',
+-        'win_release_OmitFramePointers': '0',
+-        # Ditto for debug, to support bumping win_debug_Optimization.
+-        'win_debug_InlineFunctionExpansion': 0,
+-        'win_debug_OmitFramePointers': 0,
+-        # Keep the code under #ifndef NVALGRIND.
+-        'release_valgrind_build': 1,
+-      }],
+-    ],
+-
+-    # List of default apps to install in new profiles.  The first list contains
+-    # the source files as found in svn.  The second list, used only for linux,
+-    # contains the destination location for each of the files.  When a crx
+-    # is added or removed from the list, the chrome/browser/resources/
+-    # default_apps/external_extensions.json file must also be updated.
+-    'default_apps_list': [
+-      'browser/resources/default_apps/external_extensions.json',
+-      'browser/resources/default_apps/gmail.crx',
+-      'browser/resources/default_apps/search.crx',
+-      'browser/resources/default_apps/youtube.crx',
+-      'browser/resources/default_apps/drive.crx',
+-      'browser/resources/default_apps/docs.crx',
+-    ],
+-    'default_apps_list_linux_dest': [
+-      '<(PRODUCT_DIR)/default_apps/external_extensions.json',
+-      '<(PRODUCT_DIR)/default_apps/gmail.crx',
+-      '<(PRODUCT_DIR)/default_apps/search.crx',
+-      '<(PRODUCT_DIR)/default_apps/youtube.crx',
+-      '<(PRODUCT_DIR)/default_apps/drive.crx',
+-      '<(PRODUCT_DIR)/default_apps/docs.crx',
+-    ],
+-  },
+-  'target_defaults': {
+-    'variables': {
+-      # The condition that operates on chromium_code is in a target_conditions
+-      # section, and will not have access to the default fallback value of
+-      # chromium_code at the top of this file, or to the chromium_code
+-      # variable placed at the root variables scope of .gyp files, because
+-      # those variables are not set at target scope.  As a workaround,
+-      # if chromium_code is not set at target scope, define it in target scope
+-      # to contain whatever value it has during early variable expansion.
+-      # That's enough to make it available during target conditional
+-      # processing.
+-      'chromium_code%': '<(chromium_code)',
+-
+-      # See http://msdn.microsoft.com/en-us/library/aa652360(VS.71).aspx
+-      'win_release_Optimization%': '2', # 2 = /Os
+-      'win_debug_Optimization%': '0',   # 0 = /Od
+-
+-      # See http://msdn.microsoft.com/en-us/library/2kxx5t2c(v=vs.80).aspx
+-      # Tri-state: blank is default, 1 on, 0 off
+-      'win_release_OmitFramePointers%': '0',
+-      # Tri-state: blank is default, 1 on, 0 off
+-      'win_debug_OmitFramePointers%': '',
+-
+-      # See http://msdn.microsoft.com/en-us/library/8wtf2dfz(VS.71).aspx
+-      'win_debug_RuntimeChecks%': '3',    # 3 = all checks enabled, 0 = off
+-
+-      # See http://msdn.microsoft.com/en-us/library/47238hez(VS.71).aspx
+-      'win_debug_InlineFunctionExpansion%': '',    # empty = default, 0 = off,
+-      'win_release_InlineFunctionExpansion%': '2', # 1 = only __inline, 2 = max
+-
+-      # VS inserts quite a lot of extra checks to algorithms like
+-      # std::partial_sort in Debug build which make them O(N^2)
+-      # instead of O(N*logN). This is particularly slow under memory
+-      # tools like ThreadSanitizer so we want it to be disablable.
+-      # See http://msdn.microsoft.com/en-us/library/aa985982(v=VS.80).aspx
+-      'win_debug_disable_iterator_debugging%': '0',
+-
+-      'release_extra_cflags%': '',
+-      'debug_extra_cflags%': '',
+-
+-      'release_valgrind_build%': '<(release_valgrind_build)',
+-
+-      # the non-qualified versions are widely assumed to be *nix-only
+-      'win_release_extra_cflags%': '',
+-      'win_debug_extra_cflags%': '',
+-
+-      # TODO(thakis): Make this a blacklist instead, http://crbug.com/101600
+-      'enable_wexit_time_destructors%': '<(enable_wexit_time_destructors)',
+-
+-      # Only used by Windows build for now.  Can be used to build into a
+-      # differet output directory, e.g., a build_dir_prefix of VS2010_ would
+-      # output files in src/build/VS2010_{Debug,Release}.
+-      'build_dir_prefix%': '',
+-
+-      # Targets are by default not nacl untrusted code.
+-      'nacl_untrusted_build%': 0,
+-
+-      'conditions': [
+-        ['OS=="win" and component=="shared_library"', {
+-          # See http://msdn.microsoft.com/en-us/library/aa652367.aspx
+-          'win_release_RuntimeLibrary%': '2', # 2 = /MD (nondebug DLL)
+-          'win_debug_RuntimeLibrary%': '3',   # 3 = /MDd (debug DLL)
+-        }, {
+-          # See http://msdn.microsoft.com/en-us/library/aa652367.aspx
+-          'win_release_RuntimeLibrary%': '0', # 0 = /MT (nondebug static)
+-          'win_debug_RuntimeLibrary%': '1',   # 1 = /MTd (debug static)
+-        }],
+-        ['OS=="ios"', {
+-          # See http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Optimize-Options.html
+-          'mac_release_optimization%': 's', # Use -Os unless overridden
+-          'mac_debug_optimization%': '0',   # Use -O0 unless overridden
+-        }, {
+-          # See http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Optimize-Options.html
+-          'mac_release_optimization%': '3', # Use -O3 unless overridden
+-          'mac_debug_optimization%': '0',   # Use -O0 unless overridden
+-        }],
+-      ],
+-    },
+-    'conditions': [
+-      ['OS=="linux" and linux_use_tcmalloc==1 and clang_type_profiler==1', {
+-        'cflags_cc!': ['-fno-rtti'],
+-        'cflags_cc+': [
+-          '-frtti',
+-          '-gline-tables-only',
+-          '-fintercept-allocation-functions',
+-        ],
+-        'defines': ['TYPE_PROFILING'],
+-        'dependencies': [
+-          '<(DEPTH)/base/allocator/allocator.gyp:type_profiler',
+-        ],
+-      }],
+-      ['OS=="win" and "<(msbuild_toolset)"!=""', {
+-        'msbuild_toolset': '<(msbuild_toolset)',
+-      }],
+-      ['branding=="Chrome"', {
+-        'defines': ['GOOGLE_CHROME_BUILD'],
+-      }, {  # else: branding!="Chrome"
+-        'defines': ['CHROMIUM_BUILD'],
+-      }],
+-      ['OS=="mac" and component=="shared_library"', {
+-        'xcode_settings': {
+-          'DYLIB_INSTALL_NAME_BASE': '@rpath',
+-          'LD_RUNPATH_SEARCH_PATHS': [
+-            # For unbundled binaries.
+-            '@loader_path/.',
+-            # For bundled binaries, to get back from Binary.app/Contents/MacOS.
+-            '@loader_path/../../..',
+-          ],
+-        },
+-      }],
+-      ['branding=="Chrome" and (OS=="win" or OS=="mac")', {
+-        'defines': ['ENABLE_RLZ'],
+-      }],
+-      ['component=="shared_library"', {
+-        'defines': ['COMPONENT_BUILD'],
+-      }],
+-      ['toolkit_views==1', {
+-        'defines': ['TOOLKIT_VIEWS=1'],
+-      }],
+-      ['ui_compositor_image_transport==1', {
+-        'defines': ['UI_COMPOSITOR_IMAGE_TRANSPORT'],
+-      }],
+-      ['use_aura==1', {
+-        'defines': ['USE_AURA=1'],
+-      }],
+-      ['use_ash==1', {
+-        'defines': ['USE_ASH=1'],
+-      }],
+-      ['use_libjpeg_turbo==1', {
+-        'defines': ['USE_LIBJPEG_TURBO=1'],
+-      }],
+-      ['use_nss==1', {
+-        'defines': ['USE_NSS=1'],
+-      }],
+-      ['enable_one_click_signin==1', {
+-        'defines': ['ENABLE_ONE_CLICK_SIGNIN'],
+-      }],
+-      ['toolkit_uses_gtk==1 and toolkit_views==0', {
+-        # TODO(erg): We are progressively sealing up use of deprecated features
+-        # in gtk in preparation for an eventual porting to gtk3.
+-        'defines': ['GTK_DISABLE_SINGLE_INCLUDES=1'],
+-      }],
+-      ['chromeos==1', {
+-        'defines': ['OS_CHROMEOS=1'],
+-      }],
+-      ['use_xi2_mt!=0', {
+-        'defines': ['USE_XI2_MT=<(use_xi2_mt)'],
+-      }],
+-      ['file_manager_extension==1', {
+-        'defines': ['FILE_MANAGER_EXTENSION=1'],
+-      }],
+-      ['profiling==1', {
+-        'defines': ['ENABLE_PROFILING=1'],
+-      }],
+-      ['OS=="linux" and glibcxx_debug==1', {
+-        'defines': ['_GLIBCXX_DEBUG=1',],
+-        'cflags_cc!': ['-fno-rtti'],
+-        'cflags_cc+': ['-frtti', '-g'],
+-      }],
+-      ['OS=="linux"', {
+-        # we need lrint(), which is ISOC99, and Xcode
+-	# already forces -std=c99 for mac below
+-        'defines': ['_ISOC99_SOURCE=1'],
+-      }],
+-      ['remoting==1', {
+-        'defines': ['ENABLE_REMOTING=1'],
+-      }],
+-      ['enable_webrtc==1', {
+-        'defines': ['ENABLE_WEBRTC=1'],
+-      }],
+-      ['proprietary_codecs==1', {
+-        'defines': ['USE_PROPRIETARY_CODECS'],
+-      }],
+-      ['enable_pepper_threading==1', {
+-        'defines': ['ENABLE_PEPPER_THREADING'],
+-      }],
+-      ['enable_viewport==1', {
+-        'defines': ['ENABLE_VIEWPORT'],
+-      }],
+-      ['configuration_policy==1', {
+-        'defines': ['ENABLE_CONFIGURATION_POLICY'],
+-      }],
+-      ['input_speech==1', {
+-        'defines': ['ENABLE_INPUT_SPEECH'],
+-      }],
+-      ['notifications==1', {
+-        'defines': ['ENABLE_NOTIFICATIONS'],
+-      }],
+-      ['enable_hidpi==1', {
+-        'defines': ['ENABLE_HIDPI=1'],
+-      }],
+-      ['fastbuild!=0', {
+-
+-        'conditions': [
+-          # For Windows and Mac, we don't genererate debug information.
+-          ['OS=="win" or OS=="mac"', {
+-            'msvs_settings': {
+-              'VCLinkerTool': {
+-                'GenerateDebugInformation': 'false',
+-              },
+-              'VCCLCompilerTool': {
+-                'DebugInformationFormat': '0',
+-              }
+-            },
+-            'xcode_settings': {
+-              'GCC_GENERATE_DEBUGGING_SYMBOLS': 'NO',
+-            },
+-          }, { # else: OS != "win", generate less debug information.
+-            'variables': {
+-              'debug_extra_cflags': '-g1',
+-            },
+-          }],
+-          # Clang creates chubby debug information, which makes linking very
+-          # slow. For now, don't create debug information with clang.  See
+-          # http://crbug.com/70000
+-          ['(OS=="linux" or OS=="android") and clang==1', {
+-            'variables': {
+-              'debug_extra_cflags': '-g0',
+-            },
+-          }],
+-        ],  # conditions for fastbuild.
+-      }],  # fastbuild!=0
+-      ['dcheck_always_on!=0', {
+-        'defines': ['DCHECK_ALWAYS_ON=1'],
+-      }],  # dcheck_always_on!=0
+-      ['selinux==1', {
+-        'defines': ['CHROMIUM_SELINUX=1'],
+-      }],
+-      ['win_use_allocator_shim==0', {
+-        'conditions': [
+-          ['OS=="win"', {
+-            'defines': ['NO_TCMALLOC'],
+-          }],
+-        ],
+-      }],
+-      ['enable_gpu==1', {
+-        'defines': [
+-          'ENABLE_GPU=1',
+-        ],
+-      }],
+-      ['use_openssl==1', {
+-        'defines': [
+-          'USE_OPENSSL=1',
+-        ],
+-      }],
+-      ['enable_eglimage==1', {
+-        'defines': [
+-          'ENABLE_EGLIMAGE=1',
+-        ],
+-      }],
+-      ['use_skia==1', {
+-        'defines': [
+-          'USE_SKIA=1',
+-        ],
+-      }],
+-      ['coverage!=0', {
+-        'conditions': [
+-          ['OS=="mac" or OS=="ios"', {
+-            'xcode_settings': {
+-              'GCC_INSTRUMENT_PROGRAM_FLOW_ARCS': 'YES',  # -fprofile-arcs
+-              'GCC_GENERATE_TEST_COVERAGE_FILES': 'YES',  # -ftest-coverage
+-            },
+-          }],
+-          ['OS=="mac"', {
+-            # Add -lgcov for types executable, shared_library, and
+-            # loadable_module; not for static_library.
+-            # This is a delayed conditional.
+-            'target_conditions': [
+-              ['_type!="static_library"', {
+-                'xcode_settings': { 'OTHER_LDFLAGS': [ '-lgcov' ] },
+-              }],
+-            ],
+-          }],
+-          ['OS=="linux" or OS=="android"', {
+-            'cflags': [ '-ftest-coverage',
+-                        '-fprofile-arcs' ],
+-            'link_settings': { 'libraries': [ '-lgcov' ] },
+-          }],
+-          # Finally, for Windows, we simply turn on profiling.
+-          ['OS=="win"', {
+-            'msvs_settings': {
+-              'VCLinkerTool': {
+-                'Profile': 'true',
+-              },
+-              'VCCLCompilerTool': {
+-                # /Z7, not /Zi, so coverage is happyb
+-                'DebugInformationFormat': '1',
+-                'AdditionalOptions': ['/Yd'],
+-              }
+-            }
+-         }],  # OS==win
+-        ],  # conditions for coverage
+-      }],  # coverage!=0
+-      ['OS=="win"', {
+-        'defines': [
+-          '__STD_C',
+-          '_CRT_SECURE_NO_DEPRECATE',
+-          '_SCL_SECURE_NO_DEPRECATE',
+-        ],
+-        'include_dirs': [
+-          '<(DEPTH)/third_party/wtl/include',
+-        ],
+-        'conditions': [
+-          ['win_z7!=0', {
+-            'msvs_settings': {
+-              # Generates debug info when win_z7=1
+-              # even if fastbuild=1 (that makes GenerateDebugInformation false).
+-              'VCLinkerTool': {
+-                'GenerateDebugInformation': 'true',
+-              },
+-              'VCCLCompilerTool': {
+-                'DebugInformationFormat': '1',
+-              }
+-            }
+-          }],
+-        ],  # win_z7!=0
+-      }],  # OS==win
+-      ['enable_task_manager==1', {
+-        'defines': [
+-          'ENABLE_TASK_MANAGER=1',
+-        ],
+-      }],
+-      ['enable_web_intents==1', {
+-        'defines': [
+-          'ENABLE_WEB_INTENTS=1',
+-        ],
+-      }],
+-      ['enable_extensions==1', {
+-        'defines': [
+-          'ENABLE_EXTENSIONS=1',
+-        ],
+-      }],
+-      ['OS=="win" and branding=="Chrome"', {
+-        'defines': ['ENABLE_SWIFTSHADER'],
+-      }],
+-      ['enable_dart==1', {
+-        'defines': ['WEBKIT_USING_DART=1'],
+-      }],
+-      ['enable_plugin_installation==1', {
+-        'defines': ['ENABLE_PLUGIN_INSTALLATION=1'],
+-      }],
+-      ['enable_protector_service==1', {
+-        'defines': ['ENABLE_PROTECTOR_SERVICE=1'],
+-      }],
+-      ['enable_session_service==1', {
+-        'defines': ['ENABLE_SESSION_SERVICE=1'],
+-      }],
+-      ['enable_themes==1', {
+-        'defines': ['ENABLE_THEMES=1'],
+-      }],
+-      ['enable_background==1', {
+-        'defines': ['ENABLE_BACKGROUND=1'],
+-      }],
+-      ['enable_automation==1', {
+-        'defines': ['ENABLE_AUTOMATION=1'],
+-      }],
+-      ['enable_printing==1', {
+-        'defines': ['ENABLE_PRINTING=1'],
+-      }],
+-      ['enable_captive_portal_detection==1', {
+-        'defines': ['ENABLE_CAPTIVE_PORTAL_DETECTION=1'],
+-      }],
+-      ['disable_ftp_support==1', {
+-        'defines': ['DISABLE_FTP_SUPPORT=1'],
+-      }],
+-    ],  # conditions for 'target_defaults'
+-    'target_conditions': [
+-      ['enable_wexit_time_destructors==1', {
+-        'conditions': [
+-          [ 'clang==1', {
+-            'cflags': [
+-              '-Wexit-time-destructors',
+-            ],
+-            'xcode_settings': {
+-              'WARNING_CFLAGS': [
+-                '-Wexit-time-destructors',
+-              ],
+-            },
+-          }],
+-        ],
+-      }],
+-      ['chromium_code==0', {
+-        'conditions': [
+-          [ 'os_posix==1 and OS!="mac" and OS!="ios"', {
+-            # We don't want to get warnings from third-party code,
+-            # so remove any existing warning-enabling flags like -Wall.
+-            'cflags!': [
+-              '-Wall',
+-              '-Wextra',
+-            ],
+-            'cflags_cc': [
+-              # Don't warn about hash_map in third-party code.
+-              '-Wno-deprecated',
+-            ],
+-            'cflags': [
+-              # Don't warn about printf format problems.
+-              # This is off by default in gcc but on in Ubuntu's gcc(!).
+-              '-Wno-format',
+-            ],
+-            'cflags_cc!': [
+-              # TODO(fischman): remove this.
+-              # http://code.google.com/p/chromium/issues/detail?id=90453
+-              '-Wsign-compare',
+-            ]
+-          }],
+-          # TODO: Fix all warnings on chromeos too.
+-          [ 'os_posix==1 and OS!="mac" and OS!="ios" and (clang!=1 or chromeos==1)', {
+-            'cflags!': [
+-              '-Werror',
+-            ],
+-          }],
+-          [ 'os_posix==1 and os_bsd!=1 and OS!="mac" and OS!="android"', {
+-            'cflags': [
+-              # Don't warn about ignoring the return value from e.g. close().
+-              # This is off by default in some gccs but on by default in others.
+-              # BSD systems do not support this option, since they are usually
+-              # using gcc 4.2.1, which does not have this flag yet.
+-              '-Wno-unused-result',
+-            ],
+-          }],
+-          [ 'OS=="win"', {
+-            'defines': [
+-              '_CRT_SECURE_NO_DEPRECATE',
+-              '_CRT_NONSTDC_NO_WARNINGS',
+-              '_CRT_NONSTDC_NO_DEPRECATE',
+-              '_SCL_SECURE_NO_DEPRECATE',
+-            ],
+-            'msvs_disabled_warnings': [4800],
+-            'msvs_settings': {
+-              'VCCLCompilerTool': {
+-                'WarningLevel': '3',
+-                'WarnAsError': '<(win_third_party_warn_as_error)',
+-                'Detect64BitPortabilityProblems': 'false',
+-              },
+-            },
+-            'conditions': [
+-              ['buildtype=="Official"', {
+-                'msvs_settings': {
+-                  'VCCLCompilerTool': { 'WarnAsError': 'false' },
+-                }
+-              }],
+-            ],
+-          }],
+-          # TODO(darin): Unfortunately, some third_party code depends on base/
+-          [ 'OS=="win" and component=="shared_library"', {
+-            'msvs_disabled_warnings': [
+-              4251,  # class 'std::xx' needs to have dll-interface.
+-            ],
+-          }],
+-          [ 'OS=="mac" or OS=="ios"', {
+-            'xcode_settings': {
+-              'WARNING_CFLAGS!': ['-Wall', '-Wextra'],
+-            },
+-            'conditions': [
+-              ['buildtype=="Official"', {
+-                'xcode_settings': {
+-                  'GCC_TREAT_WARNINGS_AS_ERRORS': 'NO',    # -Werror
+-                },
+-              }],
+-            ],
+-          }],
+-          [ 'OS=="ios"', {
+-            'xcode_settings': {
+-              # TODO(ios): Fix remaining warnings in third-party code, then
+-              # remove this; the Mac cleanup didn't get everything that's
+-              # flagged in an iOS build.
+-              'GCC_TREAT_WARNINGS_AS_ERRORS': 'NO',
+-              'RUN_CLANG_STATIC_ANALYZER': 'NO',
+-            },
+-          }],
+-        ],
+-      }, {
+-        'includes': [
+-           # Rules for excluding e.g. foo_win.cc from the build on non-Windows.
+-          'filename_rules.gypi',
+-        ],
+-        # In Chromium code, we define __STDC_FORMAT_MACROS in order to get the
+-        # C99 macros on Mac and Linux.
+-        'defines': [
+-          '__STDC_FORMAT_MACROS',
+-        ],
+-        'conditions': [
+-          ['OS=="win"', {
+-            # turn on warnings for signed/unsigned mismatch on chromium code.
+-            'msvs_settings': {
+-              'VCCLCompilerTool': {
+-                'AdditionalOptions': ['/we4389'],
+-              },
+-            },
+-          }],
+-          ['OS=="win" and component=="shared_library"', {
+-            'msvs_disabled_warnings': [
+-              4251,  # class 'std::xx' needs to have dll-interface.
+-            ],
+-          }],
+-        ],
+-      }],
+-    ],  # target_conditions for 'target_defaults'
+-    'default_configuration': 'Debug',
+-    'configurations': {
+-      # VCLinkerTool LinkIncremental values below:
+-      #   0 == default
+-      #   1 == /INCREMENTAL:NO
+-      #   2 == /INCREMENTAL
+-      # Debug links incremental, Release does not.
+-      #
+-      # Abstract base configurations to cover common attributes.
+-      #
+-      'Common_Base': {
+-        'abstract': 1,
+-        'msvs_configuration_attributes': {
+-          'OutputDirectory': '<(DEPTH)\\build\\<(build_dir_prefix)$(ConfigurationName)',
+-          'IntermediateDirectory': '$(OutDir)\\obj\\$(ProjectName)',
+-          'CharacterSet': '1',
+-        },
+-      },
+-      'x86_Base': {
+-        'abstract': 1,
+-        'msvs_settings': {
+-          'VCLinkerTool': {
+-            'TargetMachine': '1',
+-          },
+-        },
+-        'msvs_configuration_platform': 'Win32',
+-      },
+-      'x64_Base': {
+-        'abstract': 1,
+-        'msvs_configuration_platform': 'x64',
+-        'msvs_settings': {
+-          'VCLinkerTool': {
+-            'TargetMachine': '17', # x86 - 64
+-            'AdditionalLibraryDirectories!':
+-              ['<(windows_sdk_path)/Lib/win8/um/x86'],
+-            'AdditionalLibraryDirectories':
+-              ['<(windows_sdk_path)/Lib/win8/um/x64'],
+-          },
+-          'VCLibrarianTool': {
+-            'AdditionalLibraryDirectories!':
+-              ['<(windows_sdk_path)/Lib/win8/um/x86'],
+-            'AdditionalLibraryDirectories':
+-              ['<(windows_sdk_path)/Lib/win8/um/x64'],
+-          },
+-        },
+-        'defines': [
+-          # Not sure if tcmalloc works on 64-bit Windows.
+-          'NO_TCMALLOC',
+-        ],
+-      },
+-      'Debug_Base': {
+-        'abstract': 1,
+-        'defines': [
+-          'DYNAMIC_ANNOTATIONS_ENABLED=1',
+-          'WTF_USE_DYNAMIC_ANNOTATIONS=1',
+-        ],
+-        'xcode_settings': {
+-          'COPY_PHASE_STRIP': 'NO',
+-          'GCC_OPTIMIZATION_LEVEL': '<(mac_debug_optimization)',
+-          'OTHER_CFLAGS': [
+-            '<@(debug_extra_cflags)',
+-          ],
+-        },
+-        'msvs_settings': {
+-          'VCCLCompilerTool': {
+-            'Optimization': '<(win_debug_Optimization)',
+-            'PreprocessorDefinitions': ['_DEBUG'],
+-            'BasicRuntimeChecks': '<(win_debug_RuntimeChecks)',
+-            'RuntimeLibrary': '<(win_debug_RuntimeLibrary)',
+-            'conditions': [
+-              # According to MSVS, InlineFunctionExpansion=0 means
+-              # "default inlining", not "/Ob0".
+-              # Thus, we have to handle InlineFunctionExpansion==0 separately.
+-              ['win_debug_InlineFunctionExpansion==0', {
+-                'AdditionalOptions': ['/Ob0'],
+-              }],
+-              ['win_debug_InlineFunctionExpansion!=""', {
+-                'InlineFunctionExpansion':
+-                  '<(win_debug_InlineFunctionExpansion)',
+-              }],
+-              ['win_debug_disable_iterator_debugging==1', {
+-                'PreprocessorDefinitions': ['_HAS_ITERATOR_DEBUGGING=0'],
+-              }],
+-
+-              # if win_debug_OmitFramePointers is blank, leave as default
+-              ['win_debug_OmitFramePointers==1', {
+-                'OmitFramePointers': 'true',
+-              }],
+-              ['win_debug_OmitFramePointers==0', {
+-                'OmitFramePointers': 'false',
+-                # The above is not sufficient (http://crbug.com/106711): it
+-                # simply eliminates an explicit "/Oy", but both /O2 and /Ox
+-                # perform FPO regardless, so we must explicitly disable.
+-                # We still want the false setting above to avoid having
+-                # "/Oy /Oy-" and warnings about overriding.
+-                'AdditionalOptions': ['/Oy-'],
+-              }],
+-            ],
+-            'AdditionalOptions': [ '<@(win_debug_extra_cflags)', ],
+-          },
+-          'VCLinkerTool': {
+-            'LinkIncremental': '<(msvs_debug_link_incremental)',
+-            # ASLR makes debugging with windbg difficult because Chrome.exe and
+-            # Chrome.dll share the same base name. As result, windbg will
+-            # name the Chrome.dll module like chrome_<base address>, where
+-            # <base address> typically changes with each launch. This in turn
+-            # means that breakpoints in Chrome.dll don't stick from one launch
+-            # to the next. For this reason, we turn ASLR off in debug builds.
+-            # Note that this is a three-way bool, where 0 means to pick up
+-            # the default setting, 1 is off and 2 is on.
+-            'RandomizedBaseAddress': 1,
+-          },
+-          'VCResourceCompilerTool': {
+-            'PreprocessorDefinitions': ['_DEBUG'],
+-          },
+-        },
+-        'conditions': [
+-          ['OS=="linux" or OS=="android"', {
+-            'target_conditions': [
+-              ['_toolset=="target"', {
+-                'cflags': [
+-                  '<@(debug_extra_cflags)',
+-                ],
+-              }],
+-            ],
+-          }],
+-          # Disabled on iOS because it was causing a crash on startup.
+-          # TODO(michelea): investigate, create a reduced test and possibly
+-          # submit a radar.
+-          ['release_valgrind_build==0 and OS!="ios"', {
+-            'xcode_settings': {
+-              'OTHER_CFLAGS': [
+-                '-fstack-protector-all',  # Implies -fstack-protector
+-              ],
+-            },
+-          }],
+-        ],
+-      },
+-      'Release_Base': {
+-        'abstract': 1,
+-        'defines': [
+-          'NDEBUG',
+-        ],
+-        'xcode_settings': {
+-          'DEAD_CODE_STRIPPING': 'YES',  # -Wl,-dead_strip
+-          'GCC_OPTIMIZATION_LEVEL': '<(mac_release_optimization)',
+-          'OTHER_CFLAGS': [ '<@(release_extra_cflags)', ],
+-        },
+-        'msvs_settings': {
+-          'VCCLCompilerTool': {
+-            'RuntimeLibrary': '<(win_release_RuntimeLibrary)',
+-            'conditions': [
+-              # In official builds, each target will self-select
+-              # an optimization level.
+-              ['buildtype!="Official"', {
+-                  'Optimization': '<(win_release_Optimization)',
+-                },
+-              ],
+-              # According to MSVS, InlineFunctionExpansion=0 means
+-              # "default inlining", not "/Ob0".
+-              # Thus, we have to handle InlineFunctionExpansion==0 separately.
+-              ['win_release_InlineFunctionExpansion==0', {
+-                'AdditionalOptions': ['/Ob0'],
+-              }],
+-              ['win_release_InlineFunctionExpansion!=""', {
+-                'InlineFunctionExpansion':
+-                  '<(win_release_InlineFunctionExpansion)',
+-              }],
+-
+-              # if win_release_OmitFramePointers is blank, leave as default
+-              ['win_release_OmitFramePointers==1', {
+-                'OmitFramePointers': 'true',
+-              }],
+-              ['win_release_OmitFramePointers==0', {
+-                'OmitFramePointers': 'false',
+-                # The above is not sufficient (http://crbug.com/106711): it
+-                # simply eliminates an explicit "/Oy", but both /O2 and /Ox
+-                # perform FPO regardless, so we must explicitly disable.
+-                # We still want the false setting above to avoid having
+-                # "/Oy /Oy-" and warnings about overriding.
+-                'AdditionalOptions': ['/Oy-'],
+-              }],
+-            ],
+-            'AdditionalOptions': [ '<@(win_release_extra_cflags)', ],
+-          },
+-          'VCLinkerTool': {
+-            # LinkIncremental is a tri-state boolean, where 0 means default
+-            # (i.e., inherit from parent solution), 1 means false, and
+-            # 2 means true.
+-            'LinkIncremental': '1',
+-            # This corresponds to the /PROFILE flag which ensures the PDB
+-            # file contains FIXUP information (growing the PDB file by about
+-            # 5%) but does not otherwise alter the output binary. This
+-            # information is used by the Syzygy optimization tool when
+-            # decomposing the release image.
+-            'Profile': 'true',
+-          },
+-        },
+-        'conditions': [
+-          ['msvs_use_common_release', {
+-            'includes': ['release.gypi'],
+-          }],
+-          ['release_valgrind_build==0', {
+-            'defines': [
+-              'NVALGRIND',
+-              'DYNAMIC_ANNOTATIONS_ENABLED=0',
+-            ],
+-          }, {
+-            'defines': [
+-              'DYNAMIC_ANNOTATIONS_ENABLED=1',
+-              'WTF_USE_DYNAMIC_ANNOTATIONS=1',
+-            ],
+-          }],
+-          ['win_use_allocator_shim==0', {
+-            'defines': ['NO_TCMALLOC'],
+-          }],
+-          ['OS=="linux"', {
+-            'target_conditions': [
+-              ['_toolset=="target"', {
+-                'cflags': [
+-                  '<@(release_extra_cflags)',
+-                ],
+-              }],
+-            ],
+-          }],
+-        ],
+-      },
+-      #
+-      # Concrete configurations
+-      #
+-      'Debug': {
+-        'inherit_from': ['Common_Base', 'x86_Base', 'Debug_Base'],
+-      },
+-      'Release': {
+-        'inherit_from': ['Common_Base', 'x86_Base', 'Release_Base'],
+-      },
+-      'conditions': [
+-        [ 'OS=="win"', {
+-          # TODO(bradnelson): add a gyp mechanism to make this more graceful.
+-          'Debug_x64': {
+-            'inherit_from': ['Common_Base', 'x64_Base', 'Debug_Base'],
+-          },
+-          'Release_x64': {
+-            'inherit_from': ['Common_Base', 'x64_Base', 'Release_Base'],
+-          },
+-        }],
+-      ],
+-    },
+-  },
+-  'conditions': [
+-    ['os_posix==1 and OS!="mac" and OS!="ios"', {
+-      'target_defaults': {
+-        # Enable -Werror by default, but put it in a variable so it can
+-        # be disabled in ~/.gyp/include.gypi on the valgrind builders.
+-        'variables': {
+-          'werror%': '-Werror',
+-          'libraries_for_target%': '',
+-        },
+-        'defines': [
+-          '_FILE_OFFSET_BITS=64',
+-        ],
+-        'cflags': [
+-          '<(werror)',  # See note above about the werror variable.
+-          '-pthread',
+-          '-fno-exceptions',
+-          '-fno-strict-aliasing',  # See http://crbug.com/32204
+-          '-Wall',
+-          # TODO(evan): turn this back on once all the builds work.
+-          # '-Wextra',
+-          # Don't warn about unused function params.  We use those everywhere.
+-          '-Wno-unused-parameter',
+-          # Don't warn about the "struct foo f = {0};" initialization pattern.
+-          '-Wno-missing-field-initializers',
+-          # Don't export any symbols (for example, to plugins we dlopen()).
+-          # Note: this is *required* to make some plugins work.
+-          '-fvisibility=hidden',
+-          '-pipe',
+-        ],
+-        'cflags_cc': [
+-          '-fno-rtti',
+-          '-fno-threadsafe-statics',
+-          # Make inline functions have hidden visiblity by default.
+-          # Surprisingly, not covered by -fvisibility=hidden.
+-          '-fvisibility-inlines-hidden',
+-          # GCC turns on -Wsign-compare for C++ under -Wall, but clang doesn't,
+-          # so we specify it explicitly.
+-          # TODO(fischman): remove this if http://llvm.org/PR10448 obsoletes it.
+-          # http://code.google.com/p/chromium/issues/detail?id=90453
+-          '-Wsign-compare',
+-        ],
+-        'ldflags': [
+-          '-pthread', '-Wl,-z,noexecstack',
+-        ],
+-        'libraries' : [
+-          '<(libraries_for_target)',
+-        ],
+-        'configurations': {
+-          'Debug_Base': {
+-            'variables': {
+-              'debug_optimize%': '0',
+-            },
+-            'defines': [
+-              '_DEBUG',
+-            ],
+-            'cflags': [
+-              '-O>(debug_optimize)',
+-              '-g',
+-            ],
+-            'conditions' : [
+-              ['OS=="android" and android_full_debug==0', {
+-                # Some configurations are copied from Release_Base to reduce
+-                # the binary size.
+-                'variables': {
+-                  'debug_optimize%': 's',
+-                },
+-                'cflags': [
+-                  '-fomit-frame-pointer',
+-                  '-fdata-sections',
+-                  '-ffunction-sections',
+-                ],
+-                'ldflags': [
+-                  '-Wl,-O1',
+-                  '-Wl,--as-needed',
+-                  '-Wl,--gc-sections',
+-                ],
+-              }],
+-            ],
+-          },
+-          'Release_Base': {
+-            'variables': {
+-              'release_optimize%': '2',
+-              # Binaries become big and gold is unable to perform GC
+-              # and remove unused sections for some of test targets
+-              # on 32 bit platform.
+-              # (This is currently observed only in chromeos valgrind bots)
+-              # The following flag is to disable --gc-sections linker
+-              # option for these bots.
+-              'no_gc_sections%': 0,
+-
+-              # TODO(bradnelson): reexamine how this is done if we change the
+-              # expansion of configurations
+-              'release_valgrind_build%': 0,
+-            },
+-            'cflags': [
+-              '-O<(release_optimize)',
+-              # Don't emit the GCC version ident directives, they just end up
+-              # in the .comment section taking up binary size.
+-              '-fno-ident',
+-              # Put data and code in their own sections, so that unused symbols
+-              # can be removed at link time with --gc-sections.
+-              '-fdata-sections',
+-              '-ffunction-sections',
+-            ],
+-            'ldflags': [
+-              # Specifically tell the linker to perform optimizations.
+-              # See http://lwn.net/Articles/192624/ .
+-              '-Wl,-O1',
+-              '-Wl,--as-needed',
+-            ],
+-            'conditions' : [
+-              ['no_gc_sections==0', {
+-                'ldflags': [
+-                  '-Wl,--gc-sections',
+-                ],
+-              }],
+-              ['OS=="android"', {
+-                'variables': {
+-                  'release_optimize%': 's',
+-                },
+-                'cflags': [
+-                  '-fomit-frame-pointer',
+-                ],
+-              }],
+-              ['clang==1', {
+-                'cflags!': [
+-                  '-fno-ident',
+-                ],
+-              }],
+-              ['profiling==1', {
+-                'cflags': [
+-                  '-fno-omit-frame-pointer',
+-                  '-g',
+-                ],
+-              }],
+-            ],
+-          },
+-        },
+-        'variants': {
+-          'coverage': {
+-            'cflags': ['-fprofile-arcs', '-ftest-coverage'],
+-            'ldflags': ['-fprofile-arcs'],
+-          },
+-          'profile': {
+-            'cflags': ['-pg', '-g'],
+-            'ldflags': ['-pg'],
+-          },
+-          'symbols': {
+-            'cflags': ['-g'],
+-          },
+-        },
+-        'conditions': [
+-          ['target_arch=="ia32"', {
+-            'target_conditions': [
+-              ['_toolset=="target"', {
+-                'asflags': [
+-                  # Needed so that libs with .s files (e.g. libicudata.a)
+-                  # are compatible with the general 32-bit-ness.
+-                  '-32',
+-                ],
+-                # All floating-point computations on x87 happens in 80-bit
+-                # precision.  Because the C and C++ language standards allow
+-                # the compiler to keep the floating-point values in higher
+-                # precision than what's specified in the source and doing so
+-                # is more efficient than constantly rounding up to 64-bit or
+-                # 32-bit precision as specified in the source, the compiler,
+-                # especially in the optimized mode, tries very hard to keep
+-                # values in x87 floating-point stack (in 80-bit precision)
+-                # as long as possible. This has important side effects, that
+-                # the real value used in computation may change depending on
+-                # how the compiler did the optimization - that is, the value
+-                # kept in 80-bit is different than the value rounded down to
+-                # 64-bit or 32-bit. There are possible compiler options to
+-                # make this behavior consistent (e.g. -ffloat-store would keep
+-                # all floating-values in the memory, thus force them to be
+-                # rounded to its original precision) but they have significant
+-                # runtime performance penalty.
+-                #
+-                # -mfpmath=sse -msse2 makes the compiler use SSE instructions
+-                # which keep floating-point values in SSE registers in its
+-                # native precision (32-bit for single precision, and 64-bit
+-                # for double precision values). This means the floating-point
+-                # value used during computation does not change depending on
+-                # how the compiler optimized the code, since the value is
+-                # always kept in its specified precision.
+-                'conditions': [
+-                  ['branding=="Chromium" and disable_sse2==0', {
+-                    'cflags': [
+-                      '-march=pentium4',
+-                      '-msse2',
+-                      '-mfpmath=sse',
+-                    ],
+-                  }],
+-                  # ChromeOS targets Pinetrail, which is sse3, but most of the
+-                  # benefit comes from sse2 so this setting allows ChromeOS
+-                  # to build on other CPUs.  In the future -march=atom would
+-                  # help but requires a newer compiler.
+-                  ['chromeos==1 and disable_sse2==0', {
+-                    'cflags': [
+-                      '-msse2',
+-                    ],
+-                  }],
+-                  # Install packages have started cropping up with
+-                  # different headers between the 32-bit and 64-bit
+-                  # versions, so we have to shadow those differences off
+-                  # and make sure a 32-bit-on-64-bit build picks up the
+-                  # right files.
+-                  # For android build, use NDK headers instead of host headers
+-                  ['host_arch!="ia32" and OS!="android"', {
+-                    'include_dirs+': [
+-                      '/usr/include32',
+-                    ],
+-                  }],
+-                ],
+-               'target_conditions': [
+-                 ['_toolset=="target" and OS!="android"', {
+-                    # -mmmx allows mmintrin.h to be used for mmx intrinsics.
+-                    # video playback is mmx and sse2 optimized.
+-                    'cflags': [
+-                      '-m32',
+-                      '-mmmx',
+-                    ],
+-                    'ldflags': [
+-                      '-m32',
+-                    ],
+-                    'cflags_mozilla': [
+-                      '-m32',
+-                      '-mmmx',
+-                    ],
+-                  }],
+-                ],
+-              }],
+-            ],
+-          }],
+-          ['target_arch=="arm"', {
+-            'target_conditions': [
+-              ['_toolset=="target"', {
+-                'cflags_cc': [
+-                  # The codesourcery arm-2009q3 toolchain warns at that the ABI
+-                  # has changed whenever it encounters a varargs function. This
+-                  # silences those warnings, as they are not helpful and
+-                  # clutter legitimate warnings.
+-                  '-Wno-abi',
+-                ],
+-                'conditions': [
+-                  ['arm_thumb==1', {
+-                    'cflags': [
+-                    '-mthumb',
+-                    ]
+-                  }],
+-                  ['armv7==1', {
+-                    'cflags': [
+-                      '-march=armv7-a',
+-                      '-mtune=cortex-a8',
+-                      '-mfloat-abi=<(arm_float_abi)',
+-                    ],
+-                    'conditions': [
+-                      ['arm_neon==1', {
+-                        'cflags': [ '-mfpu=neon', ],
+-                      }, {
+-                        'cflags': [ '-mfpu=<(arm_fpu)', ],
+-                      }],
+-                    ],
+-                  }],
+-                  ['OS=="android"', {
+-                    # Most of the following flags are derived from what Android
+-                    # uses by default when building for arm, reference for which
+-                    # can be found in the following file in the Android NDK:
+-                    # toolchains/arm-linux-androideabi-4.4.3/setup.mk
+-                    'cflags': [
+-                      # The tree-sra optimization (scalar replacement for
+-                      # aggregates enabling subsequent optimizations) leads to
+-                      # invalid code generation when using the Android NDK's
+-                      # compiler (r5-r7). This can be verified using
+-                      # TestWebKitAPI's WTF.Checked_int8_t test.
+-                      '-fno-tree-sra',
+-                      '-fuse-ld=gold',
+-                      '-Wno-psabi',
+-                    ],
+-                    # Android now supports .relro sections properly.
+-                    # NOTE: While these flags enable the generation of .relro
+-                    # sections, the generated libraries can still be loaded on
+-                    # older Android platform versions.
+-                    'ldflags': [
+-                        '-Wl,-z,relro',
+-                        '-Wl,-z,now',
+-                        '-fuse-ld=gold',
+-                    ],
+-                    'conditions': [
+-                      ['arm_thumb == 1', {
+-                        # Android toolchain doesn't support -mimplicit-it=thumb
+-                        'cflags!': [ '-Wa,-mimplicit-it=thumb', ],
+-                        'cflags': [ '-mthumb-interwork', ],
+-                      }],
+-                      ['armv7==0', {
+-                        # Flags suitable for Android emulator
+-                        'cflags': [
+-                          '-march=armv5te',
+-                          '-mtune=xscale',
+-                          '-msoft-float',
+-                        ],
+-                        'defines': [
+-                          '__ARM_ARCH_5__',
+-                          '__ARM_ARCH_5T__',
+-                          '__ARM_ARCH_5E__',
+-                          '__ARM_ARCH_5TE__',
+-                        ],
+-                      }],
+-                      ['clang==1', {
+-                        'cflags!': [
+-                          # Clang does not support the following options.
+-                          '-mthumb-interwork',
+-                          '-finline-limit=64',
+-                          '-fno-tree-sra',
+-                          '-fuse-ld=gold',
+-                          '-Wno-psabi',
+-                        ],
+-                      }],
+-                    ],
+-                  }],
+-                ],
+-              }],
+-            ],
+-          }],
+-          ['linux_fpic==1', {
+-            'cflags': [
+-              '-fPIC',
+-            ],
+-            'ldflags': [
+-              '-fPIC',
+-            ],
+-          }],
+-          ['sysroot!=""', {
+-            'target_conditions': [
+-              ['_toolset=="target"', {
+-                'cflags': [
+-                  '--sysroot=<(sysroot)',
+-                ],
+-                'ldflags': [
+-                  '--sysroot=<(sysroot)',
+-                ],
+-              }]]
+-          }],
+-          ['clang==1', {
+-            'cflags': [
+-              '-Wheader-hygiene',
+-              # Clang spots more unused functions.
+-              '-Wno-unused-function',
+-              # Don't die on dtoa code that uses a char as an array index.
+-              '-Wno-char-subscripts',
+-              # Especially needed for gtest macros using enum values from Mac
+-              # system headers.
+-              # TODO(pkasting): In C++11 this is legal, so this should be
+-              # removed when we change to that.  (This is also why we don't
+-              # bother fixing all these cases today.)
+-              '-Wno-unnamed-type-template-args',
+-              # This (rightyfully) complains about 'override', which we use
+-              # heavily.
+-              '-Wno-c++11-extensions',
+-
+-              # Warns on switches on enums that cover all enum values but
+-              # also contain a default: branch. Chrome is full of that.
+-              '-Wno-covered-switch-default',
+-
+-              # TODO(thakis): Remove this.
+-              '-Wno-implicit-conversion-floating-point-to-bool',
+-            ],
+-            'cflags!': [
+-              # Clang doesn't seem to know know this flag.
+-              '-mfpmath=sse',
+-            ],
+-          }],
+-          ['clang==1 and clang_use_chrome_plugins==1', {
+-            'cflags': [
+-              '<@(clang_chrome_plugins_flags)',
+-            ],
+-          }],
+-          ['clang==1 and clang_load!=""', {
+-            'cflags': [
+-              '-Xclang', '-load', '-Xclang', '<(clang_load)',
+-            ],
+-          }],
+-          ['clang==1 and clang_add_plugin!=""', {
+-            'cflags': [
+-              '-Xclang', '-add-plugin', '-Xclang', '<(clang_add_plugin)',
+-            ],
+-          }],
+-          ['clang==1 and "<(GENERATOR)"=="ninja"', {
+-            'cflags': [
+-              # See http://crbug.com/110262
+-              '-fcolor-diagnostics',
+-            ],
+-          }],
+-          ['asan==1', {
+-            'target_conditions': [
+-              ['_toolset=="target"', {
+-                'cflags': [
+-                  '-faddress-sanitizer',
+-                  '-fno-omit-frame-pointer',
+-                ],
+-                'ldflags': [
+-                  '-faddress-sanitizer',
+-                ],
+-                'defines': [
+-                  'ADDRESS_SANITIZER',
+-                ],
+-              }],
+-            ],
+-          }],
+-          ['tsan==1', {
+-            'target_conditions': [
+-              ['_toolset=="target"', {
+-                'cflags': [
+-                  '-fthread-sanitizer',
+-                  '-fno-omit-frame-pointer',
+-                  '-fPIE',
+-                ],
+-                'ldflags': [
+-                  '-fthread-sanitizer',
+-                ],
+-                'defines': [
+-                  'THREAD_SANITIZER',
+-                  'DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL=1',
+-                ],
+-                'target_conditions': [
+-                  ['_type=="executable"', {
+-                    'ldflags': [
+-                      '-pie',
+-                    ],
+-                  }],
+-                ],
+-              }],
+-            ],
+-          }],
+-          ['order_profiling!=0 and (chromeos==1 or OS=="linux")', {
+-            'target_conditions' : [
+-              ['_toolset=="target"', {
+-                'cflags': [
+-                  '-finstrument-functions',
+-                  # Allow mmx intrinsics to inline, so that the
+-                  # compiler can expand the intrinsics.
+-                  '-finstrument-functions-exclude-file-list=mmintrin.h',
+-                ],
+-              }],
+-            ],
+-          }],
+-          ['linux_breakpad==1', {
+-            'cflags': [ '-g' ],
+-            'defines': ['USE_LINUX_BREAKPAD'],
+-          }],
+-          ['linux_use_heapchecker==1', {
+-            'variables': {'linux_use_tcmalloc%': 1},
+-            'defines': ['USE_HEAPCHECKER'],
+-          }],
+-          ['linux_use_tcmalloc==0', {
+-            'defines': ['NO_TCMALLOC'],
+-          }],
+-          ['linux_keep_shadow_stacks==1', {
+-            'defines': ['KEEP_SHADOW_STACKS'],
+-            'cflags': [
+-              '-finstrument-functions',
+-              # Allow mmx intrinsics to inline, so that the compiler can expand
+-              # the intrinsics.
+-              '-finstrument-functions-exclude-file-list=mmintrin.h',
+-            ],
+-          }],
+-          ['linux_use_gold_flags==1', {
+-            'ldflags': [
+-              # Experimentation found that using four linking threads
+-              # saved ~20% of link time.
+-              # https://groups.google.com/a/chromium.org/group/chromium-dev/browse_thread/thread/281527606915bb36
+-              '-Wl,--threads',
+-              '-Wl,--thread-count=4',
+-            ],
+-            'conditions': [
+-              ['release_valgrind_build==0', {
+-                'target_conditions': [
+-                  ['_toolset=="target"', {
+-                    'ldflags': [
+-                      # There seems to be a conflict of --icf and -pie
+-                      # in gold which can generate crashy binaries. As
+-                      # a security measure, -pie takes precendence for
+-                      # now.
+-                      #'-Wl,--icf=safe',
+-                      '-Wl,--icf=none',
+-                    ],
+-                  }],
+-                ],
+-              }],
+-            ],
+-          }],
+-          ['linux_use_gold_binary==1', {
+-            'variables': {
+-              'conditions': [
+-                ['inside_chromium_build==1', {
+-                  # We pass the path to gold to the compiler.  gyp leaves
+-                  # unspecified what the cwd is when running the compiler,
+-                  # so the normal gyp path-munging fails us.  This hack
+-                  # gets the right path.
+-                  'gold_path': '<(PRODUCT_DIR)/../../third_party/gold',
+-                }, {
+-                  'gold_path': '<(PRODUCT_DIR)/../../Source/WebKit/chromium/third_party/gold',
+-                }]
+-              ]
+-            },
+-            'ldflags': [
+-              # Put our gold binary in the search path for the linker.
+-              '-B<(gold_path)',
+-            ],
+-          }],
+-        ],
+-      },
+-    }],
+-    # FreeBSD-specific options; note that most FreeBSD options are set above,
+-    # with Linux.
+-    ['OS=="freebsd"', {
+-      'target_defaults': {
+-        'ldflags': [
+-          '-Wl,--no-keep-memory',
+-        ],
+-      },
+-    }],
+-    # Android-specific options; note that most are set above with Linux.
+-    ['OS=="android"', {
+-      'variables': {
+-        # This is the id for the archived chrome symbols. Each build that
+-        # archives symbols is assigned an id which is then added to GYP_DEFINES.
+-        # This is written to the device log on crashes just prior to dropping a
+-        # tombstone. Tools can determine the location of the archived symbols
+-        # from the id.
+-        'chrome_symbols_id%': '',
+-        'conditions': [
+-          # Use shared stlport library when system one used.
+-          # Figure this out early since it needs symbols from libgcc.a, so it
+-          # has to be before that in the set of libraries.
+-          ['use_system_stlport==1', {
+-            'android_stlport_library': 'stlport',
+-          }, {
+-            'android_stlport_library': 'stlport_static',
+-          }],
+-        ],
+-
+-        # Placing this variable here prevents from forking libvpx, used
+-        # by remoting.  Remoting is off, so it needn't built,
+-        # so forking it's deps seems like overkill.
+-        # But this variable need defined to properly run gyp.
+-        # A proper solution is to have an OS==android conditional
+-        # in third_party/libvpx/libvpx.gyp to define it.
+-        'libvpx_path': 'lib/linux/arm',
+-      },
+-      'target_defaults': {
+-        'variables': {
+-          'release_extra_cflags%': '',
+-        },
+-
+-        'target_conditions': [
+-          # Settings for building device targets using Android's toolchain.
+-          # These are based on the setup.mk file from the Android NDK.
+-          #
+-          # The NDK Android executable link step looks as follows:
+-          #  $LDFLAGS
+-          #  $(TARGET_CRTBEGIN_DYNAMIC_O)  <-- crtbegin.o
+-          #  $(PRIVATE_OBJECTS)            <-- The .o that we built
+-          #  $(PRIVATE_STATIC_LIBRARIES)   <-- The .a that we built
+-          #  $(TARGET_LIBGCC)              <-- libgcc.a
+-          #  $(PRIVATE_SHARED_LIBRARIES)   <-- The .so that we built
+-          #  $(PRIVATE_LDLIBS)             <-- System .so
+-          #  $(TARGET_CRTEND_O)            <-- crtend.o
+-          #
+-          # For now the above are approximated for executables by adding
+-          # crtbegin.o to the end of the ldflags and 'crtend.o' to the end
+-          # of 'libraries'.
+-          #
+-          # The NDK Android shared library link step looks as follows:
+-          #  $LDFLAGS
+-          #  $(PRIVATE_OBJECTS)            <-- The .o that we built
+-          #  -l,--whole-archive
+-          #  $(PRIVATE_WHOLE_STATIC_LIBRARIES)
+-          #  -l,--no-whole-archive
+-          #  $(PRIVATE_STATIC_LIBRARIES)   <-- The .a that we built
+-          #  $(TARGET_LIBGCC)              <-- libgcc.a
+-          #  $(PRIVATE_SHARED_LIBRARIES)   <-- The .so that we built
+-          #  $(PRIVATE_LDLIBS)             <-- System .so
+-          #
+-          # For now, assume that whole static libraries are not needed.
+-          #
+-          # For both executables and shared libraries, add the proper
+-          # libgcc.a to the start of libraries which puts it in the
+-          # proper spot after .o and .a files get linked in.
+-          #
+-          # TODO: The proper thing to do longer-tem would be proper gyp
+-          # support for a custom link command line.
+-          ['_toolset=="target"', {
+-           'conditions': [
+-           ['build_with_mozilla==0', {
+-            'cflags!': [
+-              '-pthread',  # Not supported by Android toolchain.
+-            ],
+-            'cflags': [
+-              '-ffunction-sections',
+-              '-funwind-tables',
+-              '-g',
+-              '-fstack-protector',
+-              '-fno-short-enums',
+-              '-finline-limit=64',
+-              '-Wa,--noexecstack',
+-              '<@(release_extra_cflags)',
+-            ],
+-            'ldflags!': [
+-              '-pthread',  # Not supported by Android toolchain.
+-            ],
+-            'ldflags': [
+-              '-nostdlib',
+-              '-Wl,--no-undefined',
+-              # Don't export symbols from statically linked libraries.
+-              '-Wl,--exclude-libs=ALL',
+-            ],
+-            'libraries': [
+-              '-l<(android_stlport_library)',
+-              # Manually link the libgcc.a that the cross compiler uses.
+-              '<!(<(android_toolchain)/*-gcc -print-libgcc-file-name)',
+-              '-lc',
+-              '-ldl',
+-              '-lstdc++',
+-              '-lm',
+-            ],
+-            'conditions': [
+-              ['android_upstream_bringup==1', {
+-                'defines': ['ANDROID_UPSTREAM_BRINGUP=1',],
+-              }],
+-              ['clang==1', {
+-                'cflags': [
+-                  # Work around incompatibilities between bionic and clang
+-                  # headers.
+-                  '-D__compiler_offsetof=__builtin_offsetof',
+-                  '-Dnan=__builtin_nan',
+-                ],
+-                'conditions': [
+-                  ['target_arch=="arm"', {
+-                    'cflags': [
+-                      '-target arm-linux-androideabi',
+-                      '-mllvm -arm-enable-ehabi',
+-                    ],
+-                    'ldflags': [
+-                      '-target arm-linux-androideabi',
+-                    ],
+-                  }],
+-                  ['target_arch=="ia32"', {
+-                    'cflags': [
+-                      '-target x86-linux-androideabi',
+-                    ],
+-                    'ldflags': [
+-                      '-target x86-linux-androideabi',
+-                    ],
+-                  }],
+-                ],
+-              }],
+-              ['android_build_type==0', {
+-                'defines': [
+-                  # The NDK has these things, but doesn't define the constants
+-                  # to say that it does. Define them here instead.
+-                  'HAVE_SYS_UIO_H',
+-                ],
+-                'cflags': [
+-                  '--sysroot=<(android_ndk_sysroot)',
+-                ],
+-                'ldflags': [
+-                  '--sysroot=<(android_ndk_sysroot)',
+-                ],
+-              }],
+-              ['android_build_type==1', {
+-                'include_dirs': [
+-                  # OpenAL headers from the Android tree.
+-                  '<(android_src)/frameworks/wilhelm/include',
+-                ],
+-                'cflags': [
+-                  # Chromium builds its own (non-third-party) code with
+-                  # -Werror to make all warnings into errors. However, Android
+-                  # enables warnings that Chromium doesn't, so some of these
+-                  # extra warnings trip and break things.
+-                  # For now, we leave these warnings enabled but prevent them
+-                  # from being treated as errors.
+-                  #
+-                  # Things that are part of -Wextra:
+-                  '-Wno-error=extra', # Enabled by -Wextra, but no specific flag
+-                  '-Wno-error=ignored-qualifiers',
+-                  '-Wno-error=type-limits',
+-                  # Other things unrelated to -Wextra:
+-                  '-Wno-error=non-virtual-dtor',
+-                  '-Wno-error=sign-promo',
+-                ],
+-                'cflags_cc': [
+-                  # Disabling c++0x-compat should be handled in WebKit, but
+-                  # this currently doesn't work because gcc_version is not set
+-                  # correctly when building with the Android build system.
+-                  # TODO(torne): Fix this in WebKit.
+-                  '-Wno-error=c++0x-compat',
+-                ],
+-              }],
+-              ['android_build_type==1 and chromium_code==0', {
+-                'cflags': [
+-                  # There is a class of warning which:
+-                  #  1) Android always enables and also treats as errors
+-                  #  2) Chromium ignores in third party code
+-                  # For now, I am leaving these warnings enabled but preventing
+-                  # them from being treated as errors here.
+-                  '-Wno-error=address',
+-                  '-Wno-error=format-security',
+-                  '-Wno-error=non-virtual-dtor',
+-                  '-Wno-error=return-type',
+-                  '-Wno-error=sequence-point',
+-                ],
+-              }],
+-              ['target_arch == "arm"', {
+-                'ldflags': [
+-                  # Enable identical code folding to reduce size.
+-                  '-Wl,--icf=safe',
+-                ],
+-              }],
+-              # NOTE: The stlport header include paths below are specified in
+-              # cflags rather than include_dirs because they need to come
+-              # after include_dirs. Think of them like system headers, but
+-              # don't use '-isystem' because the arm-linux-androideabi-4.4.3
+-              # toolchain (circa Gingerbread) will exhibit strange errors.
+-              # The include ordering here is important; change with caution.
+-              ['use_system_stlport==1', {
+-                'cflags': [
+-                  # For libstdc++/include, which is used by stlport.
+-                  '-I<(android_src)/bionic',
+-                  '-I<(android_src)/external/stlport/stlport',
+-                ],
+-              }, { # else: use_system_stlport!=1
+-                'cflags': [
+-                  '-I<(android_ndk_root)/sources/cxx-stl/stlport/stlport',
+-                ],
+-                'conditions': [
+-                  ['target_arch=="arm" and armv7==1', {
+-                    'ldflags': [
+-                      '-L<(android_ndk_root)/sources/cxx-stl/stlport/libs/armeabi-v7a',
+-                    ],
+-                  }],
+-                  ['target_arch=="arm" and armv7==0', {
+-                    'ldflags': [
+-                      '-L<(android_ndk_root)/sources/cxx-stl/stlport/libs/armeabi',
+-                    ],
+-                  }],
+-                  ['target_arch=="ia32"', {
+-                    'ldflags': [
+-                      '-L<(android_ndk_root)/sources/cxx-stl/stlport/libs/x86',
+-                    ],
+-                  }],
+-                ],
+-              }],
+-              ['target_arch=="ia32"', {
+-                # The x86 toolchain currently has problems with stack-protector.
+-                'cflags!': [
+-                  '-fstack-protector',
+-                ],
+-                'cflags': [
+-                  '-fno-stack-protector',
+-                ],
+-              }],
+-            ],
+-            'target_conditions': [
+-              ['_type=="executable"', {
+-                'ldflags': [
+-                  '-Bdynamic',
+-                  '-Wl,-dynamic-linker,/system/bin/linker',
+-                  '-Wl,--gc-sections',
+-                  '-Wl,-z,nocopyreloc',
+-                  # crtbegin_dynamic.o should be the last item in ldflags.
+-                  '<(android_ndk_lib)/crtbegin_dynamic.o',
+-                ],
+-                'libraries': [
+-                  # crtend_android.o needs to be the last item in libraries.
+-                  # Do not add any libraries after this!
+-                  '<(android_ndk_lib)/crtend_android.o',
+-                ],
+-              }],
+-              ['_type=="shared_library" or _type=="loadable_module"', {
+-                'ldflags': [
+-                  '-Wl,-shared,-Bsymbolic',
+-                  # crtbegin_so.o should be the last item in ldflags.
+-                  '<(android_ndk_lib)/crtbegin_so.o',
+-                ],
+-                'libraries': [
+-                  # crtend_so.o needs to be the last item in libraries.
+-                  # Do not add any libraries after this!
+-                  '<(android_ndk_lib)/crtend_so.o',
+-                ],
+-              }],
+-            ],
+-
+-           }], # build_with_mozilla== 0
+-
+-            ],
+-            'defines': [
+-              'ANDROID',
+-              '__GNU_SOURCE=1',  # Necessary for clone()
+-              'USE_STLPORT=1',
+-              '_STLP_USE_PTR_SPECIALIZATIONS=1',
+-              'CHROME_SYMBOLS_ID="<(chrome_symbols_id)"',
+-            ],
+-           }],
+-          # Settings for building host targets using the system toolchain.
+-          ['_toolset=="host"', {
+-            'cflags!': [
+-              # Due to issues in Clang build system, using ASan on 32-bit
+-              # binaries on x86_64 host is problematic.
+-              # TODO(eugenis): re-enable.
+-              '-faddress-sanitizer',
+-            ],
+-            'ldflags!': [
+-              '-faddress-sanitizer',
+-              '-Wl,-z,noexecstack',
+-              '-Wl,--gc-sections',
+-              '-Wl,-O1',
+-              '-Wl,--as-needed',
+-            ],
+-            'sources/': [
+-              ['exclude', '_android(_unittest)?\\.cc$'],
+-              ['exclude', '(^|/)android/']
+-            ],
+-          }],
+-        ],
+-      },
+-    }],
+-    ['OS=="solaris"', {
+-      'cflags!': ['-fvisibility=hidden'],
+-      'cflags_cc!': ['-fvisibility-inlines-hidden'],
+-    }],
+-    ['OS=="mac" or OS=="ios"', {
+-      'target_defaults': {
+-        'mac_bundle': 0,
+-        'xcode_settings': {
+-          'ALWAYS_SEARCH_USER_PATHS': 'NO',
+-          'GCC_C_LANGUAGE_STANDARD': 'c99',         # -std=c99
+-          'GCC_CW_ASM_SYNTAX': 'NO',                # No -fasm-blocks
+-          'GCC_ENABLE_CPP_EXCEPTIONS': 'NO',        # -fno-exceptions
+-          'GCC_ENABLE_CPP_RTTI': 'NO',              # -fno-rtti
+-          'GCC_ENABLE_PASCAL_STRINGS': 'NO',        # No -mpascal-strings
+-          # GCC_INLINES_ARE_PRIVATE_EXTERN maps to -fvisibility-inlines-hidden
+-          'GCC_INLINES_ARE_PRIVATE_EXTERN': 'YES',
+-          'GCC_OBJC_CALL_CXX_CDTORS': 'YES',        # -fobjc-call-cxx-cdtors
+-          'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES',      # -fvisibility=hidden
+-          'GCC_THREADSAFE_STATICS': 'NO',           # -fno-threadsafe-statics
+-          'GCC_TREAT_WARNINGS_AS_ERRORS': 'YES',    # -Werror
+-          'GCC_VERSION': '4.2',
+-          'GCC_WARN_ABOUT_MISSING_NEWLINE': 'YES',  # -Wnewline-eof
+-          'USE_HEADERMAP': 'NO',
+-          'WARNING_CFLAGS': [
+-            '-Wall',
+-            '-Wendif-labels',
+-            '-Wextra',
+-            # Don't warn about unused function parameters.
+-            '-Wno-unused-parameter',
+-            # Don't warn about the "struct foo f = {0};" initialization
+-            # pattern.
+-            '-Wno-missing-field-initializers',
+-          ],
+-          'conditions': [
+-            ['chromium_mac_pch', {'GCC_PRECOMPILE_PREFIX_HEADER': 'YES'},
+-                                 {'GCC_PRECOMPILE_PREFIX_HEADER': 'NO'}
+-            ],
+-          ],
+-        },
+-        'target_conditions': [
+-          ['_type!="static_library"', {
+-            'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-search_paths_first']},
+-          }],
+-          ['_mac_bundle', {
+-            'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-ObjC']},
+-          }],
+-        ],  # target_conditions
+-      },  # target_defaults
+-    }],  # OS=="mac" or OS=="ios"
+-    ['OS=="mac"', {
+-      'target_defaults': {
+-        'variables': {
+-          # These should end with %, but there seems to be a bug with % in
+-          # variables that are intended to be set to different values in
+-          # different targets, like these.
+-          'mac_pie': 1,        # Most executables can be position-independent.
+-          'mac_real_dsym': 0,  # Fake .dSYMs are fine in most cases.
+-          # Strip debugging symbols from the target.
+-          'mac_strip': '<(mac_strip_release)',
+-        },
+-        'xcode_settings': {
+-          'GCC_DYNAMIC_NO_PIC': 'NO',               # No -mdynamic-no-pic
+-                                                    # (Equivalent to -fPIC)
+-          # MACOSX_DEPLOYMENT_TARGET maps to -mmacosx-version-min
+-          'MACOSX_DEPLOYMENT_TARGET': '<(mac_deployment_target)',
+-          # Keep pch files below xcodebuild/.
+-          'SHARED_PRECOMPS_DIR': '$(CONFIGURATION_BUILD_DIR)/SharedPrecompiledHeaders',
+-          'OTHER_CFLAGS': [
+-            '-fno-strict-aliasing',  # See http://crbug.com/32204
+-          ],
+-          'conditions': [
+-            ['clang==1', {
+-              'CC': '$(SOURCE_ROOT)/<(clang_dir)/clang',
+-              'LDPLUSPLUS': '$(SOURCE_ROOT)/<(clang_dir)/clang++',
+-
+-              # Don't use -Wc++0x-extensions, which Xcode 4 enables by default
+-              # when buliding with clang. This warning is triggered when the
+-              # override keyword is used via the OVERRIDE macro from
+-              # base/compiler_specific.h.
+-              'CLANG_WARN_CXX0X_EXTENSIONS': 'NO',
+-
+-              'GCC_VERSION': 'com.apple.compilers.llvm.clang.1_0',
+-              'WARNING_CFLAGS': [
+-                '-Wheader-hygiene',
+-                # Don't die on dtoa code that uses a char as an array index.
+-                # This is required solely for base/third_party/dmg_fp/dtoa.cc.
+-                '-Wno-char-subscripts',
+-                # Clang spots more unused functions.
+-                '-Wno-unused-function',
+-                # See comments on this flag higher up in this file.
+-                '-Wno-unnamed-type-template-args',
+-                # This (rightyfully) complains about 'override', which we use
+-                # heavily.
+-                '-Wno-c++11-extensions',
+-
+-                # Warns on switches on enums that cover all enum values but
+-                # also contain a default: branch. Chrome is full of that.
+-                '-Wno-covered-switch-default',
+-
+-                # TODO(thakis): Remove this.
+-                '-Wno-implicit-conversion-floating-point-to-bool',
+-              ],
+-            }],
+-            ['clang==1 and clang_use_chrome_plugins==1', {
+-              'OTHER_CFLAGS': [
+-                '<@(clang_chrome_plugins_flags)',
+-              ],
+-            }],
+-            ['clang==1 and clang_load!=""', {
+-              'OTHER_CFLAGS': [
+-                '-Xclang', '-load', '-Xclang', '<(clang_load)',
+-              ],
+-            }],
+-            ['clang==1 and clang_add_plugin!=""', {
+-              'OTHER_CFLAGS': [
+-                '-Xclang', '-add-plugin', '-Xclang', '<(clang_add_plugin)',
+-              ],
+-            }],
+-            ['clang==1 and "<(GENERATOR)"=="ninja"', {
+-              'OTHER_CFLAGS': [
+-                # See http://crbug.com/110262
+-                '-fcolor-diagnostics',
+-              ],
+-            }],
+-          ],
+-        },
+-        'conditions': [
+-          ['clang==1', {
+-            'variables': {
+-              'clang_dir': '../third_party/llvm-build/Release+Asserts/bin',
+-            },
+-          }],
+-          ['asan==1', {
+-            'xcode_settings': {
+-              'OTHER_CFLAGS': [
+-                '-faddress-sanitizer',
+-              ],
+-            },
+-            'defines': [
+-              'ADDRESS_SANITIZER',
+-            ],
+-          }],
+-        ],
+-        'target_conditions': [
+-          ['_type!="static_library"', {
+-            'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-search_paths_first']},
+-            'conditions': [
+-              ['asan==1', {
+-                'xcode_settings': {
+-                  'OTHER_LDFLAGS': [
+-                    '-faddress-sanitizer',
+-                  ],
+-                },
+-              }],
+-            ],
+-          }],
+-          ['_mac_bundle', {
+-            'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-ObjC']},
+-          }],
+-          ['_type=="executable"', {
+-            'postbuilds': [
+-              {
+-                # Arranges for data (heap) pages to be protected against
+-                # code execution when running on Mac OS X 10.7 ("Lion"), and
+-                # ensures that the position-independent executable (PIE) bit
+-                # is set for ASLR when running on Mac OS X 10.5 ("Leopard").
+-                'variables': {
+-                  # Define change_mach_o_flags in a variable ending in _path
+-                  # so that GYP understands it's a path and performs proper
+-                  # relativization during dict merging.
+-                  'change_mach_o_flags':
+-                      'mac/change_mach_o_flags_from_xcode.sh',
+-                  'change_mach_o_flags_options%': [
+-                  ],
+-                  'target_conditions': [
+-                    ['mac_pie==0 or release_valgrind_build==1', {
+-                      # Don't enable PIE if it's unwanted. It's unwanted if
+-                      # the target specifies mac_pie=0 or if building for
+-                      # Valgrind, because Valgrind doesn't understand slide.
+-                      # See the similar mac_pie/release_valgrind_build check
+-                      # below.
+-                      'change_mach_o_flags_options': [
+-                        '--no-pie',
+-                      ],
+-                    }],
+-                  ],
+-                },
+-                'postbuild_name': 'Change Mach-O Flags',
+-                'action': [
+-                   '$(srcdir)$(os_sep)build$(os_sep)<(change_mach_o_flags)',
+-                  '>@(change_mach_o_flags_options)',
+-                ],
+-              },
+-            ],
+-            'conditions': [
+-              ['asan==1', {
+-                'variables': {
+-                 'asan_saves_file': 'asan.saves',
+-                },
+-                'xcode_settings': {
+-                  'CHROMIUM_STRIP_SAVE_FILE': '<(asan_saves_file)',
+-                },
+-              }],
+-            ],
+-            'target_conditions': [
+-              ['mac_pie==1 and release_valgrind_build==0', {
+-                # Turn on position-independence (ASLR) for executables. When
+-                # PIE is on for the Chrome executables, the framework will
+-                # also be subject to ASLR.
+-                # Don't do this when building for Valgrind, because Valgrind
+-                # doesn't understand slide. TODO: Make Valgrind on Mac OS X
+-                # understand slide, and get rid of the Valgrind check.
+-                'xcode_settings': {
+-                  'OTHER_LDFLAGS': [
+-                    '-Wl,-pie',  # Position-independent executable (MH_PIE)
+-                  ],
+-                },
+-              }],
+-            ],
+-          }],
+-          ['(_type=="executable" or _type=="shared_library" or \
+-             _type=="loadable_module") and mac_strip!=0', {
+-            'target_conditions': [
+-              ['mac_real_dsym == 1', {
+-                # To get a real .dSYM bundle produced by dsymutil, set the
+-                # debug information format to dwarf-with-dsym.  Since
+-                # strip_from_xcode will not be used, set Xcode to do the
+-                # stripping as well.
+-                'configurations': {
+-                  'Release_Base': {
+-                    'xcode_settings': {
+-                      'DEBUG_INFORMATION_FORMAT': 'dwarf-with-dsym',
+-                      'DEPLOYMENT_POSTPROCESSING': 'YES',
+-                      'STRIP_INSTALLED_PRODUCT': 'YES',
+-                      'target_conditions': [
+-                        ['_type=="shared_library" or _type=="loadable_module"', {
+-                          # The Xcode default is to strip debugging symbols
+-                          # only (-S).  Local symbols should be stripped as
+-                          # well, which will be handled by -x.  Xcode will
+-                          # continue to insert -S when stripping even when
+-                          # additional flags are added with STRIPFLAGS.
+-                          'STRIPFLAGS': '-x',
+-                        }],  # _type=="shared_library" or _type=="loadable_module"'
+-                      ],  # target_conditions
+-                    },  # xcode_settings
+-                  },  # configuration "Release"
+-                },  # configurations
+-              }, {  # mac_real_dsym != 1
+-                # To get a fast fake .dSYM bundle, use a post-build step to
+-                # produce the .dSYM and strip the executable.  strip_from_xcode
+-                # only operates in the Release configuration.
+-                'postbuilds': [
+-                  {
+-                    'variables': {
+-                      # Define strip_from_xcode in a variable ending in _path
+-                      # so that gyp understands it's a path and performs proper
+-                      # relativization during dict merging.
+-                      'strip_from_xcode': 'mac/strip_from_xcode',
+-                    },
+-                    'postbuild_name': 'Strip If Needed',
+-                    'action': ['$(srcdir)$(os_sep)build$(os_sep)<(strip_from_xcode)'],
+-                  },
+-                ],  # postbuilds
+-              }],  # mac_real_dsym
+-            ],  # target_conditions
+-          }],  # (_type=="executable" or _type=="shared_library" or
+-               #  _type=="loadable_module") and mac_strip!=0
+-        ],  # target_conditions
+-      },  # target_defaults
+-    }],  # OS=="mac"
+-    ['OS=="ios"', {
+-      'target_defaults': {
+-        'xcode_settings' : {
+-          'GCC_VERSION': 'com.apple.compilers.llvm.clang.1_0',
+-
+-          # This next block is mostly common with the 'mac' section above,
+-          # but keying off (or setting) 'clang' isn't valid for iOS as it
+-          # also seems to mean using the custom build of clang.
+-
+-          # Don't use -Wc++0x-extensions, which Xcode 4 enables by default
+-          # when buliding with clang. This warning is triggered when the
+-          # override keyword is used via the OVERRIDE macro from
+-          # base/compiler_specific.h.
+-          'CLANG_WARN_CXX0X_EXTENSIONS': 'NO',
+-          'WARNING_CFLAGS': [
+-            '-Wheader-hygiene',
+-            # Don't die on dtoa code that uses a char as an array index.
+-            # This is required solely for base/third_party/dmg_fp/dtoa.cc.
+-            '-Wno-char-subscripts',
+-            # Clang spots more unused functions.
+-            '-Wno-unused-function',
+-            # See comments on this flag higher up in this file.
+-            '-Wno-unnamed-type-template-args',
+-            # This (rightyfully) complains about 'override', which we use
+-            # heavily.
+-            '-Wno-c++11-extensions',
+-          ],
+-        },
+-        'target_conditions': [
+-          ['_type=="executable"', {
+-            'configurations': {
+-              'Release_Base': {
+-                'xcode_settings': {
+-                  'DEPLOYMENT_POSTPROCESSING': 'YES',
+-                  'STRIP_INSTALLED_PRODUCT': 'YES',
+-                },
+-              },
+-            },
+-            'xcode_settings': {
+-              'conditions': [
+-                ['chromium_ios_signing', {
+-                  # iOS SDK wants everything for device signed.
+-                  'CODE_SIGN_IDENTITY[sdk=iphoneos*]': 'iPhone Developer',
+-                }, {
+-                  'CODE_SIGNING_REQUIRED': 'NO',
+-                  'CODE_SIGN_IDENTITY[sdk=iphoneos*]': '',
+-                }],
+-              ],
+-            },
+-          }],
+-        ],  # target_conditions
+-      },  # target_defaults
+-    }],  # OS=="ios"
+-    ['OS=="win"', {
+-      'target_defaults': {
+-        'defines': [
+-          'WIN32',
+-          '_WINDOWS',
+-          'NOMINMAX',
+-          '_CRT_RAND_S',
+-          'CERT_CHAIN_PARA_HAS_EXTRA_FIELDS',
+-          'WIN32_LEAN_AND_MEAN',
+-          '_ATL_NO_OPENGL',
+-        ],
+-        'conditions': [
+-          ['build_with_mozilla==0', {
+-              'defines': [
+-                '_WIN32_WINNT=0x0602',
+-                'WINVER=0x0602',
+-              ],
+-          }],
+-          ['buildtype=="Official"', {
+-              # In official builds, targets can self-select an optimization
+-              # level by defining a variable named 'optimize', and setting it
+-              # to one of
+-              # - "size", optimizes for minimal code size - the default.
+-              # - "speed", optimizes for speed over code size.
+-              # - "max", whole program optimization and link-time code
+-              #   generation. This is very expensive and should be used
+-              #   sparingly.
+-              'variables': {
+-                'optimize%': 'size',
+-              },
+-              'target_conditions': [
+-                ['optimize=="size"', {
+-                    'msvs_settings': {
+-                      'VCCLCompilerTool': {
+-                        # 1, optimizeMinSpace, Minimize Size (/O1)
+-                        'Optimization': '1',
+-                        # 2, favorSize - Favor small code (/Os)
+-                        'FavorSizeOrSpeed': '2',
+-                      },
+-                    },
+-                  },
+-                ],
+-                ['optimize=="speed"', {
+-                    'msvs_settings': {
+-                      'VCCLCompilerTool': {
+-                        # 2, optimizeMaxSpeed, Maximize Speed (/O2)
+-                        'Optimization': '2',
+-                        # 1, favorSpeed - Favor fast code (/Ot)
+-                        'FavorSizeOrSpeed': '1',
+-                      },
+-                    },
+-                  },
+-                ],
+-                ['optimize=="max"', {
+-                    'msvs_settings': {
+-                      'VCCLCompilerTool': {
+-                        # 2, optimizeMaxSpeed, Maximize Speed (/O2)
+-                        'Optimization': '2',
+-                        # 1, favorSpeed - Favor fast code (/Ot)
+-                        'FavorSizeOrSpeed': '1',
+-                        # This implies link time code generation.
+-                        'WholeProgramOptimization': 'true',
+-                      },
+-                    },
+-                  },
+-                ],
+-              ],
+-            },
+-          ],
+-          ['component=="static_library"', {
+-            'defines': [
+-              '_HAS_EXCEPTIONS=0',
+-            ],
+-          }],
+-          ['MSVS_VERSION=="2008"', {
+-            'defines': [
+-              '_HAS_TR1=0',
+-            ],
+-          }],
+-          ['secure_atl', {
+-            'defines': [
+-              '_SECURE_ATL',
+-            ],
+-          }],
+-        ],
+-        'msvs_system_include_dirs': [
+-          '<(windows_sdk_path)/Include/shared',
+-          '<(windows_sdk_path)/Include/um',
+-          '<(windows_sdk_path)/Include/winrt',
+-#          '<(directx_sdk_path)/Include',
+-          '$(VSInstallDir)/VC/atlmfc/include',
+-        ],
+-        'msvs_cygwin_dirs': ['<(DEPTH)/third_party/cygwin'],
+-        'msvs_disabled_warnings': [4351, 4396, 4503, 4819,
+-          # TODO(maruel): These warnings are level 4. They will be slowly
+-          # removed as code is fixed.
+-          4100, 4121, 4125, 4127, 4130, 4131, 4189, 4201, 4238, 4244, 4245,
+-          4310, 4355, 4428, 4481, 4505, 4510, 4512, 4530, 4610, 4611, 4701,
+-          4702, 4706,
+-        ],
+-        'msvs_settings': {
+-          'VCCLCompilerTool': {
+-            'AdditionalOptions': ['/MP'],
+-            'MinimalRebuild': 'false',
+-            'BufferSecurityCheck': 'true',
+-            'EnableFunctionLevelLinking': 'true',
+-            'RuntimeTypeInfo': 'false',
+-            'WarningLevel': '4',
+-            'WarnAsError': 'true',
+-            'DebugInformationFormat': '3',
+-            'conditions': [
+-              ['component=="shared_library"', {
+-                'ExceptionHandling': '1',  # /EHsc
+-              }, {
+-                'ExceptionHandling': '0',
+-              }],
+-            ],
+-          },
+-          'VCLibrarianTool': {
+-            'AdditionalOptions': ['/ignore:4221'],
+-            'AdditionalLibraryDirectories': [
+-#              '<(directx_sdk_path)/Lib/x86',
+-              '<(windows_sdk_path)/Lib/win8/um/x86',
+-            ],
+-          },
+-          'VCLinkerTool': {
+-            'AdditionalDependencies': [
+-              'wininet.lib',
+-              'dnsapi.lib',
+-              'version.lib',
+-              'msimg32.lib',
+-              'ws2_32.lib',
+-              'usp10.lib',
+-              'dbghelp.lib',
+-              'winmm.lib',
+-              'shlwapi.lib',
+-            ],
+-
+-            'conditions': [
+-              ['msvs_express', {
+-                # Explicitly required when using the ATL with express
+-                'AdditionalDependencies': [
+-                  'atlthunk.lib',
+-                ],
+-
+-                # ATL 8.0 included in WDK 7.1 makes the linker to generate
+-                # almost eight hundred LNK4254 and LNK4078 warnings:
+-                #   - warning LNK4254: section 'ATL' (50000040) merged into
+-                #     '.rdata' (40000040) with different attributes
+-                #   - warning LNK4078: multiple 'ATL' sections found with
+-                #     different attributes
+-                'AdditionalOptions': ['/ignore:4254', '/ignore:4078'],
+-              }],
+-              ['MSVS_VERSION=="2005e"', {
+-                # Non-express versions link automatically to these
+-                'AdditionalDependencies': [
+-                  'advapi32.lib',
+-                  'comdlg32.lib',
+-                  'ole32.lib',
+-                  'shell32.lib',
+-                  'user32.lib',
+-                  'winspool.lib',
+-                ],
+-              }],
+-            ],
+-            'AdditionalLibraryDirectories': [
+-#              '<(directx_sdk_path)/Lib/x86', XXXX
+-              '<(windows_sdk_path)/Lib/win8/um/x86',
+-            ],
+-            'GenerateDebugInformation': 'true',
+-            'MapFileName': '$(OutDir)\\$(TargetName).map',
+-            'ImportLibrary': '$(OutDir)\\lib\\$(TargetName).lib',
+-            'FixedBaseAddress': '1',
+-            # SubSystem values:
+-            #   0 == not set
+-            #   1 == /SUBSYSTEM:CONSOLE
+-            #   2 == /SUBSYSTEM:WINDOWS
+-            # Most of the executables we'll ever create are tests
+-            # and utilities with console output.
+-            'SubSystem': '1',
+-          },
+-          'VCMIDLTool': {
+-            'GenerateStublessProxies': 'true',
+-            'TypeLibraryName': '$(InputName).tlb',
+-            'OutputDirectory': '$(IntDir)',
+-            'HeaderFileName': '$(InputName).h',
+-            'DLLDataFileName': '$(InputName).dlldata.c',
+-            'InterfaceIdentifierFileName': '$(InputName)_i.c',
+-            'ProxyFileName': '$(InputName)_p.c',
+-          },
+-          'VCResourceCompilerTool': {
+-            'Culture' : '1033',
+-            'AdditionalIncludeDirectories': [
+-              '<(DEPTH)',
+-              '<(SHARED_INTERMEDIATE_DIR)',
+-            ],
+-          },
+-        },
+-      },
+-    }],
+-    ['disable_nacl==1', {
+-      'target_defaults': {
+-        'defines': [
+-          'DISABLE_NACL',
+-        ],
+-      },
+-    }],
+-    ['OS=="win" and msvs_use_common_linker_extras', {
+-      'target_defaults': {
+-        'msvs_settings': {
+-          'VCLinkerTool': {
+-            'DelayLoadDLLs': [
+-              'dbghelp.dll',
+-              'dwmapi.dll',
+-              'shell32.dll',
+-              'uxtheme.dll',
+-            ],
+-          },
+-        },
+-        'configurations': {
+-          'x86_Base': {
+-            'msvs_settings': {
+-              'VCLinkerTool': {
+-                'AdditionalOptions': [
+-                  '/safeseh',
+-                  '/dynamicbase',
+-                  '/ignore:4199',
+-                  '/ignore:4221',
+-                  '/nxcompat',
+-                ],
+-              },
+-            },
+-          },
+-          'x64_Base': {
+-            'msvs_settings': {
+-              'VCLinkerTool': {
+-                'AdditionalOptions': [
+-                  # safeseh is not compatible with x64
+-                  '/dynamicbase',
+-                  '/ignore:4199',
+-                  '/ignore:4221',
+-                  '/nxcompat',
+-                ],
+-              },
+-            },
+-          },
+-        },
+-      },
+-    }],
+-    ['enable_new_npdevice_api==1', {
+-      'target_defaults': {
+-        'defines': [
+-          'ENABLE_NEW_NPDEVICE_API',
+-        ],
+-      },
+-    }],
+-    ['clang==1', {
+-      'conditions': [
+-        ['OS=="android"', {
+-          # Android could use the goma with clang.
+-          'make_global_settings': [
+-            ['CC', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} ${CHROME_SRC}/<(make_clang_dir)/bin/clang)'],
+-            ['CXX', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} ${CHROME_SRC}/<(make_clang_dir)/bin/clang++)'],
+-            ['LINK', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} ${CHROME_SRC}/<(make_clang_dir)/bin/clang++)'],
+-            ['CC.host', '$(CC)'],
+-            ['CXX.host', '$(CXX)'],
+-            ['LINK.host', '$(LINK)'],
+-          ],
+-        }, {
+-          'make_global_settings': [
+-            ['CC', '<(make_clang_dir)/bin/clang'],
+-            ['CXX', '<(make_clang_dir)/bin/clang++'],
+-            ['LINK', '$(CXX)'],
+-            ['CC.host', '$(CC)'],
+-            ['CXX.host', '$(CXX)'],
+-            ['LINK.host', '$(LINK)'],
+-          ],
+-        }],
+-      ],
+-    }],
+-    ['OS=="android" and clang==0', {
+-      # Hardcode the compiler names in the Makefile so that
+-      # it won't depend on the environment at make time.
+-      'make_global_settings': [
+-        ['CC', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <(android_toolchain)/*-gcc)'],
+-        ['CXX', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <(android_toolchain)/*-g++)'],
+-        ['LINK', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <(android_toolchain)/*-gcc)'],
+-        ['CC.host', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <!(which gcc))'],
+-        ['CXX.host', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <!(which g++))'],
+-        ['LINK.host', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <!(which g++))'],
+-      ],
+-    }],
+-  ],
+-  'xcode_settings': {
+-    # DON'T ADD ANYTHING NEW TO THIS BLOCK UNLESS YOU REALLY REALLY NEED IT!
+-    # This block adds *project-wide* configuration settings to each project
+-    # file.  It's almost always wrong to put things here.  Specify your
+-    # custom xcode_settings in target_defaults to add them to targets instead.
+-
+-    'conditions': [
+-      # In an Xcode Project Info window, the "Base SDK for All Configurations"
+-      # setting sets the SDK on a project-wide basis. In order to get the
+-      # configured SDK to show properly in the Xcode UI, SDKROOT must be set
+-      # here at the project level.
+-      ['OS=="mac"', {
+-        'conditions': [
+-          ['mac_sdk_path==""', {
+-            'SDKROOT': 'macosx<(mac_sdk)',  # -isysroot
+-          }, {
+-            'SDKROOT': '<(mac_sdk_path)',  # -isysroot
+-          }],
+-        ],
+-      }],
+-      ['OS=="ios"', {
+-        'conditions': [
+-          ['ios_sdk_path==""', {
+-            'SDKROOT': 'iphoneos<(ios_sdk)',  # -isysroot
+-          }, {
+-            'SDKROOT': '<(ios_sdk_path)',  # -isysroot
+-          }],
+-        ],
+-      }],
+-      ['OS=="ios"', {
+-        # Just build armv7 since iOS 4.3+ only supports armv7.
+-        'ARCHS': '$(ARCHS_UNIVERSAL_IPHONE_OS)',
+-        'IPHONEOS_DEPLOYMENT_TARGET': '<(ios_deployment_target)',
+-        # Target both iPhone and iPad.
+-        'TARGETED_DEVICE_FAMILY': '1,2',
+-      }],
+-    ],
+-
+-    # The Xcode generator will look for an xcode_settings section at the root
+-    # of each dict and use it to apply settings on a file-wide basis.  Most
+-    # settings should not be here, they should be in target-specific
+-    # xcode_settings sections, or better yet, should use non-Xcode-specific
+-    # settings in target dicts.  SYMROOT is a special case, because many other
+-    # Xcode variables depend on it, including variables such as
+-    # PROJECT_DERIVED_FILE_DIR.  When a source group corresponding to something
+-    # like PROJECT_DERIVED_FILE_DIR is added to a project, in order for the
+-    # files to appear (when present) in the UI as actual files and not red
+-    # red "missing file" proxies, the correct path to PROJECT_DERIVED_FILE_DIR,
+-    # and therefore SYMROOT, needs to be set at the project level.
+-    'SYMROOT': '<(DEPTH)/xcodebuild',
+-  },
+-}
+diff --git a/media/webrtc/trunk/build/common_untrusted.gypi b/media/webrtc/trunk/build/common_untrusted.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/common_untrusted.gypi
++++ /dev/null
+@@ -1,29 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This GYP file should be included for every target in Chromium that is built
+-# using the NaCl toolchain.
+-{
+-  'includes': [
+-    '../native_client/build/untrusted.gypi',
+-  ],
+-  'target_defaults': {
+-    'conditions': [
+-      ['target_arch=="arm"', {
+-        'variables': {
+-          'clang': 1,
+-        },
+-        'defines': [
+-          # Needed by build/build_config.h processor architecture detection.
+-          '__ARMEL__',
+-          # Needed by base/third_party/nspr/prtime.cc.
+-          '__arm__',
+-          # Disable ValGrind. The assembly code it generates causes the build
+-          # to fail.
+-          'NVALGRIND',
+-        ],
+-      }],
+-    ],
+-  },
+-}
+\ No newline at end of file
+diff --git a/media/webrtc/trunk/build/copy_test_data_ios.gypi b/media/webrtc/trunk/build/copy_test_data_ios.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/copy_test_data_ios.gypi
++++ /dev/null
+@@ -1,48 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This file is meant to be included into an action to copy test data files into
+-# an iOS app bundle. To use this the following variables need to be defined:
+-#   test_data_files: list: paths to test data files or directories
+-#   test_data_prefix: string: a directory prefix that will be prepended to each
+-#                             output path.  Generally, this should be the base
+-#                             directory of the gypi file containing the unittest
+-#                             target (e.g. "base" or "chrome").
+-#
+-# To use this, create a gyp target with the following form:
+-# {
+-#   'target_name': 'my_unittests',
+-#   'conditions': [
+-#     ['OS == "ios"', {
+-#       'actions': [
+-#         {
+-#           'action_name': 'copy_test_data',
+-#           'variables': {
+-#             'test_data_files': [
+-#               'path/to/datafile.txt',
+-#               'path/to/data/directory/',
+-#             ]
+-#             'test_data_prefix' : 'prefix',
+-#           },
+-#           'includes': ['path/to/this/gypi/file'],
+-#         },
+-#       ],
+-#     }],
+-# }
+-#
+-
+-{
+-  'inputs': [
+-    '<!@pymod_do_main(copy_test_data_ios --inputs <(test_data_files))',
+-  ],
+-  'outputs': [
+-    '<!@pymod_do_main(copy_test_data_ios -o <(PRODUCT_DIR)/<(_target_name).app/<(test_data_prefix) --outputs <(test_data_files))',
+-  ],
+-  'action': [
+-    'python',
+-    '<(DEPTH)/build/copy_test_data_ios.py',
+-    '-o', '<(PRODUCT_DIR)/<(_target_name).app/<(test_data_prefix)',
+-    '<(_inputs)',
+-  ],
+-}
+diff --git a/media/webrtc/trunk/build/filename_rules.gypi b/media/webrtc/trunk/build/filename_rules.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/filename_rules.gypi
++++ /dev/null
+@@ -1,96 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This gypi file defines the patterns used for determining whether a
+-# file is excluded from the build on a given platform.  It is
+-# included by common.gypi for chromium_code.
+-
+-{
+-  'target_conditions': [
+-    ['OS!="win" or >(nacl_untrusted_build)==1', {
+-      'sources/': [ ['exclude', '_win(_unittest)?\\.(h|cc)$'],
+-                    ['exclude', '(^|/)win/'],
+-                    ['exclude', '(^|/)win_[^/]*\\.(h|cc)$'] ],
+-    }],
+-    ['OS!="mac" or >(nacl_untrusted_build)==1', {
+-      'sources/': [ ['exclude', '_(cocoa|mac)(_unittest)?\\.(h|cc|mm?)$'],
+-                    ['exclude', '(^|/)(cocoa|mac)/'] ],
+-    }],
+-    ['OS!="ios" or >(nacl_untrusted_build)==1', {
+-      'sources/': [ ['exclude', '_ios(_unittest)?\\.(h|cc|mm?)$'],
+-                    ['exclude', '(^|/)ios/'] ],
+-    }],
+-    ['(OS!="mac" and OS!="ios") or >(nacl_untrusted_build)==1', {
+-      'sources/': [ ['exclude', '\\.mm?$' ] ],
+-    }],
+-    # Do not exclude the linux files on *BSD since most of them can be
+-    # shared at this point.
+-    # In case a file is not needed, it is going to be excluded later on.
+-    # TODO(evan): the above is not correct; we shouldn't build _linux
+-    # files on non-linux.
+-    ['OS!="linux" and OS!="solaris" and <(os_bsd)!=1 or >(nacl_untrusted_build)==1', {
+-      'sources/': [
+-        ['exclude', '_linux(_unittest)?\\.(h|cc)$'],
+-        ['exclude', '(^|/)linux/'],
+-      ],
+-    }],
+-    ['OS!="android"', {
+-      'sources/': [
+-        ['exclude', '_android(_unittest)?\\.cc$'],
+-        ['exclude', '(^|/)android/'],
+-      ],
+-    }],
+-    ['OS=="win" and >(nacl_untrusted_build)==0', {
+-      'sources/': [
+-        ['exclude', '_posix(_unittest)?\\.(h|cc)$'],
+-        ['exclude', '(^|/)posix/'],
+-      ],
+-    }],
+-    ['<(chromeos)!=1 or >(nacl_untrusted_build)==1', {
+-      'sources/': [ ['exclude', '_chromeos(_unittest)?\\.(h|cc)$'] ]
+-    }],
+-    ['>(nacl_untrusted_build)==0', {
+-      'sources/': [
+-        ['exclude', '_nacl(_unittest)?\\.(h|cc)$'],
+-      ],
+-    }],
+-    ['OS!="linux" and OS!="solaris" and <(os_bsd)!=1 or >(nacl_untrusted_build)==1', {
+-      'sources/': [
+-        ['exclude', '_xdg(_unittest)?\\.(h|cc)$'],
+-      ],
+-    }],
+-    ['<(use_x11)!=1 or >(nacl_untrusted_build)==1', {
+-      'sources/': [
+-        ['exclude', '_(x|x11)(_unittest)?\\.(h|cc)$'],
+-        ['exclude', '(^|/)x11_[^/]*\\.(h|cc)$'],
+-      ],
+-    }],
+-    ['(<(toolkit_uses_gtk)!=1 or >(nacl_untrusted_build)==1) and (build_with_mozilla==0)', {
+-      'sources/': [
+-        ['exclude', '_gtk(_browsertest|_unittest)?\\.(h|cc)$'],
+-        ['exclude', '(^|/)gtk/'],
+-        ['exclude', '(^|/)gtk_[^/]*\\.(h|cc)$'],
+-      ],
+-    }],
+-    ['<(toolkit_views)==0 or >(nacl_untrusted_build)==1', {
+-      'sources/': [ ['exclude', '_views\\.(h|cc)$'] ]
+-    }],
+-    ['<(use_aura)==0 or >(nacl_untrusted_build)==1', {
+-      'sources/': [ ['exclude', '_aura(_unittest)?\\.(h|cc)$'],
+-                    ['exclude', '(^|/)aura/'],
+-      ]
+-    }],
+-    ['<(use_aura)==0 or <(use_x11)==0 or >(nacl_untrusted_build)==1', {
+-      'sources/': [ ['exclude', '_aurax11\\.(h|cc)$'] ]
+-    }],
+-    ['<(use_aura)==0 or OS!="win" or >(nacl_untrusted_build)==1', {
+-      'sources/': [ ['exclude', '_aurawin\\.(h|cc)$'] ]
+-    }],
+-    ['<(use_ash)==0 or >(nacl_untrusted_build)==1', {
+-      'sources/': [ ['exclude', '_ash(_unittest)?\\.(h|cc)$'],
+-                    ['exclude', '(^|/)ash/'],
+-      ]
+-    }],
+-  ]
+-}
+diff --git a/media/webrtc/trunk/build/grit_action.gypi b/media/webrtc/trunk/build/grit_action.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/grit_action.gypi
++++ /dev/null
+@@ -1,33 +0,0 @@
+-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This file is meant to be included into an action to invoke grit in a
+-# consistent manner. To use this the following variables need to be
+-# defined:
+-#   grit_grd_file: string: grd file path
+-#   grit_out_dir: string: the output directory path
+-
+-# It would be really nice to do this with a rule instead of actions, but it
+-# would need to determine inputs and outputs via grit_info on a per-file
+-# basis. GYP rules don’t currently support that. They could be extended to
+-# do this, but then every generator would need to be updated to handle this.
+-
+-{
+-  'variables': {
+-    'grit_cmd': ['python', '<(DEPTH)/tools/grit/grit.py'],
+-  },
+-  'inputs': [
+-    '<!@pymod_do_main(grit_info <@(grit_defines) --inputs <(grit_grd_file))',
+-  ],
+-  'outputs': [
+-    '<!@pymod_do_main(grit_info <@(grit_defines) --outputs \'<(grit_out_dir)\' <(grit_grd_file))',
+-  ],
+-  'action': ['<@(grit_cmd)',
+-             '-i', '<(grit_grd_file)', 'build',
+-             '-fGRIT_DIR/../gritsettings/resource_ids',
+-             '-o', '<(grit_out_dir)',
+-             '<@(grit_defines)' ],
+-  'msvs_cygwin_shell': 0,
+-  'message': 'Generating resources from <(grit_grd_file)',
+-}
+diff --git a/media/webrtc/trunk/build/grit_target.gypi b/media/webrtc/trunk/build/grit_target.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/grit_target.gypi
++++ /dev/null
+@@ -1,30 +0,0 @@
+-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This file is meant to be included into a target that will have one or more
+-# uses of grit_action.gypi. To use this the following variables need to be
+-# defined:
+-#   grit_out_dir: string: the output directory path
+-
+-# NOTE: This file is optional, not all targets that use grit include it, some
+-# do their own custom directives instead.
+-{
+-  'conditions': [
+-    # If the target is a direct binary, it needs to be able to find the header,
+-    # otherwise it probably a supporting target just for grit so the include
+-    # dir needs to be set on anything that depends on this action.
+-    ['_type=="executable" or _type=="shared_library" or \
+-      _type=="loadable_module" or _type=="static_library"', {
+-      'include_dirs': [
+-        '<(grit_out_dir)',
+-      ],
+-    }, {
+-      'direct_dependent_settings': {
+-        'include_dirs': [
+-          '<(grit_out_dir)',
+-        ],
+-      },
+-    }],
+-  ],
+-}
+diff --git a/media/webrtc/trunk/build/gyp_chromium b/media/webrtc/trunk/build/gyp_chromium
+deleted file mode 100755
+--- a/media/webrtc/trunk/build/gyp_chromium
++++ /dev/null
+@@ -1,12 +0,0 @@
+-#!/usr/bin/env python
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# Simple launcher script for gyp_chromium.py.
+-# TODO(sbc): This should probably be shell script but for historical
+-# reasons (all the python code used to live in this script without a
+-# .py extension, and was often run as 'python gyp_chromium') it is
+-# currently still python.
+-
+-execfile(__file__ + '.py')
+diff --git a/media/webrtc/trunk/build/gyp_chromium.py b/media/webrtc/trunk/build/gyp_chromium.py
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/gyp_chromium.py
++++ /dev/null
+@@ -1,68 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-"""This script is now only used by the closure_compilation builders."""
+-
+-import argparse
+-import glob
+-import gyp_environment
+-import os
+-import shlex
+-import sys
+-
+-script_dir = os.path.dirname(os.path.realpath(__file__))
+-chrome_src = os.path.abspath(os.path.join(script_dir, os.pardir))
+-
+-sys.path.insert(0, os.path.join(chrome_src, 'tools', 'gyp', 'pylib'))
+-import gyp
+-
+-
+-def ProcessGypDefinesItems(items):
+-  """Converts a list of strings to a list of key-value pairs."""
+-  result = []
+-  for item in items:
+-    tokens = item.split('=', 1)
+-    # Some GYP variables have hyphens, which we don't support.
+-    if len(tokens) == 2:
+-      result += [(tokens[0], tokens[1])]
+-    else:
+-      # No value supplied, treat it as a boolean and set it. Note that we
+-      # use the string '1' here so we have a consistent definition whether
+-      # you do 'foo=1' or 'foo'.
+-      result += [(tokens[0], '1')]
+-  return result
+-
+-
+-def GetSupplementalFiles():
+-  return []
+-
+-
+-def GetGypVars(_):
+-  """Returns a dictionary of all GYP vars."""
+-  # GYP defines from the environment.
+-  env_items = ProcessGypDefinesItems(
+-      shlex.split(os.environ.get('GYP_DEFINES', '')))
+-
+-  # GYP defines from the command line.
+-  parser = argparse.ArgumentParser()
+-  parser.add_argument('-D', dest='defines', action='append', default=[])
+-  cmdline_input_items = parser.parse_known_args()[0].defines
+-  cmdline_items = ProcessGypDefinesItems(cmdline_input_items)
+-
+-  return dict(env_items + cmdline_items)
+-
+-
+-def main():
+-  gyp_environment.SetEnvironment()
+-
+-  print 'Updating projects from gyp files...'
+-  sys.stdout.flush()
+-  sys.exit(gyp.main(sys.argv[1:] + [
+-      '--check',
+-      '--no-circular-check',
+-      '-I', os.path.join(script_dir, 'common.gypi'),
+-      '-D', 'gyp_output_dir=out']))
+-
+-if __name__ == '__main__':
+-  sys.exit(main())
+diff --git a/media/webrtc/trunk/build/gyp_environment.py b/media/webrtc/trunk/build/gyp_environment.py
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/gyp_environment.py
++++ /dev/null
+@@ -1,30 +0,0 @@
+-# Copyright 2014 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-"""
+-Sets up various automatic gyp environment variables. These are used by
+-gyp_chromium and landmines.py which run at different stages of runhooks. To
+-make sure settings are consistent between them, all setup should happen here.
+-"""
+-
+-import gyp_helper
+-import os
+-import sys
+-import vs_toolchain
+-
+-def SetEnvironment():
+-  """Sets defaults for GYP_* variables."""
+-  gyp_helper.apply_chromium_gyp_env()
+-
+-  # Default to ninja on linux and windows, but only if no generator has
+-  # explicitly been set.
+-  # Also default to ninja on mac, but only when not building chrome/ios.
+-  # . -f / --format has precedence over the env var, no need to check for it
+-  # . set the env var only if it hasn't been set yet
+-  # . chromium.gyp_env has been applied to os.environ at this point already
+-  if sys.platform.startswith(('linux', 'win', 'freebsd', 'darwin')) and \
+-      not os.environ.get('GYP_GENERATORS'):
+-    os.environ['GYP_GENERATORS'] = 'ninja'
+-
+-  vs_toolchain.SetEnvironmentAndGetRuntimeDllDirs()
+diff --git a/media/webrtc/trunk/build/gyp_helper.py b/media/webrtc/trunk/build/gyp_helper.py
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/gyp_helper.py
++++ /dev/null
+@@ -1,68 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This file helps gyp_chromium and landmines correctly set up the gyp
+-# environment from chromium.gyp_env on disk
+-
+-import os
+-
+-SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
+-CHROME_SRC = os.path.dirname(SCRIPT_DIR)
+-
+-
+-def apply_gyp_environment_from_file(file_path):
+-  """Reads in a *.gyp_env file and applies the valid keys to os.environ."""
+-  if not os.path.exists(file_path):
+-    return
+-  with open(file_path, 'rU') as f:
+-    file_contents = f.read()
+-  try:
+-    file_data = eval(file_contents, {'__builtins__': None}, None)
+-  except SyntaxError, e:
+-    e.filename = os.path.abspath(file_path)
+-    raise
+-  supported_vars = (
+-      'CC',
+-      'CC_wrapper',
+-      'CC.host_wrapper',
+-      'CHROMIUM_GYP_FILE',
+-      'CHROMIUM_GYP_SYNTAX_CHECK',
+-      'CXX',
+-      'CXX_wrapper',
+-      'CXX.host_wrapper',
+-      'GYP_DEFINES',
+-      'GYP_GENERATOR_FLAGS',
+-      'GYP_CROSSCOMPILE',
+-      'GYP_GENERATOR_OUTPUT',
+-      'GYP_GENERATORS',
+-      'GYP_INCLUDE_FIRST',
+-      'GYP_INCLUDE_LAST',
+-      'GYP_MSVS_VERSION',
+-  )
+-  for var in supported_vars:
+-    file_val = file_data.get(var)
+-    if file_val:
+-      if var in os.environ:
+-        behavior = 'replaces'
+-        if var == 'GYP_DEFINES':
+-          result = file_val + ' ' + os.environ[var]
+-          behavior = 'merges with, and individual components override,'
+-        else:
+-          result = os.environ[var]
+-        print 'INFO: Environment value for "%s" %s value in %s' % (
+-            var, behavior, os.path.abspath(file_path)
+-        )
+-        string_padding = max(len(var), len(file_path), len('result'))
+-        print '      %s: %s' % (var.rjust(string_padding), os.environ[var])
+-        print '      %s: %s' % (file_path.rjust(string_padding), file_val)
+-        os.environ[var] = result
+-      else:
+-        os.environ[var] = file_val
+-
+-
+-def apply_chromium_gyp_env():
+-  if 'SKIP_CHROMIUM_GYP_ENV' not in os.environ:
+-    # Update the environment based on chromium.gyp_env
+-    path = os.path.join(os.path.dirname(CHROME_SRC), 'chromium.gyp_env')
+-    apply_gyp_environment_from_file(path)
+diff --git a/media/webrtc/trunk/build/gypi_to_gn.py b/media/webrtc/trunk/build/gypi_to_gn.py
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/gypi_to_gn.py
++++ /dev/null
+@@ -1,191 +0,0 @@
+-# Copyright 2014 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-"""Converts a given gypi file to a python scope and writes the result to stdout.
+-
+-USING THIS SCRIPT IN CHROMIUM
+-
+-Forking Python to run this script in the middle of GN is slow, especially on
+-Windows, and it makes both the GYP and GN files harder to follow. You can't
+-use "git grep" to find files in the GN build any more, and tracking everything
+-in GYP down requires a level of indirection. Any calls will have to be removed
+-and cleaned up once the GYP-to-GN transition is complete.
+-
+-As a result, we only use this script when the list of files is large and
+-frequently-changing. In these cases, having one canonical list outweights the
+-downsides.
+-
+-As of this writing, the GN build is basically complete. It's likely that all
+-large and frequently changing targets where this is appropriate use this
+-mechanism already. And since we hope to turn down the GYP build soon, the time
+-horizon is also relatively short. As a result, it is likely that no additional
+-uses of this script should every be added to the build. During this later part
+-of the transition period, we should be focusing more and more on the absolute
+-readability of the GN build.
+-
+-
+-HOW TO USE
+-
+-It is assumed that the file contains a toplevel dictionary, and this script
+-will return that dictionary as a GN "scope" (see example below). This script
+-does not know anything about GYP and it will not expand variables or execute
+-conditions.
+-
+-It will strip conditions blocks.
+-
+-A variables block at the top level will be flattened so that the variables
+-appear in the root dictionary. This way they can be returned to the GN code.
+-
+-Say your_file.gypi looked like this:
+-  {
+-     'sources': [ 'a.cc', 'b.cc' ],
+-     'defines': [ 'ENABLE_DOOM_MELON' ],
+-  }
+-
+-You would call it like this:
+-  gypi_values = exec_script("//build/gypi_to_gn.py",
+-                            [ rebase_path("your_file.gypi") ],
+-                            "scope",
+-                            [ "your_file.gypi" ])
+-
+-Notes:
+- - The rebase_path call converts the gypi file from being relative to the
+-   current build file to being system absolute for calling the script, which
+-   will have a different current directory than this file.
+-
+- - The "scope" parameter tells GN to interpret the result as a series of GN
+-   variable assignments.
+-
+- - The last file argument to exec_script tells GN that the given file is a
+-   dependency of the build so Ninja can automatically re-run GN if the file
+-   changes.
+-
+-Read the values into a target like this:
+-  component("mycomponent") {
+-    sources = gypi_values.sources
+-    defines = gypi_values.defines
+-  }
+-
+-Sometimes your .gypi file will include paths relative to a different
+-directory than the current .gn file. In this case, you can rebase them to
+-be relative to the current directory.
+-  sources = rebase_path(gypi_values.sources, ".",
+-                        "//path/gypi/input/values/are/relative/to")
+-
+-This script will tolerate a 'variables' in the toplevel dictionary or not. If
+-the toplevel dictionary just contains one item called 'variables', it will be
+-collapsed away and the result will be the contents of that dictinoary. Some
+-.gypi files are written with or without this, depending on how they expect to
+-be embedded into a .gyp file.
+-
+-This script also has the ability to replace certain substrings in the input.
+-Generally this is used to emulate GYP variable expansion. If you passed the
+-argument "--replace=<(foo)=bar" then all instances of "<(foo)" in strings in
+-the input will be replaced with "bar":
+-
+-  gypi_values = exec_script("//build/gypi_to_gn.py",
+-                            [ rebase_path("your_file.gypi"),
+-                              "--replace=<(foo)=bar"],
+-                            "scope",
+-                            [ "your_file.gypi" ])
+-
+-"""
+-
+-import gn_helpers
+-from optparse import OptionParser
+-import sys
+-
+-def LoadPythonDictionary(path):
+-  file_string = open(path).read()
+-  try:
+-    file_data = eval(file_string, {'__builtins__': None}, None)
+-  except SyntaxError, e:
+-    e.filename = path
+-    raise
+-  except Exception, e:
+-    raise Exception("Unexpected error while reading %s: %s" % (path, str(e)))
+-
+-  assert isinstance(file_data, dict), "%s does not eval to a dictionary" % path
+-
+-  # Flatten any variables to the top level.
+-  if 'variables' in file_data:
+-    file_data.update(file_data['variables'])
+-    del file_data['variables']
+-
+-  # Strip all elements that this script can't process.
+-  elements_to_strip = [
+-    'conditions',
+-    'target_conditions',
+-    'targets',
+-    'includes',
+-    'actions',
+-  ]
+-  for element in elements_to_strip:
+-    if element in file_data:
+-      del file_data[element]
+-
+-  return file_data
+-
+-
+-def ReplaceSubstrings(values, search_for, replace_with):
+-  """Recursively replaces substrings in a value.
+-
+-  Replaces all substrings of the "search_for" with "repace_with" for all
+-  strings occurring in "values". This is done by recursively iterating into
+-  lists as well as the keys and values of dictionaries."""
+-  if isinstance(values, str):
+-    return values.replace(search_for, replace_with)
+-
+-  if isinstance(values, list):
+-    return [ReplaceSubstrings(v, search_for, replace_with) for v in values]
+-
+-  if isinstance(values, dict):
+-    # For dictionaries, do the search for both the key and values.
+-    result = {}
+-    for key, value in values.items():
+-      new_key = ReplaceSubstrings(key, search_for, replace_with)
+-      new_value = ReplaceSubstrings(value, search_for, replace_with)
+-      result[new_key] = new_value
+-    return result
+-
+-  # Assume everything else is unchanged.
+-  return values
+-
+-def main():
+-  parser = OptionParser()
+-  parser.add_option("-r", "--replace", action="append",
+-    help="Replaces substrings. If passed a=b, replaces all substrs a with b.")
+-  (options, args) = parser.parse_args()
+-
+-  if len(args) != 1:
+-    raise Exception("Need one argument which is the .gypi file to read.")
+-
+-  data = LoadPythonDictionary(args[0])
+-  if options.replace:
+-    # Do replacements for all specified patterns.
+-    for replace in options.replace:
+-      split = replace.split('=')
+-      # Allow "foo=" to replace with nothing.
+-      if len(split) == 1:
+-        split.append('')
+-      assert len(split) == 2, "Replacement must be of the form 'key=value'."
+-      data = ReplaceSubstrings(data, split[0], split[1])
+-
+-  # Sometimes .gypi files use the GYP syntax with percents at the end of the
+-  # variable name (to indicate not to overwrite a previously-defined value):
+-  #   'foo%': 'bar',
+-  # Convert these to regular variables.
+-  for key in data:
+-    if len(key) > 1 and key[len(key) - 1] == '%':
+-      data[key[:-1]] = data[key]
+-      del data[key]
+-
+-  print gn_helpers.ToGNString(data)
+-
+-if __name__ == '__main__':
+-  try:
+-    main()
+-  except Exception, e:
+-    print str(e)
+-    sys.exit(1)
+diff --git a/media/webrtc/trunk/build/internal/release_defaults.gypi b/media/webrtc/trunk/build/internal/release_defaults.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/internal/release_defaults.gypi
++++ /dev/null
+@@ -1,18 +0,0 @@
+-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-{
+-  'msvs_settings': {
+-    'VCCLCompilerTool': {
+-      'StringPooling': 'true',
+-    },
+-    'VCLinkerTool': {
+-      # No incremental linking.
+-      'LinkIncremental': '1',
+-      # Eliminate Unreferenced Data (/OPT:REF).
+-      'OptimizeReferences': '2',
+-      # Folding on (/OPT:ICF).
+-      'EnableCOMDATFolding': '2',
+-    },
+-  },
+-}
+diff --git a/media/webrtc/trunk/build/internal/release_impl.gypi b/media/webrtc/trunk/build/internal/release_impl.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/internal/release_impl.gypi
++++ /dev/null
+@@ -1,17 +0,0 @@
+-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-{
+-  'includes': ['release_defaults.gypi'],
+-  'msvs_settings': {
+-    'VCCLCompilerTool': {
+-      'OmitFramePointers': 'false',
+-      # The above is not sufficient (http://crbug.com/106711): it
+-      # simply eliminates an explicit "/Oy", but both /O2 and /Ox
+-      # perform FPO regardless, so we must explicitly disable.
+-      # We still want the false setting above to avoid having
+-      # "/Oy /Oy-" and warnings about overriding.
+-      'AdditionalOptions': ['/Oy-'],
+-    },
+-  },
+-}
+diff --git a/media/webrtc/trunk/build/internal/release_impl_official.gypi b/media/webrtc/trunk/build/internal/release_impl_official.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/internal/release_impl_official.gypi
++++ /dev/null
+@@ -1,43 +0,0 @@
+-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-{
+-  'includes': ['release_defaults.gypi'],
+-  'defines': ['OFFICIAL_BUILD'],
+-  'msvs_settings': {
+-    'VCCLCompilerTool': {
+-      'InlineFunctionExpansion': '2',
+-      'EnableIntrinsicFunctions': 'true',
+-      'EnableFiberSafeOptimizations': 'true',
+-      'OmitFramePointers': 'false',
+-      # The above is not sufficient (http://crbug.com/106711): it
+-      # simply eliminates an explicit "/Oy", but both /O2 and /Ox
+-      # perform FPO regardless, so we must explicitly disable.
+-      # We still want the false setting above to avoid having
+-      # "/Oy /Oy-" and warnings about overriding.
+-      'AdditionalOptions': ['/Oy-'],
+-    },
+-    'VCLibrarianTool': {
+-      'AdditionalOptions': [
+-        '/ltcg',
+-        '/expectedoutputsize:120000000'
+-      ],
+-    },
+-    'VCLinkerTool': {
+-      'AdditionalOptions': [
+-        '/time',
+-        # This may reduce memory fragmentation during linking.
+-        # The expected size is 40*1024*1024, which gives us about 10M of
+-        # headroom as of Dec 16, 2011.
+-        '/expectedoutputsize:41943040',
+-      ],
+-      'LinkTimeCodeGeneration': '1',
+-      # The /PROFILE flag causes the linker to add a "FIXUP" debug stream to
+-      # the generated PDB. According to MSDN documentation, this flag is only
+-      # available (or perhaps supported) in the Enterprise (team development)
+-      # version of Visual Studio. If this blocks your official build, simply
+-      # comment out this line, then  re-run "gclient runhooks".
+-      'Profile': 'true',
+-    },
+-  },
+-}
+diff --git a/media/webrtc/trunk/build/ios/mac_build.gypi b/media/webrtc/trunk/build/ios/mac_build.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/ios/mac_build.gypi
++++ /dev/null
+@@ -1,79 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# Xcode throws an error if an iOS target depends on a Mac OS X target. So
+-# any place a utility program needs to be build and run, an action is
+-# used to run ninja as script to work around this.
+-# Example:
+-# {
+-#   'target_name': 'foo',
+-#   'type': 'none',
+-#   'variables': {
+-#     # The name of a directory used for ninja. This cannot be shared with
+-#     # another mac build.
+-#     'ninja_output_dir': 'ninja-foo',
+-#     # The list of all the gyp files that contain the targets to run.
+-#     're_run_targets': [
+-#       'foo.gyp',
+-#     ],
+-#   },
+-#   'includes': ['path_to/mac_build.gypi'],
+-#   'actions': [
+-#     {
+-#       'action_name': 'compile foo',
+-#       'inputs': [],
+-#       'outputs': [],
+-#       'action': [
+-#         '<@(ninja_cmd)',
+-#         # All the targets to build.
+-#         'foo1',
+-#         'foo2',
+-#       ],
+-#     },
+-#   ],
+-# }
+-{
+-  'variables': {
+-    # Convenience variable pointing to the ninja product directory.
+-    'ninja_product_dir':
+-      '<(DEPTH)/xcodebuild/<(ninja_output_dir)/<(CONFIGURATION_NAME)',
+-
+-    # Common ninja command line flags.
+-    'ninja_cmd': [
+-      # Bounce through clean_env to clean up the environment so things
+-      # set by the iOS build don't pollute the Mac build.
+-      '<(DEPTH)/build/ios/clean_env.py',
+-      # ninja must be found in the PATH.
+-      'ADD_TO_PATH=<!(echo $PATH)',
+-      'ninja',
+-      '-C',
+-      '<(ninja_product_dir)',
+-    ],
+-
+-    # Common syntax to rerun gyp to generate the Mac projects.
+-    're_run_gyp': [
+-      'build/gyp_chromium',
+-      # Don't use anything set for the iOS side of things.
+-      '--ignore-environment',
+-      # Generate for ninja
+-      '--format=ninja',
+-      # Generate files into xcodebuild/ninja
+-      '-Goutput_dir=xcodebuild/<(ninja_output_dir)',
+-      # nacl isn't in the iOS checkout, make sure it's turned off
+-      '-Ddisable_nacl=1',
+-      # Add a variable to handle specific cases for mac_build.
+-      '-Dios_mac_build=1',
+-      # Pass through the Mac SDK version.
+-      '-Dmac_sdk=<(mac_sdk)',
+-    ],
+-
+-    # Rerun gyp for each of the projects needed. This is what actually
+-    # generates the projects on disk.
+-    're_run_gyp_execution':
+-      '<!(cd <(DEPTH) && <@(re_run_gyp) <@(re_run_targets))',
+-  },
+-  # Since these are used to generate things needed by other targets, make
+-  # them hard dependencies so they are always built first.
+-  'hard_dependency': 1,
+-}
+diff --git a/media/webrtc/trunk/build/jar_file_jni_generator.gypi b/media/webrtc/trunk/build/jar_file_jni_generator.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/jar_file_jni_generator.gypi
++++ /dev/null
+@@ -1,53 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This file is meant to be included into a target to provide a rule
+-# to generate jni bindings for system Java-files in a consistent manner.
+-#
+-# To use this, create a gyp target with the following form:
+-# {
+-#   'target_name': 'android_jar_jni_headers',
+-#   'type': 'none',
+-#   'variables': {
+-#     'jni_gen_dir': 'chrome',
+-#     'input_java_class': 'java/io/InputStream.class',
+-#     'input_jar_file': '<(android_sdk)/android.jar',
+-#   },
+-#   'includes': [ '../build/jar_file_jni_generator.gypi' ],
+-# },
+-
+-{
+-  'variables': {
+-    'jni_generator': '<(DEPTH)/base/android/jni_generator/jni_generator.py',
+-  },
+-  'actions': [
+-    {
+-      'action_name': 'generate_jni_headers_from_jar_file',
+-      'inputs': [
+-        '<(jni_generator)',
+-        '<(input_jar_file)',
+-      ],
+-      'variables': {
+-        'java_class_name': '<!(basename <(input_java_class)|sed "s/\.class//")'
+-      },
+-      'outputs': [
+-        '<(SHARED_INTERMEDIATE_DIR)/<(jni_gen_dir)/jni/<(java_class_name)_jni.h',
+-      ],
+-      'action': [
+-        '<(jni_generator)',
+-        '-j',
+-        '<(input_jar_file)',
+-        '--input_file',
+-        '<(input_java_class)',
+-        '--output_dir',
+-        '<(SHARED_INTERMEDIATE_DIR)/<(jni_gen_dir)/jni',
+-      ],
+-      'message': 'Generating JNI bindings from  <(input_jar_file)/<(input_java_class)',
+-      'process_outputs_as_sources': 1,
+-    },
+-  ],
+-  # This target exports a hard dependency because it generates header
+-  # files.
+-  'hard_dependency': 1,
+-}
+diff --git a/media/webrtc/trunk/build/java.gypi b/media/webrtc/trunk/build/java.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/java.gypi
++++ /dev/null
+@@ -1,90 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This file is meant to be included into a target to provide a rule
+-# to build Java in a consistent manner.
+-#
+-# To use this, create a gyp target with the following form:
+-# {
+-#   'target_name': 'my-package_java',
+-#   'type': 'none',
+-#   'variables': {
+-#     'package_name': 'my-package',
+-#     'java_in_dir': 'path/to/package/root',
+-#   },
+-#   'includes': ['path/to/this/gypi/file'],
+-# }
+-#
+-# The generated jar-file will be:
+-#   <(PRODUCT_DIR)/lib.java/chromium_<(package_name).jar
+-# Required variables:
+-#  package_name - Used to name the intermediate output directory and in the
+-#    names of some output files.
+-#  java_in_dir - The top-level java directory. The src should be in
+-#    <java_in_dir>/src.
+-# Optional/automatic variables:
+-#  additional_input_paths - These paths will be included in the 'inputs' list to
+-#    ensure that this target is rebuilt when one of these paths changes.
+-#  additional_src_dirs - Additional directories with .java files to be compiled
+-#    and included in the output of this target.
+-#  generated_src_dirs - Same as additional_src_dirs except used for .java files
+-#    that are generated at build time. This should be set automatically by a
+-#    target's dependencies. The .java files in these directories are not
+-#    included in the 'inputs' list (unlike additional_src_dirs).
+-#  input_jars_paths - The path to jars to be included in the classpath. This
+-#    should be filled automatically by depending on the appropriate targets.
+-
+-{
+-  'dependencies': [
+-    '<(DEPTH)/build/build_output_dirs_android.gyp:build_output_dirs'
+-  ],
+-  # This all_dependent_settings is used for java targets only. This will add the
+-  # chromium_<(package_name) jar to the classpath of dependent java targets.
+-  'all_dependent_settings': {
+-    'variables': {
+-      'input_jars_paths': ['<(PRODUCT_DIR)/lib.java/chromium_<(package_name).jar'],
+-    },
+-  },
+-  'variables': {
+-    'input_jars_paths': [],
+-    'additional_src_dirs': [],
+-    'additional_input_paths': [],
+-    'generated_src_dirs': [],
+-  },
+-  'actions': [
+-    {
+-      'action_name': 'ant_<(package_name)',
+-      'message': 'Building <(package_name) java sources.',
+-      'inputs': [
+-        'android/ant/common.xml',
+-        'android/ant/chromium-jars.xml',
+-        '>!@(find >(java_in_dir) >(additional_src_dirs) -name "*.java")',
+-        '>@(input_jars_paths)',
+-        '>@(additional_input_paths)',
+-      ],
+-      'outputs': [
+-        '<(PRODUCT_DIR)/lib.java/chromium_<(package_name).jar',
+-      ],
+-      'action': [
+-        'ant',
+-        '-DCONFIGURATION_NAME=<(CONFIGURATION_NAME)',
+-        '-DANDROID_SDK=<(android_sdk)',
+-        '-DANDROID_SDK_ROOT=<(android_sdk_root)',
+-        '-DANDROID_SDK_TOOLS=<(android_sdk_tools)',
+-        '-DANDROID_SDK_VERSION=<(android_sdk_version)',
+-        '-DANDROID_GDBSERVER=<(android_gdbserver)',
+-        '-DPRODUCT_DIR=<(ant_build_out)',
+-
+-        '-DADDITIONAL_SRC_DIRS=>(additional_src_dirs)',
+-        '-DGENERATED_SRC_DIRS=>(generated_src_dirs)',
+-        '-DINPUT_JARS_PATHS=>(input_jars_paths)',
+-        '-DPACKAGE_NAME=<(package_name)',
+-
+-        '-Dbasedir=<(java_in_dir)',
+-        '-buildfile',
+-        '<(DEPTH)/build/android/ant/chromium-jars.xml'
+-      ]
+-    },
+-  ],
+-}
+diff --git a/media/webrtc/trunk/build/java_aidl.gypi b/media/webrtc/trunk/build/java_aidl.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/java_aidl.gypi
++++ /dev/null
+@@ -1,58 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This file is meant to be included into a target to provide a rule
+-# to build Java aidl files in a consistent manner.
+-#
+-# To use this, create a gyp target with the following form:
+-# {
+-#   'target_name': 'aidl_aidl-file-name',
+-#   'type': 'none',
+-#   'variables': {
+-#     'package_name': <name-of-package>
+-#     'aidl_interface_file': '<interface-path>/<interface-file>.aidl',
+-#   },
+-#   'sources': {
+-#     '<input-path1>/<input-file1>.aidl',
+-#     '<input-path2>/<input-file2>.aidl',
+-#     ...
+-#   },
+-#   'includes': ['<path-to-this-file>/java_aidl.gypi'],
+-# }
+-#
+-#
+-# The generated java files will be:
+-#   <(PRODUCT_DIR)/lib.java/<input-file1>.java
+-#   <(PRODUCT_DIR)/lib.java/<input-file2>.java
+-#   ...
+-#
+-# TODO(cjhopman): dependents need to rebuild when this target's inputs have changed.
+-
+-{
+-  'direct_dependent_settings': {
+-    'variables': {
+-      'generated_src_dirs': ['<(SHARED_INTERMEDIATE_DIR)/<(package_name)/aidl/'],
+-    },
+-  },
+-  'rules': [
+-    {
+-      'rule_name': 'compile_aidl',
+-      'extension': 'aidl',
+-      'inputs': [
+-        '<(android_sdk)/framework.aidl',
+-        '<(aidl_interface_file)',
+-      ],
+-      'outputs': [
+-        '<(SHARED_INTERMEDIATE_DIR)/<(package_name)/aidl/<(RULE_INPUT_ROOT).java',
+-      ],
+-      'action': [
+-        '<(android_sdk_tools)/aidl',
+-        '-p<(android_sdk)/framework.aidl',
+-        '-p<(aidl_interface_file)',
+-        '<(RULE_INPUT_PATH)',
+-        '<(SHARED_INTERMEDIATE_DIR)/<(package_name)/aidl/<(RULE_INPUT_ROOT).java',
+-      ],
+-    },
+-  ],
+-}
+diff --git a/media/webrtc/trunk/build/jni_generator.gypi b/media/webrtc/trunk/build/jni_generator.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/jni_generator.gypi
++++ /dev/null
+@@ -1,58 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This file is meant to be included into a target to provide a rule
+-# to generate jni bindings for Java-files in a consistent manner.
+-#
+-# To use this, create a gyp target with the following form:
+-#  {
+-#    'target_name': 'base_jni_headers',
+-#    'type': 'none',
+-#    'sources': [
+-#      'android/java/src/org/chromium/base/BuildInfo.java',
+-#      ...
+-#      ...
+-#      'android/java/src/org/chromium/base/SystemMessageHandler.java',
+-#    ],
+-#    'variables': {
+-#      'jni_gen_dir': 'base',
+-#    },
+-#    'includes': [ '../build/jni_generator.gypi' ],
+-#  },
+-#
+-# The generated file name pattern can be seen on the "outputs" section below.
+-# (note that RULE_INPUT_ROOT is the basename for the java file).
+-#
+-# See base/android/jni_generator/jni_generator.py for more info about the
+-# format of generating JNI bindings.
+-
+-{
+-  'variables': {
+-    'jni_generator': '<(DEPTH)/base/android/jni_generator/jni_generator.py',
+-  },
+-  'rules': [
+-    {
+-      'rule_name': 'generate_jni_headers',
+-      'extension': 'java',
+-      'inputs': [
+-        '<(jni_generator)',
+-      ],
+-      'outputs': [
+-        '<(SHARED_INTERMEDIATE_DIR)/<(jni_gen_dir)/jni/<(RULE_INPUT_ROOT)_jni.h',
+-      ],
+-      'action': [
+-        '<(jni_generator)',
+-        '--input_file',
+-        '<(RULE_INPUT_PATH)',
+-        '--output_dir',
+-        '<(SHARED_INTERMEDIATE_DIR)/<(jni_gen_dir)/jni',
+-      ],
+-      'message': 'Generating JNI bindings from <(RULE_INPUT_PATH)',
+-      'process_outputs_as_sources': 1,
+-    },
+-  ],
+-  # This target exports a hard dependency because it generates header
+-  # files.
+-  'hard_dependency': 1,
+-}
+diff --git a/media/webrtc/trunk/build/json_schema_bundle_compile.gypi b/media/webrtc/trunk/build/json_schema_bundle_compile.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/json_schema_bundle_compile.gypi
++++ /dev/null
+@@ -1,62 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-{
+-  'variables': {
+-    # When including this gypi, the following variables must be set:
+-    #   idl_schema_files: an array of idl files that comprise the api model.
+-    #   cc_dir: path to generated files
+-    #   root_namespace: the C++ namespace that all generated files go under
+-    # Functions and namespaces can be excluded by setting "nocompile" to true.
+-    'api_gen_dir': '<(DEPTH)/tools/json_schema_compiler',
+-    'api_gen': '<(api_gen_dir)/compiler.py',
+-  },
+-  'actions': [
+-    {
+-      'action_name': 'genapi_bundle',
+-      'inputs': [
+-        '<(api_gen_dir)/cc_generator.py',
+-        '<(api_gen_dir)/code.py',
+-        '<(api_gen_dir)/compiler.py',
+-        '<(api_gen_dir)/cpp_type_generator.py',
+-        '<(api_gen_dir)/cpp_util.py',
+-        '<(api_gen_dir)/h_generator.py',
+-        '<(api_gen_dir)/idl_schema.py',
+-        '<(api_gen_dir)/json_schema.py',
+-        '<(api_gen_dir)/model.py',
+-        '<(api_gen_dir)/schema_bundle_generator.py',
+-        '<(api_gen_dir)/util_cc_helper.py',
+-        '<@(idl_schema_files)',
+-      ],
+-      'outputs': [
+-        '<(SHARED_INTERMEDIATE_DIR)/<(cc_dir)/generated_api.h',
+-        '<(SHARED_INTERMEDIATE_DIR)/<(cc_dir)/generated_schemas.h',
+-        '<(SHARED_INTERMEDIATE_DIR)/<(cc_dir)/generated_schemas.cc',
+-      ],
+-      'action': [
+-        'python',
+-        '<(api_gen)',
+-        '--root=<(DEPTH)',
+-        '--destdir=<(SHARED_INTERMEDIATE_DIR)',
+-        '--namespace=<(root_namespace)',
+-        '--bundle',
+-        '<@(idl_schema_files)',
+-      ],
+-      'message': 'Generating C++ API bundle code',
+-      'process_outputs_as_sources': 1,
+-    }
+-  ],
+-  'include_dirs': [
+-    '<(SHARED_INTERMEDIATE_DIR)',
+-    '<(DEPTH)',
+-  ],
+-  'direct_dependent_settings': {
+-    'include_dirs': [
+-      '<(SHARED_INTERMEDIATE_DIR)',
+-    ]
+-  },
+-  # This target exports a hard dependency because it generates header
+-  # files.
+-  'hard_dependency': 1,
+-}
+diff --git a/media/webrtc/trunk/build/json_schema_compile.gypi b/media/webrtc/trunk/build/json_schema_compile.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/json_schema_compile.gypi
++++ /dev/null
+@@ -1,110 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-{
+-  'variables': {
+-    # When including this gypi, the following variables must be set:
+-    #   json_schema_files: a list of json files that comprise the api model.
+-    #   idl_schema_files: a list of IDL files that comprise the api model.
+-    #   cc_dir: path to generated files
+-    #   root_namespace: the C++ namespace that all generated files go under
+-    # Functions and namespaces can be excluded by setting "nocompile" to true.
+-    'api_gen_dir': '<(DEPTH)/tools/json_schema_compiler',
+-    'api_gen': '<(api_gen_dir)/compiler.py',
+-  },
+-  'rules': [
+-    {
+-      'rule_name': 'genapi',
+-      'extension': 'json',
+-      'inputs': [
+-        '<(api_gen_dir)/any.cc',
+-        '<(api_gen_dir)/any.h',
+-        '<(api_gen_dir)/any_helper.py',
+-        '<(api_gen_dir)/cc_generator.py',
+-        '<(api_gen_dir)/code.py',
+-        '<(api_gen_dir)/compiler.py',
+-        '<(api_gen_dir)/cpp_type_generator.py',
+-        '<(api_gen_dir)/cpp_util.py',
+-        '<(api_gen_dir)/h_generator.py',
+-        '<(api_gen_dir)/json_schema.py',
+-        '<(api_gen_dir)/model.py',
+-        '<(api_gen_dir)/util.cc',
+-        '<(api_gen_dir)/util.h',
+-        '<(api_gen_dir)/util_cc_helper.py',
+-        # TODO(calamity): uncomment this when gyp on windows behaves like other
+-        # platforms. List expansions of filepaths in inputs expand to different
+-        # things.
+-        # '<@(json_schema_files)',
+-      ],
+-      'outputs': [
+-        '<(SHARED_INTERMEDIATE_DIR)/<(cc_dir)/<(RULE_INPUT_ROOT).cc',
+-        '<(SHARED_INTERMEDIATE_DIR)/<(cc_dir)/<(RULE_INPUT_ROOT).h',
+-      ],
+-      'action': [
+-        'python',
+-        '<(api_gen)',
+-        '<(RULE_INPUT_PATH)',
+-        '--root=<(DEPTH)',
+-        '--destdir=<(SHARED_INTERMEDIATE_DIR)',
+-        '--namespace=<(root_namespace)',
+-      ],
+-      'message': 'Generating C++ code from <(RULE_INPUT_PATH) json files',
+-      'process_outputs_as_sources': 1,
+-    },
+-    {
+-      'rule_name': 'genapi_idl',
+-      'msvs_external_rule': 1,
+-      'extension': 'idl',
+-      'inputs': [
+-        '<(api_gen_dir)/any.cc',
+-        '<(api_gen_dir)/any.h',
+-        '<(api_gen_dir)/any_helper.py',
+-        '<(api_gen_dir)/cc_generator.py',
+-        '<(api_gen_dir)/code.py',
+-        '<(api_gen_dir)/compiler.py',
+-        '<(api_gen_dir)/cpp_type_generator.py',
+-        '<(api_gen_dir)/cpp_util.py',
+-        '<(api_gen_dir)/h_generator.py',
+-        '<(api_gen_dir)/idl_schema.py',
+-        '<(api_gen_dir)/model.py',
+-        '<(api_gen_dir)/util.cc',
+-        '<(api_gen_dir)/util.h',
+-        '<(api_gen_dir)/util_cc_helper.py',
+-        # TODO(calamity): uncomment this when gyp on windows behaves like other
+-        # platforms. List expansions of filepaths in inputs expand to different
+-        # things.
+-        # '<@(idl_schema_files)',
+-      ],
+-      'outputs': [
+-        '<(SHARED_INTERMEDIATE_DIR)/<(cc_dir)/<(RULE_INPUT_ROOT).cc',
+-        '<(SHARED_INTERMEDIATE_DIR)/<(cc_dir)/<(RULE_INPUT_ROOT).h',
+-      ],
+-      'action': [
+-        'python',
+-        '<(api_gen)',
+-        '<(RULE_INPUT_PATH)',
+-        '--root=<(DEPTH)',
+-        '--destdir=<(SHARED_INTERMEDIATE_DIR)',
+-        '--namespace=<(root_namespace)',
+-      ],
+-      'message': 'Generating C++ code from <(RULE_INPUT_PATH) IDL files',
+-      'process_outputs_as_sources': 1,
+-    },
+-  ],
+-  'include_dirs': [
+-    '<(SHARED_INTERMEDIATE_DIR)',
+-    '<(DEPTH)',
+-  ],
+-  'dependencies':[
+-    '<(DEPTH)/tools/json_schema_compiler/api_gen_util.gyp:api_gen_util',
+-  ],
+-  'direct_dependent_settings': {
+-    'include_dirs': [
+-      '<(SHARED_INTERMEDIATE_DIR)',
+-    ]
+-  },
+-  # This target exports a hard dependency because it generates header
+-  # files.
+-  'hard_dependency': 1,
+-}
+diff --git a/media/webrtc/trunk/build/nocompile.gypi b/media/webrtc/trunk/build/nocompile.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/nocompile.gypi
++++ /dev/null
+@@ -1,96 +0,0 @@
+-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This file is meant to be included into an target to create a unittest that
+-# invokes a set of no-compile tests.  A no-compile test is a test that asserts
+-# a particular construct will not compile.
+-#
+-# Also see:
+-#   http://dev.chromium.org/developers/testing/no-compile-tests
+-#
+-# To use this, create a gyp target with the following form:
+-# {
+-#   'target_name': 'my_module_nc_unittests',
+-#   'type': 'executable',
+-#   'sources': [
+-#     'nc_testset_1.nc',
+-#     'nc_testset_2.nc',
+-#   ],
+-#   'includes': ['path/to/this/gypi/file'],
+-# }
+-#
+-# The .nc files are C++ files that contain code we wish to assert will not
+-# compile.  Each individual test case in the file should be put in its own
+-# #ifdef section.  The expected output should be appended with a C++-style
+-# comment that has a python list of regular expressions.  This will likely
+-# be greater than 80-characters. Giving a solid expected output test is
+-# important so that random compile failures do not cause the test to pass.
+-#
+-# Example .nc file:
+-#
+-#   #if defined(TEST_NEEDS_SEMICOLON)  // [r"expected ',' or ';' at end of input"]
+-#
+-#   int a = 1
+-#
+-#   #elif defined(TEST_NEEDS_CAST)  // [r"invalid conversion from 'void*' to 'char*'"]
+-#
+-#   void* a = NULL;
+-#   char* b = a;
+-#
+-#   #endif
+-#
+-# If we needed disable TEST_NEEDS_SEMICOLON, then change the define to:
+-#
+-#   DISABLE_TEST_NEEDS_SEMICOLON
+-#   TEST_NEEDS_CAST
+-#
+-# The lines above are parsed by a regexp so avoid getting creative with the
+-# formatting or ifdef logic; it will likely just not work.
+-#
+-# Implementation notes:
+-# The .nc files are actually processed by a python script which executes the
+-# compiler and generates a .cc file that is empty on success, or will have a
+-# series of #error lines on failure, and a set of trivially passing gunit
+-# TEST() functions on success. This allows us to fail at the compile step when
+-# something goes wrong, and know during the unittest run that the test was at
+-# least processed when things go right.
+-
+-{
+-  # TODO(awong): Disabled until http://crbug.com/105388 is resolved.
+-  'sources/': [['exclude', '\\.nc$']],
+-  'conditions': [
+-    [ 'OS=="linux" and clang==0', {
+-      'rules': [
+-        {
+-          'variables': {
+-            'nocompile_driver': '<(DEPTH)/tools/nocompile_driver.py',
+-            'nc_result_path': ('<(INTERMEDIATE_DIR)/<(module_dir)/'
+-                               '<(RULE_INPUT_ROOT)_nc.cc'),
+-           },
+-          'rule_name': 'run_nocompile',
+-          'extension': 'nc',
+-          'inputs': [
+-            '<(nocompile_driver)',
+-          ],
+-          'outputs': [
+-            '<(nc_result_path)'
+-          ],
+-          'action': [
+-            'python',
+-            '<(nocompile_driver)',
+-            '4', # number of compilers to invoke in parallel.
+-            '<(RULE_INPUT_PATH)',
+-            '-Wall -Werror -Wfatal-errors -I<(DEPTH)',
+-            '<(nc_result_path)',
+-            ],
+-          'message': 'Generating no compile results for <(RULE_INPUT_PATH)',
+-          'process_outputs_as_sources': 1,
+-        },
+-      ],
+-    }, {
+-      'sources/': [['exclude', '\\.nc$']]
+-    }],  # 'OS=="linux" and clang=="0"'
+-  ],
+-}
+-
+diff --git a/media/webrtc/trunk/build/protoc.gypi b/media/webrtc/trunk/build/protoc.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/protoc.gypi
++++ /dev/null
+@@ -1,116 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# This file is meant to be included into a target to provide a rule
+-# to invoke protoc in a consistent manner.
+-#
+-# To use this, create a gyp target with the following form:
+-# {
+-#   'target_name': 'my_proto_lib',
+-#   'type': 'static_library',
+-#   'sources': [
+-#     'foo.proto',
+-#     'bar.proto',
+-#   ],
+-#   'variables': {
+-#     # Optional, see below: 'proto_in_dir': '.'
+-#     'proto_out_dir': 'dir/for/my_proto_lib'
+-#   },
+-#   'includes': ['path/to/this/gypi/file'],
+-# }
+-# If necessary, you may add normal .cc files to the sources list or other gyp
+-# dependencies.  The proto headers are guaranteed to be generated before any
+-# source files, even within this target, are compiled.
+-#
+-# The 'proto_in_dir' variable must be the relative path to the
+-# directory containing the .proto files.  If left out, it defaults to '.'.
+-#
+-# The 'proto_out_dir' variable specifies the path suffix that output
+-# files are generated under.  Targets that gyp-depend on my_proto_lib
+-# will be able to include the resulting proto headers with an include
+-# like:
+-#   #include "dir/for/my_proto_lib/foo.pb.h"
+-#
+-# If you need to add an EXPORT macro to a protobuf's c++ header, set the
+-# 'cc_generator_options' variable with the value: 'dllexport_decl=FOO_EXPORT:'
+-# e.g. 'dllexport_decl=BASE_EXPORT:'
+-#
+-# It is likely you also need to #include a file for the above EXPORT macro to
+-# work. You can do so with the 'cc_include' variable.
+-# e.g. 'base/base_export.h'
+-#
+-# Implementation notes:
+-# A proto_out_dir of foo/bar produces
+-#   <(SHARED_INTERMEDIATE_DIR)/protoc_out/foo/bar/{file1,file2}.pb.{cc,h}
+-#   <(SHARED_INTERMEDIATE_DIR)/pyproto/foo/bar/{file1,file2}_pb2.py
+-
+-{
+-  'variables': {
+-    'protoc_wrapper': '<(DEPTH)/tools/protoc_wrapper/protoc_wrapper.py',
+-    'protoc': '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)protoc<(EXECUTABLE_SUFFIX)',
+-    'cc_dir': '<(SHARED_INTERMEDIATE_DIR)/protoc_out/<(proto_out_dir)',
+-    'py_dir': '<(PRODUCT_DIR)/pyproto/<(proto_out_dir)',
+-    'cc_generator_options%': '',
+-    'cc_include%': '',
+-    'proto_in_dir%': '.',
+-  },
+-  'rules': [
+-    {
+-      'rule_name': 'genproto',
+-      'extension': 'proto',
+-      'inputs': [
+-        '<(protoc_wrapper)',
+-        '<(protoc)',
+-      ],
+-      'outputs': [
+-        '<(py_dir)/<(RULE_INPUT_ROOT)_pb2.py',
+-        '<(cc_dir)/<(RULE_INPUT_ROOT).pb.cc',
+-        '<(cc_dir)/<(RULE_INPUT_ROOT).pb.h',
+-      ],
+-      'action': [
+-        'python',
+-        '<(protoc_wrapper)',
+-        '--include',
+-        '<(cc_include)',
+-        '--protobuf',
+-        '<(cc_dir)/<(RULE_INPUT_ROOT).pb.h',
+-        '--',
+-        '<(protoc)',
+-        # Using the --arg val form (instead of --arg=val) allows gyp's msvs rule
+-        # generation to correct 'val' which is a path.
+-        '--proto_path','<(proto_in_dir)',
+-        # Naively you'd use <(RULE_INPUT_PATH) here, but protoc requires
+-        # --proto_path is a strict prefix of the path given as an argument.
+-        '<(proto_in_dir)/<(RULE_INPUT_ROOT)<(RULE_INPUT_EXT)',
+-        '--cpp_out', '<(cc_generator_options)<(cc_dir)',
+-        '--python_out', '<(py_dir)',
+-      ],
+-      'msvs_cygwin_shell': 0,
+-      'message': 'Generating C++ and Python code from <(RULE_INPUT_PATH)',
+-      'process_outputs_as_sources': 1,
+-    },
+-  ],
+-  'dependencies': [
+-    '<(DEPTH)/third_party/protobuf/protobuf.gyp:protoc#host',
+-    '<(DEPTH)/third_party/protobuf/protobuf.gyp:protobuf_lite',
+-  ],
+-  'include_dirs': [
+-    '<(SHARED_INTERMEDIATE_DIR)/protoc_out',
+-    '<(DEPTH)',
+-  ],
+-  'direct_dependent_settings': {
+-    'include_dirs': [
+-      '<(SHARED_INTERMEDIATE_DIR)/protoc_out',
+-      '<(DEPTH)',
+-    ]
+-  },
+-  'export_dependent_settings': [
+-    # The generated headers reference headers within protobuf_lite,
+-    # so dependencies must be able to find those headers too.
+-    '<(DEPTH)/third_party/protobuf/protobuf.gyp:protobuf_lite',
+-  ],
+-  # This target exports a hard dependency because it generates header
+-  # files.
+-  'hard_dependency': 1,
+-}
+diff --git a/media/webrtc/trunk/build/release.gypi b/media/webrtc/trunk/build/release.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/release.gypi
++++ /dev/null
+@@ -1,17 +0,0 @@
+-{
+-  'conditions': [
+-    # Handle build types.
+-    ['buildtype=="Dev"', {
+-      'includes': ['internal/release_impl.gypi'],
+-    }],
+-    ['buildtype=="Official"', {
+-      'includes': ['internal/release_impl_official.gypi'],
+-    }],
+-    # TODO(bradnelson): may also need:
+-    #     checksenabled
+-    #     coverage
+-    #     dom_stats
+-    #     pgo_instrument
+-    #     pgo_optimize
+-  ],
+-}
+diff --git a/media/webrtc/trunk/build/some.gyp b/media/webrtc/trunk/build/some.gyp
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/some.gyp
++++ /dev/null
+@@ -1,24 +0,0 @@
+-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-{
+-  'targets': [
+-    {
+-      'target_name': 'some',
+-      'type': 'none',
+-      'dependencies': [
+-        # This file is intended to be locally modified. List the targets you use
+-        # regularly. The generated some.sln will contains projects for only
+-        # those targets and the targets they are transitively dependent on. This
+-        # can result in a solution that loads and unloads faster in Visual
+-        # Studio.
+-        #
+-        # Tip: Create a dummy CL to hold your local edits to this file, so they
+-        # don't accidentally get added to another CL that you are editing.
+-        #
+-        # Example:
+-        # '../chrome/chrome.gyp:chrome',
+-      ],
+-    },
+-  ],
+-}
+diff --git a/media/webrtc/trunk/build/temp_gyp/README.chromium b/media/webrtc/trunk/build/temp_gyp/README.chromium
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/temp_gyp/README.chromium
++++ /dev/null
+@@ -1,3 +0,0 @@
+-This directory will be removed once the files in it are committed upstream and
+-Chromium imports an upstream revision with these files.  Contact mark for
+-details.
+diff --git a/media/webrtc/trunk/build/temp_gyp/googleurl.gyp b/media/webrtc/trunk/build/temp_gyp/googleurl.gyp
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/temp_gyp/googleurl.gyp
++++ /dev/null
+@@ -1,105 +0,0 @@
+-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# TODO(mark): Upstream this file to googleurl.
+-{
+-  'variables': {
+-    'chromium_code': 1,
+-  },
+-  'targets': [
+-    {
+-      'target_name': 'googleurl',
+-      'type': '<(component)',
+-      'dependencies': [
+-        '../../base/base.gyp:base',
+-        '../../third_party/icu/icu.gyp:icudata',
+-        '../../third_party/icu/icu.gyp:icui18n',
+-        '../../third_party/icu/icu.gyp:icuuc',
+-      ],
+-      'sources': [
+-        '../../googleurl/src/gurl.cc',
+-        '../../googleurl/src/gurl.h',
+-        '../../googleurl/src/url_canon.h',
+-        '../../googleurl/src/url_canon_etc.cc',
+-        '../../googleurl/src/url_canon_fileurl.cc',
+-        '../../googleurl/src/url_canon_filesystemurl.cc',
+-        '../../googleurl/src/url_canon_host.cc',
+-        '../../googleurl/src/url_canon_icu.cc',
+-        '../../googleurl/src/url_canon_icu.h',
+-        '../../googleurl/src/url_canon_internal.cc',
+-        '../../googleurl/src/url_canon_internal.h',
+-        '../../googleurl/src/url_canon_internal_file.h',
+-        '../../googleurl/src/url_canon_ip.cc',
+-        '../../googleurl/src/url_canon_ip.h',
+-        '../../googleurl/src/url_canon_mailtourl.cc',
+-        '../../googleurl/src/url_canon_path.cc',
+-        '../../googleurl/src/url_canon_pathurl.cc',
+-        '../../googleurl/src/url_canon_query.cc',
+-        '../../googleurl/src/url_canon_relative.cc',
+-        '../../googleurl/src/url_canon_stdstring.h',
+-        '../../googleurl/src/url_canon_stdurl.cc',
+-        '../../googleurl/src/url_file.h',
+-        '../../googleurl/src/url_parse.cc',
+-        '../../googleurl/src/url_parse.h',
+-        '../../googleurl/src/url_parse_file.cc',
+-        '../../googleurl/src/url_parse_internal.h',
+-        '../../googleurl/src/url_util.cc',
+-        '../../googleurl/src/url_util.h',
+-      ],
+-      'direct_dependent_settings': {
+-        'include_dirs': [
+-          '../..',
+-        ],
+-      },
+-      'defines': [
+-        'FULL_FILESYSTEM_URL_SUPPORT=1',
+-      ],
+-      'conditions': [
+-        ['component=="shared_library"', {
+-          'defines': [
+-            'GURL_DLL',
+-            'GURL_IMPLEMENTATION=1',
+-          ],
+-          'direct_dependent_settings': {
+-            'defines': [
+-              'GURL_DLL',
+-            ],
+-          },
+-        }],
+-      ],
+-    },
+-    {
+-      'target_name': 'googleurl_unittests',
+-      'type': 'executable',
+-      'dependencies': [
+-        'googleurl',
+-        '../../base/base.gyp:base_i18n',
+-        '../../base/base.gyp:run_all_unittests',
+-        '../../testing/gtest.gyp:gtest',
+-        '../../third_party/icu/icu.gyp:icuuc',
+-      ],
+-      'sources': [
+-        '../../googleurl/src/gurl_unittest.cc',
+-        '../../googleurl/src/url_canon_unittest.cc',
+-        '../../googleurl/src/url_parse_unittest.cc',
+-        '../../googleurl/src/url_test_utils.h',
+-        '../../googleurl/src/url_util_unittest.cc',
+-      ],
+-      'defines': [
+-        'FULL_FILESYSTEM_URL_SUPPORT=1',
+-      ],
+-      'conditions': [
+-        ['os_posix==1 and OS!="mac" and OS!="ios"', {
+-          'conditions': [
+-            ['linux_use_tcmalloc==1', {
+-              'dependencies': [
+-                '../../base/allocator/allocator.gyp:allocator',
+-              ],
+-            }],
+-          ],
+-        }],
+-      ],
+-    },
+-  ],
+-}
+diff --git a/media/webrtc/trunk/build/temp_gyp/pdfsqueeze.gyp b/media/webrtc/trunk/build/temp_gyp/pdfsqueeze.gyp
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/temp_gyp/pdfsqueeze.gyp
++++ /dev/null
+@@ -1,40 +0,0 @@
+-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-{
+-  'targets': [
+-    {
+-      'target_name': 'pdfsqueeze',
+-      'type': 'executable',
+-      'sources': [
+-        '../../third_party/pdfsqueeze/pdfsqueeze.m',
+-      ],
+-      'defines': [
+-        # Use defines to map the full path names that will be used for
+-        # the vars into the short forms expected by pdfsqueeze.m.
+-        '______third_party_pdfsqueeze_ApplyGenericRGB_qfilter=ApplyGenericRGB_qfilter',
+-        '______third_party_pdfsqueeze_ApplyGenericRGB_qfilter_len=ApplyGenericRGB_qfilter_len',
+-      ],
+-      'include_dirs': [
+-        '<(INTERMEDIATE_DIR)',
+-      ],
+-      'libraries': [
+-        '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
+-        '$(SDKROOT)/System/Library/Frameworks/Quartz.framework',
+-      ],
+-      'actions': [
+-        {
+-          'action_name': 'Generate inline filter data',
+-          'inputs': [
+-            '../../third_party/pdfsqueeze/ApplyGenericRGB.qfilter',
+-          ],
+-          'outputs': [
+-            '<(INTERMEDIATE_DIR)/ApplyGenericRGB.h',
+-          ],
+-          'action': ['xxd', '-i', '<@(_inputs)', '<@(_outputs)'],
+-        },
+-      ],
+-    },
+-  ],
+-}
+diff --git a/media/webrtc/trunk/build/win_precompile.gypi b/media/webrtc/trunk/build/win_precompile.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/build/win_precompile.gypi
++++ /dev/null
+@@ -1,20 +0,0 @@
+-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
+-# Use of this source code is governed by a BSD-style license that can be
+-# found in the LICENSE file.
+-
+-# Include this file to make targets in your .gyp use the default
+-# precompiled header on Windows, in debug builds only as the official
+-# builders blow up (out of memory) if precompiled headers are used for
+-# release builds.
+-
+-{
+-  'conditions': [
+-    ['OS=="win" and chromium_win_pch==1', {
+-        'target_defaults': {
+-          'msvs_precompiled_header': '<(DEPTH)/build/precompile.h',
+-          'msvs_precompiled_source': '<(DEPTH)/build/precompile.cc',
+-          'sources': ['<(DEPTH)/build/precompile.cc'],
+-        }
+-      }],
+-  ],
+-}
+diff --git a/media/webrtc/trunk/net/net.gyp b/media/webrtc/trunk/net/net.gyp
+deleted file mode 100644
+--- a/media/webrtc/trunk/net/net.gyp
++++ /dev/null
+@@ -1,9 +0,0 @@
+-# This is a dummy gyp file to satisfy libjingle.gyp.
+-{
+-  'targets': [
+-    {
+-      'target_name': 'net',
+-      'type': 'none',
+-    },
+-  ],
+-}
+diff --git a/media/webrtc/trunk/peerconnection.gyp b/media/webrtc/trunk/peerconnection.gyp
+deleted file mode 100644
+--- a/media/webrtc/trunk/peerconnection.gyp
++++ /dev/null
+@@ -1,165 +0,0 @@
+-# Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
+-#
+-# Use of this source code is governed by a BSD-style license
+-# that can be found in the LICENSE file in the root of the source
+-# tree. An additional intellectual property rights grant can be found
+-# in the file PATENTS.  All contributing project authors may
+-# be found in the AUTHORS file in the root of the source tree.
+-
+-{
+-  'includes': [
+-    'webrtc/build/common.gypi',
+-    'webrtc/video/webrtc_video.gypi',
+-  ],
+-  'variables': {
+-    'peerconnection_sample': 'third_party/libjingle/source/talk/examples/peerconnection',
+-  },
+-
+-  # for mozilla, we want to force stuff to build but we don't want peerconnection_client or server
+-  # for unknown reasons, 'targets' must be outside of conditions.  And don't try to build a dummy
+-  # executable...
+-  'targets': [
+-  {
+-    'conditions': [
+-      ['build_with_mozilla==1', {
+-        'target_name': 'dummy',
+-        'type': 'none',
+-        'dependencies': [
+-	  'webrtc/webrtc.gyp:webrtc_lib',
+-          'webrtc/modules/modules.gyp:audio_device',
+-          'webrtc/modules/modules.gyp:video_capture_module',
+-          'webrtc/modules/modules.gyp:video_capture_module_internal_impl',
+-# TODO: missing?
+-#          'webrtc/modules/modules.gyp:video_render',
+-#          'webrtc/system_wrappers/source/system_wrappers.gyp:system_wrappers',
+-#      'webrtc/system_wrappers/source/system_wrappers.gyp:metrics_default',
+-#         'webrtc/video_engine/video_engine.gyp:video_engine_core',
+-         'webrtc/voice_engine/voice_engine.gyp:voice_engine',
+-#          '<@(webrtc_video_dependencies)',
+-        ],
+-        'conditions': [
+-          ['OS!="android" and OS!="ios"', {
+-            'dependencies': [
+-               'webrtc/modules/modules.gyp:desktop_capture',
+-            ],
+-          },
+-         ]],
+-      }, ],
+-    ],
+-  }, ],
+-  'conditions': [
+-    ['build_with_mozilla==0', {
+-    'targets': [
+-    {
+-      'target_name': 'peerconnection_server',
+-      'type': 'executable',
+-      'sources': [
+-        '<(peerconnection_sample)/server/data_socket.cc',
+-        '<(peerconnection_sample)/server/data_socket.h',
+-        '<(peerconnection_sample)/server/main.cc',
+-        '<(peerconnection_sample)/server/peer_channel.cc',
+-        '<(peerconnection_sample)/server/peer_channel.h',
+-        '<(peerconnection_sample)/server/utils.cc',
+-        '<(peerconnection_sample)/server/utils.h',
+-      ],
+-      'include_dirs': [
+-        'third_party/libjingle/source',
+-      ],
+-     }, ],
+-  'conditions': [
+-    # TODO(wu): Merge the target for different platforms.
+-    ['OS=="win"', {
+-      'targets': [
+-        {
+-          'target_name': 'peerconnection_client',
+-          'type': 'executable',
+-          'sources': [
+-            '<(peerconnection_sample)/client/conductor.cc',
+-            '<(peerconnection_sample)/client/conductor.h',
+-            '<(peerconnection_sample)/client/defaults.cc',
+-            '<(peerconnection_sample)/client/defaults.h',
+-            '<(peerconnection_sample)/client/main.cc',
+-            '<(peerconnection_sample)/client/main_wnd.cc',
+-            '<(peerconnection_sample)/client/main_wnd.h',
+-            '<(peerconnection_sample)/client/peer_connection_client.cc',
+-            '<(peerconnection_sample)/client/peer_connection_client.h',
+-            'third_party/libjingle/source/talk/base/win32socketinit.cc',
+-            'third_party/libjingle/source/talk/base/win32socketserver.cc',
+-          ],
+-          'msvs_settings': {
+-            'VCLinkerTool': {
+-             'SubSystem': '2',  # Windows
+-            },
+-          },
+-          'dependencies': [
+-            #'third_party/jsoncpp/jsoncpp.gyp:jsoncpp',
+-            #'third_party/libjingle/libjingle.gyp:libjingle_peerconnection',
+-          ],
+-          'include_dirs': [
+-            'src',
+-            'webrtc/modules/interface',
+-            'third_party/libjingle/source',
+-          ],
+-        },
+-      ],  # targets
+-    }, ],  # OS="win"
+-    ['OS=="linux"', {
+-      'targets': [
+-        {
+-          'target_name': 'peerconnection_client',
+-          'type': 'executable',
+-          'sources': [
+-            '<(peerconnection_sample)/client/conductor.cc',
+-            '<(peerconnection_sample)/client/conductor.h',
+-            '<(peerconnection_sample)/client/defaults.cc',
+-            '<(peerconnection_sample)/client/defaults.h',
+-            '<(peerconnection_sample)/client/linux/main.cc',
+-            '<(peerconnection_sample)/client/linux/main_wnd.cc',
+-            '<(peerconnection_sample)/client/linux/main_wnd.h',
+-            '<(peerconnection_sample)/client/peer_connection_client.cc',
+-            '<(peerconnection_sample)/client/peer_connection_client.h',
+-          ],
+-          'dependencies': [
+-            #'third_party/jsoncpp/jsoncpp.gyp:jsoncpp',
+-            #'third_party/libjingle/libjingle.gyp:libjingle_peerconnection',
+-            # TODO(tommi): Switch to this and remove specific gtk dependency
+-            # sections below for cflags and link_settings.
+-            # '<(DEPTH)/build/linux/system.gyp:gtk',
+-          ],
+-          'include_dirs': [
+-            'third_party/libjingle/source',
+-          ],
+-          'cflags': [
+-            '<!@(pkg-config --cflags gtk+-2.0)',
+-          ],
+-          'link_settings': {
+-            'ldflags': [
+-              '<!@(pkg-config --libs-only-L --libs-only-other gtk+-2.0 gthread-2.0)',
+-            ],
+-            'libraries': [
+-              '<!@(pkg-config --libs-only-l gtk+-2.0 gthread-2.0)',
+-              '-lX11',
+-              '-lXcomposite',
+-              '-lXext',
+-              '-lXrender',
+-            ],
+-          },
+-        },
+-      ],  # targets
+-    }, ],  # OS="linux"
+-    # There's no peerconnection_client implementation for Mac.
+-    # But add this dummy peerconnection_client target so that the runhooks
+-    # won't complain.
+-    ['OS=="mac"', {
+-      'targets': [
+-        {
+-          'target_name': 'peerconnection_client',
+-          'type': 'none',
+-        },
+-      ],
+-    }, ],
+-  ],
+-    }, ],
+-  ],
+-
+-}
+diff --git a/media/webrtc/trunk/supplement/supplement.gypi b/media/webrtc/trunk/supplement/supplement.gypi
+deleted file mode 100644
+--- a/media/webrtc/trunk/supplement/supplement.gypi
++++ /dev/null
+@@ -1,30 +0,0 @@
+-# This file will be picked up by gyp to initialize some global settings.
+-{
+-  'variables': {
+-# make sure we can override this with --include
+-    'build_with_chromium%': 1,
+-    'clang_use_chrome_plugins%': 0,
+-    'enable_protobuf%': 1,
+-    'enabled_libjingle_device_manager%': 1,
+-    'include_internal_audio_device%': 1,
+-    'include_internal_video_capture%': 1,
+-    'include_internal_video_render%': 1,
+-    'include_pulse_audio%': 1,
+-    'use_openssl%': 1,
+-  },
+-  'target_defaults': {
+-    'conditions': [
+-      ['OS=="linux" and clang==1', {
+-        'cflags': [
+-          # Suppress the warning caused by
+-          # LateBindingSymbolTable::TableInfo from
+-          # latebindingsymboltable.cc.def.
+-          '-Wno-address-of-array-temporary',
+-        ],
+-        'cflags_mozilla': [
+-          '-Wno-address-of-array-temporary',
+-        ],
+-      }],
+-    ],
+-  }, # target_defaults
+-}
+diff --git a/media/webrtc/trunk/third_party/opus/opus.gyp b/media/webrtc/trunk/third_party/opus/opus.gyp
+deleted file mode 100644
+--- a/media/webrtc/trunk/third_party/opus/opus.gyp
++++ /dev/null
+@@ -1,178 +0,0 @@
+-# Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
+-#
+-# Use of this source code is governed by a BSD-style license
+-# that can be found in the LICENSE file in the root of the source
+-# tree. An additional intellectual property rights grant can be found
+-# in the file PATENTS.  All contributing project authors may
+-# be found in the AUTHORS file in the root of the source tree.
+-
+-{
+-  'targets': [
+-    {
+-      'target_name': 'opus',
+-      'type': '<(library)',
+-      'defines': [
+-        'OPUS_BUILD',
+-        'FLOATING_POINT',
+-        'VAR_ARRAYS',
+-      ],
+-      'conditions': [
+-        ['OS=="linux"', {
+-          'cflags': [
+-            '-std=c99',
+-          ],
+-          'cflags_mozilla': [
+-            '-std=c99',
+-          ],
+-          'defines': [
+-            'HAVE_LRINTF',
+-          ],
+-        }]
+-      ],
+-
+-      'include_dirs': [
+-        'source/include',
+-        'source/src',
+-        'source/celt',
+-        'source/silk',
+-        'source/silk/float',
+-      ],
+-      'sources': [
+-        # opus wrapper/glue
+-        'source/src/opus.c',
+-        'source/src/opus_decoder.c',
+-        'source/src/opus_encoder.c',
+-        'source/src/repacketizer.c',
+-
+-        # celt sub-codec
+-        'source/celt/bands.c',
+-        'source/celt/celt.c',
+-        'source/celt/cwrs.c',
+-        'source/celt/entcode.c',
+-        'source/celt/entdec.c',
+-        'source/celt/entenc.c',
+-        'source/celt/kiss_fft.c',
+-        'source/celt/laplace.c',
+-        'source/celt/mathops.c',
+-        'source/celt/mdct.c',
+-        'source/celt/modes.c',
+-        'source/celt/pitch.c',
+-        'source/celt/celt_lpc.c',
+-        'source/celt/quant_bands.c',
+-        'source/celt/rate.c',
+-        'source/celt/vq.c',
+-
+-        # silk sub-codec
+-        'source/silk/CNG.c',
+-        'source/silk/code_signs.c',
+-        'source/silk/init_decoder.c',
+-        'source/silk/decode_core.c',
+-        'source/silk/decode_frame.c',
+-        'source/silk/decode_parameters.c',
+-        'source/silk/decode_indices.c',
+-        'source/silk/decode_pulses.c',
+-        'source/silk/decoder_set_fs.c',
+-        'source/silk/dec_API.c',
+-        'source/silk/enc_API.c',
+-        'source/silk/encode_indices.c',
+-        'source/silk/encode_pulses.c',
+-        'source/silk/gain_quant.c',
+-        'source/silk/interpolate.c',
+-        'source/silk/LP_variable_cutoff.c',
+-        'source/silk/NLSF_decode.c',
+-        'source/silk/NSQ.c',
+-        'source/silk/NSQ_del_dec.c',
+-        'source/silk/PLC.c',
+-        'source/silk/shell_coder.c',
+-        'source/silk/tables_gain.c',
+-        'source/silk/tables_LTP.c',
+-        'source/silk/tables_NLSF_CB_NB_MB.c',
+-        'source/silk/tables_NLSF_CB_WB.c',
+-        'source/silk/tables_other.c',
+-        'source/silk/tables_pitch_lag.c',
+-        'source/silk/tables_pulses_per_block.c',
+-        'source/silk/VAD.c',
+-        'source/silk/control_audio_bandwidth.c',
+-        'source/silk/quant_LTP_gains.c',
+-        'source/silk/VQ_WMat_EC.c',
+-        'source/silk/HP_variable_cutoff.c',
+-        'source/silk/NLSF_encode.c',
+-        'source/silk/NLSF_VQ.c',
+-        'source/silk/NLSF_unpack.c',
+-        'source/silk/NLSF_del_dec_quant.c',
+-        'source/silk/process_NLSFs.c',
+-        'source/silk/stereo_LR_to_MS.c',
+-        'source/silk/stereo_MS_to_LR.c',
+-        'source/silk/check_control_input.c',
+-        'source/silk/control_SNR.c',
+-        'source/silk/init_encoder.c',
+-        'source/silk/control_codec.c',
+-        'source/silk/A2NLSF.c',
+-        'source/silk/ana_filt_bank_1.c',
+-        'source/silk/biquad_alt.c',
+-        'source/silk/bwexpander_32.c',
+-        'source/silk/bwexpander.c',
+-        'source/silk/debug.c',
+-        'source/silk/decode_pitch.c',
+-        'source/silk/inner_prod_aligned.c',
+-        'source/silk/lin2log.c',
+-        'source/silk/log2lin.c',
+-        'source/silk/LPC_analysis_filter.c',
+-        'source/silk/LPC_inv_pred_gain.c',
+-        'source/silk/table_LSF_cos.c',
+-        'source/silk/NLSF2A.c',
+-        'source/silk/NLSF_stabilize.c',
+-        'source/silk/NLSF_VQ_weights_laroia.c',
+-        'source/silk/pitch_est_tables.c',
+-        'source/silk/resampler.c',
+-        'source/silk/resampler_down2_3.c',
+-        'source/silk/resampler_down2.c',
+-        'source/silk/resampler_private_AR2.c',
+-        'source/silk/resampler_private_down_FIR.c',
+-        'source/silk/resampler_private_IIR_FIR.c',
+-        'source/silk/resampler_private_up2_HQ.c',
+-        'source/silk/resampler_rom.c',
+-        'source/silk/sigm_Q15.c',
+-        'source/silk/sort.c',
+-        'source/silk/sum_sqr_shift.c',
+-        'source/silk/stereo_decode_pred.c',
+-        'source/silk/stereo_encode_pred.c',
+-        'source/silk/stereo_find_predictor.c',
+-        'source/silk/stereo_quant_pred.c',
+-
+-        # silk floating point engine
+-        'source/silk/float/apply_sine_window_FLP.c',
+-        'source/silk/float/corrMatrix_FLP.c',
+-        'source/silk/float/encode_frame_FLP.c',
+-        'source/silk/float/find_LPC_FLP.c',
+-        'source/silk/float/find_LTP_FLP.c',
+-        'source/silk/float/find_pitch_lags_FLP.c',
+-        'source/silk/float/find_pred_coefs_FLP.c',
+-        'source/silk/float/LPC_analysis_filter_FLP.c',
+-        'source/silk/float/LTP_analysis_filter_FLP.c',
+-        'source/silk/float/LTP_scale_ctrl_FLP.c',
+-        'source/silk/float/noise_shape_analysis_FLP.c',
+-        'source/silk/float/prefilter_FLP.c',
+-        'source/silk/float/process_gains_FLP.c',
+-        'source/silk/float/regularize_correlations_FLP.c',
+-        'source/silk/float/residual_energy_FLP.c',
+-        'source/silk/float/solve_LS_FLP.c',
+-        'source/silk/float/warped_autocorrelation_FLP.c',
+-        'source/silk/float/wrappers_FLP.c',
+-        'source/silk/float/autocorrelation_FLP.c',
+-        'source/silk/float/burg_modified_FLP.c',
+-        'source/silk/float/bwexpander_FLP.c',
+-        'source/silk/float/energy_FLP.c',
+-        'source/silk/float/inner_product_FLP.c',
+-        'source/silk/float/k2a_FLP.c',
+-        'source/silk/float/levinsondurbin_FLP.c',
+-        'source/silk/float/LPC_inv_pred_gain_FLP.c',
+-        'source/silk/float/pitch_analysis_core_FLP.c',
+-        'source/silk/float/scale_copy_vector_FLP.c',
+-        'source/silk/float/scale_vector_FLP.c',
+-        'source/silk/float/schur_FLP.c',
+-        'source/silk/float/sort_FLP.c',
+-      ]
+-    }
+-  ]
+-}

File diff suppressed because it is too large
+ 91582 - 0
rel-257/ian/patches/1371485-3-63a1.patch


+ 4003 - 0
rel-257/ian/patches/1371485-4-63a1.patch

@@ -0,0 +1,4003 @@
+# HG changeset patch
+# User Dan Minor <dminor@mozilla.com>
+# Date 1529606374 14400
+# Node ID b94ed33798026f9e8a0c200f3ff80faae257b93e
+# Parent  b39399f12e04f744b4567c93f29d840b9e2438d1
+Bug 1371485 - Use updated version of gyp; r=chmanchester
+
+Tags: #secure-revision
+
+Bug #: 1371485
+
+Differential Revision: https://phabricator.services.mozilla.com/D1801
+
+diff --git a/build/gyp_includes/common.gypi b/build/gyp_includes/common.gypi
+new file mode 100644
+--- /dev/null
++++ b/build/gyp_includes/common.gypi
+@@ -0,0 +1,3668 @@
++# Copyright (c) 2012 The Chromium Authors. All rights reserved.
++# Use of this source code is governed by a BSD-style license that can be
++# found in the LICENSE file.
++
++# IMPORTANT:
++# Please don't directly include this file if you are building via gyp_chromium,
++# since gyp_chromium is automatically forcing its inclusion.
++{
++  # Variables expected to be overriden on the GYP command line (-D) or by
++  # ~/.gyp/include.gypi.
++  'variables': {
++    # Putting a variables dict inside another variables dict looks kind of
++    # weird.  This is done so that 'host_arch', 'chromeos', etc are defined as
++    # variables within the outer variables dict here.  This is necessary
++    # to get these variables defined for the conditions within this variables
++    # dict that operate on these variables.
++    'variables': {
++      'variables': {
++        'variables': {
++          'variables': {
++            # Whether we're building a ChromeOS build.
++            'chromeos%': 0,
++
++            # Whether or not we are using the Aura windowing framework.
++            'use_aura%': 0,
++
++            # Whether or not we are building the Ash shell.
++            'use_ash%': 0,
++          },
++          # Copy conditionally-set variables out one scope.
++          'chromeos%': '<(chromeos)',
++          'use_aura%': '<(use_aura)',
++          'use_ash%': '<(use_ash)',
++
++          # Whether we are using Views Toolkit
++          'toolkit_views%': 0,
++
++          # Use OpenSSL instead of NSS. Under development: see http://crbug.com/62803
++          'use_openssl%': 0,
++
++          'use_ibus%': 0,
++
++          # Disable viewport meta tag by default.
++          'enable_viewport%': 0,
++
++          # Enable HiDPI support.
++          'enable_hidpi%': 0,
++
++          # Enable touch optimized art assets and metrics.
++          'enable_touch_ui%': 0,
++
++          # Is this change part of the android upstream bringup?
++          # Allows us to *temporarily* disable certain things for
++          # staging.  Only set to 1 in a GYP_DEFINES.
++          'android_upstream_bringup%': 0,
++
++          # Override buildtype to select the desired build flavor.
++          # Dev - everyday build for development/testing
++          # Official - release build (generally implies additional processing)
++          # TODO(mmoss) Once 'buildtype' is fully supported (e.g. Windows gyp
++          # conversion is done), some of the things which are now controlled by
++          # 'branding', such as symbol generation, will need to be refactored
++          # based on 'buildtype' (i.e. we don't care about saving symbols for
++          # non-Official # builds).
++          'buildtype%': 'Dev',
++
++          'conditions': [
++            # ChromeOS implies ash.
++            ['chromeos==1', {
++              'use_ash%': 1,
++              'use_aura%': 1,
++            }],
++
++            # For now, Windows builds that |use_aura| should also imply using
++            # ash. This rule should be removed for the future when Windows is
++            # using the aura windows without the ash interface.
++            ['use_aura==1 and OS=="win"', {
++              'use_ash%': 1,
++            }],
++            ['use_ash==1', {
++              'use_aura%': 1,
++            }],
++
++            # A flag for BSD platforms
++            ['OS=="dragonfly" or OS=="freebsd" or OS=="netbsd" or \
++              OS=="openbsd"', {
++              'os_bsd%': 1,
++            }, {
++              'os_bsd%': 0,
++            }],
++          ],
++        },
++        # Copy conditionally-set variables out one scope.
++        'chromeos%': '<(chromeos)',
++        'use_aura%': '<(use_aura)',
++        'use_ash%': '<(use_ash)',
++        'os_bsd%': '<(os_bsd)',
++        'use_openssl%': '<(use_openssl)',
++        'use_ibus%': '<(use_ibus)',
++        'enable_viewport%': '<(enable_viewport)',
++        'enable_hidpi%': '<(enable_hidpi)',
++        'enable_touch_ui%': '<(enable_touch_ui)',
++        'android_upstream_bringup%': '<(android_upstream_bringup)',
++        'buildtype%': '<(buildtype)',
++
++        # Sets whether we're building with the Android SDK/NDK (and hence with
++        # Ant, value 0), or as part of the Android system (and hence with the
++        # Android build system, value 1).
++        'android_build_type%': 0,
++
++        # Compute the architecture that we're building on.
++        'conditions': [
++          ['OS=="win" or OS=="ios"', {
++            'host_arch%': 'ia32',
++          }, {
++            # This handles the Unix platforms for which there is some support.
++            # Anything else gets passed through, which probably won't work very
++            # well; such hosts should pass an explicit target_arch to gyp.
++            'host_arch%':
++              '<!(uname -m | sed -e "s/i.86/ia32/;s/x86_64/x64/;s/amd64/x64/;s/arm.*/arm/;s/i86pc/ia32/")',
++          }],
++
++          # Set default value of toolkit_views based on OS.
++          ['OS=="win" or chromeos==1 or use_aura==1', {
++            'toolkit_views%': 1,
++          }, {
++            'toolkit_views%': 0,
++          }],
++
++          # Set toolkit_uses_gtk for the Chromium browser on Linux.
++          ['(OS=="linux" or OS=="solaris" or os_bsd==1) and use_aura==0', {
++            'toolkit_uses_gtk%': 1,
++          }, {
++            'toolkit_uses_gtk%': 0,
++          }],
++
++          # Enable HiDPI on Mac OS and Chrome OS.
++          ['OS=="mac" or chromeos==1', {
++            'enable_hidpi%': 1,
++          }],
++
++          # Enable touch UI on Metro.
++          ['OS=="win"', {
++            'enable_touch_ui%': 1,
++          }],
++        ],
++      },
++
++      # Copy conditionally-set variables out one scope.
++      'chromeos%': '<(chromeos)',
++      'host_arch%': '<(host_arch)',
++      'toolkit_views%': '<(toolkit_views)',
++      'toolkit_uses_gtk%': '<(toolkit_uses_gtk)',
++      'use_aura%': '<(use_aura)',
++      'use_ash%': '<(use_ash)',
++      'os_bsd%': '<(os_bsd)',
++      'use_openssl%': '<(use_openssl)',
++      'use_ibus%': '<(use_ibus)',
++      'enable_viewport%': '<(enable_viewport)',
++      'enable_hidpi%': '<(enable_hidpi)',
++      'enable_touch_ui%': '<(enable_touch_ui)',
++      'android_upstream_bringup%': '<(android_upstream_bringup)',
++      'android_build_type%': '<(android_build_type)',
++
++      # We used to provide a variable for changing how libraries were built.
++      # This variable remains until we can clean up all the users.
++      # This needs to be one nested variables dict in so that dependent
++      # gyp files can make use of it in their outer variables.  (Yikes!)
++      # http://code.google.com/p/chromium/issues/detail?id=83308
++      'library%': 'static_library',
++
++      # Override branding to select the desired branding flavor.
++      'branding%': 'Chromium',
++
++      'buildtype%': '<(buildtype)',
++
++      # Default architecture we're building for is the architecture we're
++      # building on.
++      'target_arch%': '<(host_arch)',
++
++      # This variable tells WebCore.gyp and JavaScriptCore.gyp whether they are
++      # are built under a chromium full build (1) or a webkit.org chromium
++      # build (0).
++      'inside_chromium_build%': 1,
++
++      # Set to 1 to enable fast builds. It disables debug info for fastest
++      # compilation.
++      'fastbuild%': 0,
++
++      # Set to 1 to enable dcheck in release without having to use the flag.
++      'dcheck_always_on%': 0,
++
++      # Disable file manager component extension by default.
++      'file_manager_extension%': 0,
++
++      # Python version.
++      'python_ver%': '2.6',
++
++      # Set ARM version (for libyuv)
++      'arm_version%': 6,
++
++      # Set ARM-v7 compilation flags
++      'armv7%': 0,
++
++      # Set Neon compilation flags (only meaningful if armv7==1).
++      'arm_neon%': 1,
++      'arm_neon_optional%': 0,
++
++      # The system root for cross-compiles. Default: none.
++      'sysroot%': '',
++
++      # The system libdir used for this ABI.
++      'system_libdir%': 'lib',
++
++      # On Linux, we build with sse2 for Chromium builds.
++      'disable_sse2%': 0,
++
++      # Use libjpeg-turbo as the JPEG codec used by Chromium.
++      'use_libjpeg_turbo%': 1,
++
++      # Use system libjpeg. Note that the system's libjepg will be used even if
++      # use_libjpeg_turbo is set.
++      'use_system_libjpeg%': 0,
++
++      # Use system libvpx
++      'use_system_libvpx%': 0,
++
++      # Variable 'component' is for cases where we would like to build some
++      # components as dynamic shared libraries but still need variable
++      # 'library' for static libraries.
++      # By default, component is set to whatever library is set to and
++      # it can be overriden by the GYP command line or by ~/.gyp/include.gypi.
++      'component%': 'static_library',
++
++      # Set to select the Title Case versions of strings in GRD files.
++      'use_titlecase_in_grd_files%': 0,
++
++      # Use translations provided by volunteers at launchpad.net.  This
++      # currently only works on Linux.
++      'use_third_party_translations%': 0,
++
++      # Remoting compilation is enabled by default. Set to 0 to disable.
++      'remoting%': 1,
++
++      # Configuration policy is enabled by default. Set to 0 to disable.
++      'configuration_policy%': 1,
++
++      # Safe browsing is compiled in by default. Set to 0 to disable.
++      'safe_browsing%': 1,
++
++      # Speech input is compiled in by default. Set to 0 to disable.
++      'input_speech%': 1,
++
++      # Notifications are compiled in by default. Set to 0 to disable.
++      'notifications%' : 1,
++
++      # If this is set, the clang plugins used on the buildbot will be used.
++      # Run tools/clang/scripts/update.sh to make sure they are compiled.
++      # This causes 'clang_chrome_plugins_flags' to be set.
++      # Has no effect if 'clang' is not set as well.
++      'clang_use_chrome_plugins%': 1,
++
++      # Enable building with ASAN (Clang's -faddress-sanitizer option).
++      # -faddress-sanitizer only works with clang, but asan=1 implies clang=1
++      # See https://sites.google.com/a/chromium.org/dev/developers/testing/addresssanitizer
++      'asan%': 0,
++
++      # Enable building with TSAN (Clang's -fthread-sanitizer option).
++      # -fthread-sanitizer only works with clang, but tsan=1 implies clang=1
++      # See http://clang.llvm.org/docs/ThreadSanitizer.html
++      'tsan%': 0,
++
++      # Use a modified version of Clang to intercept allocated types and sizes
++      # for allocated objects. clang_type_profiler=1 implies clang=1.
++      # See http://dev.chromium.org/developers/deep-memory-profiler/cpp-object-type-identifier
++      # TODO(dmikurube): Support mac.  See http://crbug.com/123758#c11
++      'clang_type_profiler%': 0,
++
++      # Set to true to instrument the code with function call logger.
++      # See src/third_party/cygprofile/cyg-profile.cc for details.
++      'order_profiling%': 0,
++
++      # Use the provided profiled order file to link Chrome image with it.
++      # This makes Chrome faster by better using CPU cache when executing code.
++      # This is known as PGO (profile guided optimization).
++      # See https://sites.google.com/a/google.com/chrome-msk/dev/boot-speed-up-effort
++      'order_text_section%' : "",
++
++      # Set to 1 compile with -fPIC cflag on linux. This is a must for shared
++      # libraries on linux x86-64 and arm, plus ASLR.
++      'linux_fpic%': 1,
++
++      # Whether one-click signin is enabled or not.
++      'enable_one_click_signin%': 0,
++
++      # Enable Web Intents support in WebKit.
++      'enable_web_intents%': 1,
++
++      # Enable Chrome browser extensions
++      'enable_extensions%': 1,
++
++      # Enable browser automation.
++      'enable_automation%': 1,
++
++      # Enable printing support and UI.
++      'enable_printing%': 1,
++
++      # Enable Web Intents web content registration via HTML element
++      # and WebUI managing such registrations.
++      'enable_web_intents_tag%': 0,
++
++      # Webrtc compilation is enabled by default. Set to 0 to disable.
++      'enable_webrtc%': 1,
++
++      # PPAPI by default does not support plugins making calls off the main
++      # thread. Set to 1 to turn on experimental support for out-of-process
++      # plugins to make call of the main thread.
++      'enable_pepper_threading%': 0,
++
++      # Enables use of the session service, which is enabled by default.
++      # Support for disabling depends on the platform.
++      'enable_session_service%': 1,
++
++      # Enables theme support, which is enabled by default.  Support for
++      # disabling depends on the platform.
++      'enable_themes%': 1,
++
++      # Uses OEM-specific wallpaper resources on Chrome OS.
++      'use_oem_wallpaper%': 0,
++
++      # Enables support for background apps.
++      'enable_background%': 1,
++
++      # Enable the task manager by default.
++      'enable_task_manager%': 1,
++
++      # Enable FTP support by default.
++      'disable_ftp_support%': 0,
++
++      # XInput2 multitouch support is disabled by default (use_xi2_mt=0).
++      # Setting to non-zero value enables XI2 MT. When XI2 MT is enabled,
++      # the input value also defines the required XI2 minor minimum version.
++      # For example, use_xi2_mt=2 means XI2.2 or above version is required.
++      'use_xi2_mt%': 0,
++
++      # Use of precompiled headers on Windows.
++      #
++      # This is on by default in VS 2010, but off by default for VS
++      # 2008 because of complications that it can cause with our
++      # trybots etc.
++      #
++      # This variable may be explicitly set to 1 (enabled) or 0
++      # (disabled) in ~/.gyp/include.gypi or via the GYP command line.
++      # This setting will override the default.
++      #
++      # Note that a setting of 1 is probably suitable for most or all
++      # Windows developers using VS 2008, since precompiled headers
++      # provide a build speedup of 20-25%.  There are a couple of
++      # small workarounds you may need to use when using VS 2008 (but
++      # not 2010), see
++      # http://code.google.com/p/chromium/wiki/WindowsPrecompiledHeaders
++      # for details.
++      'chromium_win_pch%': 0,
++
++      # Set this to true when building with Clang.
++      # See http://code.google.com/p/chromium/wiki/Clang for details.
++      'clang%': 0,
++
++      # Enable plug-in installation by default.
++      'enable_plugin_installation%': 1,
++
++      # Enable protector service by default.
++      'enable_protector_service%': 1,
++
++      # Specifies whether to use canvas_skia.cc in place of platform
++      # specific implementations of gfx::Canvas. Affects text drawing in the
++      # Chrome UI.
++      # TODO(asvitkine): Enable this on all platforms and delete this flag.
++      #                  http://crbug.com/105550
++      'use_canvas_skia%': 0,
++
++      # Set to "tsan", "memcheck", or "drmemory" to configure the build to work
++      # with one of those tools.
++      'build_for_tool%': '',
++
++      # Whether tests targets should be run, archived or just have the
++      # dependencies verified. All the tests targets have the '_run' suffix,
++      # e.g. base_unittests_run runs the target base_unittests. The test target
++      # always calls tools/swarm_client/isolate.py. See the script's --help for
++      # more information and the valid --mode values. Meant to be overriden with
++      # GYP_DEFINES.
++      # TODO(maruel): Converted the default from 'check' to 'noop' so work can
++      # be done while the builders are being reconfigured to check out test data
++      # files.
++      'test_isolation_mode%': 'noop',
++      # It must not be '<(PRODUCT_DIR)' alone, the '/' is necessary otherwise
++      # gyp will remove duplicate flags, causing isolate.py to be confused.
++      'test_isolation_outdir%': '<(PRODUCT_DIR)/isolate',
++
++       # Force rlz to use chrome's networking stack.
++      'force_rlz_use_chrome_net%': 1,
++
++      'sas_dll_path%': '<(DEPTH)/third_party/platformsdk_win7/files/redist/x86',
++      'wix_path%': '<(DEPTH)/third_party/wix',
++
++      'conditions': [
++        # TODO(epoger): Figure out how to set use_skia=1 for Mac outside of
++        # the 'conditions' clause.  Initial attempts resulted in chromium and
++        # webkit disagreeing on its setting.
++        ['OS=="mac"', {
++          'use_skia%': 1,
++        }, {
++          'use_skia%': 1,
++        }],
++
++        # A flag for POSIX platforms
++        ['OS=="win"', {
++          'os_posix%': 0,
++        }, {
++          'os_posix%': 1,
++        }],
++
++        # NSS usage.
++        ['(OS=="linux" or OS=="solaris" or os_bsd==1) and use_openssl==0', {
++          'use_nss%': 1,
++        }, {
++          'use_nss%': 0,
++        }],
++
++        # Flags to use X11 on non-Mac POSIX platforms
++        ['OS=="win" or OS=="mac" or OS=="ios" or OS=="android"', {
++          'use_glib%': 0,
++          'use_x11%': 0,
++        }, {
++          'use_glib%': 1,
++          'use_x11%': 1,
++        }],
++
++        # We always use skia text rendering in Aura on Windows, since GDI
++        # doesn't agree with our BackingStore.
++        # TODO(beng): remove once skia text rendering is on by default.
++        ['use_aura==1 and OS=="win"', {
++          'enable_skia_text%': 1,
++        }],
++
++        # A flag to enable or disable our compile-time dependency
++        # on gnome-keyring. If that dependency is disabled, no gnome-keyring
++        # support will be available. This option is useful
++        # for Linux distributions and for Aura.
++        ['chromeos==1 or use_aura==1', {
++          'use_gnome_keyring%': 0,
++        }, {
++          'use_gnome_keyring%': 1,
++        }],
++
++        ['toolkit_uses_gtk==1 or OS=="mac" or OS=="ios"', {
++          # GTK+, Mac and iOS want Title Case strings
++          'use_titlecase_in_grd_files%': 1,
++        }],
++
++        # Enable file manager extension on Chrome OS.
++        ['chromeos==1', {
++          'file_manager_extension%': 1,
++        }, {
++          'file_manager_extension%': 0,
++        }],
++
++        ['OS=="win" or OS=="mac" or (OS=="linux" and use_aura==0)', {
++          'enable_one_click_signin%': 1,
++        }],
++
++        ['OS=="android"', {
++          'enable_extensions%': 0,
++          'enable_printing%': 0,
++          'enable_themes%': 0,
++          'enable_webrtc%': 0,
++          'proprietary_codecs%': 1,
++          'remoting%': 0,
++        }],
++
++        ['OS=="ios"', {
++          'configuration_policy%': 0,
++          'disable_ftp_support%': 1,
++          'enable_automation%': 0,
++          'enable_extensions%': 0,
++          'enable_printing%': 0,
++          'enable_themes%': 0,
++          'enable_webrtc%': 0,
++          'notifications%': 0,
++          'remoting%': 0,
++        }],
++
++        # Use GPU accelerated cross process image transport by default
++        # on linux builds with the Aura window manager
++        ['use_aura==1 and OS=="linux"', {
++          'ui_compositor_image_transport%': 1,
++        }, {
++          'ui_compositor_image_transport%': 0,
++        }],
++
++        # Turn precompiled headers on by default for VS 2010.
++        ['OS=="win" and MSVS_VERSION=="2010" and buildtype!="Official"', {
++          'chromium_win_pch%': 1
++        }],
++
++        ['use_aura==1 or chromeos==1 or OS=="android"', {
++          'enable_plugin_installation%': 0,
++        }, {
++          'enable_plugin_installation%': 1,
++        }],
++
++        ['OS=="android" or OS=="ios"', {
++          'enable_protector_service%': 0,
++        }, {
++          'enable_protector_service%': 1,
++        }],
++
++        # linux_use_gold_binary: whether to use the binary checked into
++        # third_party/gold.
++        ['OS=="linux"', {
++          'linux_use_gold_binary%': 1,
++        }, {
++          'linux_use_gold_binary%': 0,
++        }],
++
++        # linux_use_gold_flags: whether to use build flags that rely on gold.
++        # On by default for x64 Linux.  Temporarily off for ChromeOS as
++        # it failed on a buildbot.
++        ['OS=="linux" and chromeos==0', {
++          'linux_use_gold_flags%': 1,
++        }, {
++          'linux_use_gold_flags%': 0,
++        }],
++
++        ['OS=="android"', {
++          'enable_captive_portal_detection%': 0,
++        }, {
++          'enable_captive_portal_detection%': 1,
++        }],
++
++        # Enable Skia UI text drawing incrementally on different platforms.
++        # http://crbug.com/105550
++        #
++        # On Aura, this allows per-tile painting to be used in the browser
++        # compositor.
++        ['OS!="mac" and OS!="android"', {
++          'use_canvas_skia%': 1,
++        }],
++
++        ['chromeos==1', {
++          # When building for ChromeOS we dont want Chromium to use libjpeg_turbo.
++          'use_libjpeg_turbo%': 0,
++        }],
++
++        ['OS=="android"', {
++          # When building as part of the Android system, use system libraries
++          # where possible to reduce ROM size.
++          'use_system_libjpeg%': '<(android_build_type)',
++        }],
++      ],
++
++      # Set this to 1 to use the Google-internal file containing
++      # official API keys for Google Chrome even in a developer build.
++      # Setting this variable explicitly to 1 will cause your build to
++      # fail if the internal file is missing.
++      #
++      # Set this to 0 to not use the internal file, even when it
++      # exists in your checkout.
++      #
++      # Leave set to 2 to have this variable implicitly set to 1 if
++      # you have src/google_apis/internal/google_chrome_api_keys.h in
++      # your checkout, and implicitly set to 0 if not.
++      #
++      # Note that official builds always behave as if this variable
++      # was explicitly set to 1, i.e. they always use official keys,
++      # and will fail to build if the internal file is missing.
++      'use_official_google_api_keys%': 2,
++
++      # Set these to bake the specified API keys and OAuth client
++      # IDs/secrets into your build.
++      #
++      # If you create a build without values baked in, you can instead
++      # set environment variables to provide the keys at runtime (see
++      # src/google_apis/google_api_keys.h for details).  Features that
++      # require server-side APIs may fail to work if no keys are
++      # provided.
++      #
++      # Note that if you are building an official build or if
++      # use_official_google_api_keys has been set to 1 (explicitly or
++      # implicitly), these values will be ignored and the official
++      # keys will be used instead.
++      'google_api_key%': '',
++      'google_default_client_id%': '',
++      'google_default_client_secret%': '',
++    },
++
++    # Copy conditionally-set variables out one scope.
++    'branding%': '<(branding)',
++    'buildtype%': '<(buildtype)',
++    'target_arch%': '<(target_arch)',
++    'host_arch%': '<(host_arch)',
++    'library%': 'static_library',
++    'toolkit_views%': '<(toolkit_views)',
++    'ui_compositor_image_transport%': '<(ui_compositor_image_transport)',
++    'use_aura%': '<(use_aura)',
++    'use_ash%': '<(use_ash)',
++    'use_openssl%': '<(use_openssl)',
++    'use_ibus%': '<(use_ibus)',
++    'use_nss%': '<(use_nss)',
++    'os_bsd%': '<(os_bsd)',
++    'os_posix%': '<(os_posix)',
++    'use_glib%': '<(use_glib)',
++    'toolkit_uses_gtk%': '<(toolkit_uses_gtk)',
++    'use_skia%': '<(use_skia)',
++    'use_x11%': '<(use_x11)',
++    'use_gnome_keyring%': '<(use_gnome_keyring)',
++    'linux_fpic%': '<(linux_fpic)',
++    'enable_pepper_threading%': '<(enable_pepper_threading)',
++    'chromeos%': '<(chromeos)',
++    'enable_viewport%': '<(enable_viewport)',
++    'enable_hidpi%': '<(enable_hidpi)',
++    'enable_touch_ui%': '<(enable_touch_ui)',
++    'use_xi2_mt%':'<(use_xi2_mt)',
++    'file_manager_extension%': '<(file_manager_extension)',
++    'inside_chromium_build%': '<(inside_chromium_build)',
++    'fastbuild%': '<(fastbuild)',
++    'dcheck_always_on%': '<(dcheck_always_on)',
++    'python_ver%': '<(python_ver)',
++    'arm_version%': '<(arm_version)',
++    'armv7%': '<(armv7)',
++    'arm_neon%': '<(arm_neon)',
++    'arm_neon_optional%': '<(arm_neon_optional)',
++    'sysroot%': '<(sysroot)',
++    'system_libdir%': '<(system_libdir)',
++    'component%': '<(component)',
++    'use_titlecase_in_grd_files%': '<(use_titlecase_in_grd_files)',
++    'use_third_party_translations%': '<(use_third_party_translations)',
++    'remoting%': '<(remoting)',
++    'enable_one_click_signin%': '<(enable_one_click_signin)',
++    'enable_webrtc%': '<(enable_webrtc)',
++    'chromium_win_pch%': '<(chromium_win_pch)',
++    'configuration_policy%': '<(configuration_policy)',
++    'safe_browsing%': '<(safe_browsing)',
++    'input_speech%': '<(input_speech)',
++    'notifications%': '<(notifications)',
++    'clang_use_chrome_plugins%': '<(clang_use_chrome_plugins)',
++    'asan%': '<(asan)',
++    'tsan%': '<(tsan)',
++    'clang_type_profiler%': '<(clang_type_profiler)',
++    'order_profiling%': '<(order_profiling)',
++    'order_text_section%': '<(order_text_section)',
++    'enable_extensions%': '<(enable_extensions)',
++    'enable_web_intents%': '<(enable_web_intents)',
++    'enable_web_intents_tag%': '<(enable_web_intents_tag)',
++    'enable_plugin_installation%': '<(enable_plugin_installation)',
++    'enable_protector_service%': '<(enable_protector_service)',
++    'enable_session_service%': '<(enable_session_service)',
++    'enable_themes%': '<(enable_themes)',
++    'use_oem_wallpaper%': '<(use_oem_wallpaper)',
++    'enable_background%': '<(enable_background)',
++    'linux_use_gold_binary%': '<(linux_use_gold_binary)',
++    'linux_use_gold_flags%': '<(linux_use_gold_flags)',
++    'use_canvas_skia%': '<(use_canvas_skia)',
++    'test_isolation_mode%': '<(test_isolation_mode)',
++    'test_isolation_outdir%': '<(test_isolation_outdir)',
++    'enable_automation%': '<(enable_automation)',
++    'enable_printing%': '<(enable_printing)',
++    'enable_captive_portal_detection%': '<(enable_captive_portal_detection)',
++    'disable_ftp_support%': '<(disable_ftp_support)',
++    'force_rlz_use_chrome_net%': '<(force_rlz_use_chrome_net)',
++    'enable_task_manager%': '<(enable_task_manager)',
++    'sas_dll_path%': '<(sas_dll_path)',
++    'wix_path%': '<(wix_path)',
++    'android_upstream_bringup%': '<(android_upstream_bringup)',
++    'use_libjpeg_turbo%': '<(use_libjpeg_turbo)',
++    'use_system_libjpeg%': '<(use_system_libjpeg)',
++    'android_build_type%': '<(android_build_type)',
++    'use_official_google_api_keys%': '<(use_official_google_api_keys)',
++    'google_api_key%': '<(google_api_key)',
++    'google_default_client_id%': '<(google_default_client_id)',
++    'google_default_client_secret%': '<(google_default_client_secret)',
++
++    # Use system yasm instead of bundled one.
++    'use_system_yasm%': 0,
++
++    # Default to enabled PIE; this is important for ASLR but we may need to be
++    # able to turn it off for various reasons.
++    'linux_disable_pie%': 0,
++
++    # The release channel that this build targets. This is used to restrict
++    # channel-specific build options, like which installer packages to create.
++    # The default is 'all', which does no channel-specific filtering.
++    'channel%': 'all',
++
++    # Override chromium_mac_pch and set it to 0 to suppress the use of
++    # precompiled headers on the Mac.  Prefix header injection may still be
++    # used, but prefix headers will not be precompiled.  This is useful when
++    # using distcc to distribute a build to compile slaves that don't
++    # share the same compiler executable as the system driving the compilation,
++    # because precompiled headers rely on pointers into a specific compiler
++    # executable's image.  Setting this to 0 is needed to use an experimental
++    # Linux-Mac cross compiler distcc farm.
++    'chromium_mac_pch%': 1,
++
++    # The default value for mac_strip in target_defaults. This cannot be
++    # set there, per the comment about variable% in a target_defaults.
++    'mac_strip_release%': 1,
++
++    # Set to 1 to enable code coverage.  In addition to build changes
++    # (e.g. extra CFLAGS), also creates a new target in the src/chrome
++    # project file called "coverage".
++    # Currently ignored on Windows.
++    'coverage%': 0,
++
++    # Set to 1 to force Visual C++ to use legacy debug information format /Z7.
++    # This is useful for parallel compilation tools which can't support /Zi.
++    # Only used on Windows.
++    'win_z7%' : 0,
++
++    # Although base/allocator lets you select a heap library via an
++    # environment variable, the libcmt shim it uses sometimes gets in
++    # the way.  To disable it entirely, and switch to normal msvcrt, do e.g.
++    #  'win_use_allocator_shim': 0,
++    #  'win_release_RuntimeLibrary': 2
++    # to ~/.gyp/include.gypi, gclient runhooks --force, and do a release build.
++    'win_use_allocator_shim%': 1, # 1 = shim allocator via libcmt; 0 = msvcrt
++
++    # Whether usage of OpenMAX is enabled.
++    'enable_openmax%': 0,
++
++    # Whether proprietary audio/video codecs are assumed to be included with
++    # this build (only meaningful if branding!=Chrome).
++    'proprietary_codecs%': 0,
++
++    # TODO(bradnelson): eliminate this when possible.
++    # To allow local gyp files to prevent release.vsprops from being included.
++    # Yes(1) means include release.vsprops.
++    # Once all vsprops settings are migrated into gyp, this can go away.
++    'msvs_use_common_release%': 1,
++
++    # TODO(bradnelson): eliminate this when possible.
++    # To allow local gyp files to override additional linker options for msvs.
++    # Yes(1) means set use the common linker options.
++    'msvs_use_common_linker_extras%': 1,
++
++    # TODO(sgk): eliminate this if possible.
++    # It would be nicer to support this via a setting in 'target_defaults'
++    # in chrome/app/locales/locales.gypi overriding the setting in the
++    # 'Debug' configuration in the 'target_defaults' dict below,
++    # but that doesn't work as we'd like.
++    'msvs_debug_link_incremental%': '2',
++
++    # Needed for some of the largest modules.
++    'msvs_debug_link_nonincremental%': '1',
++
++    # Turns on Use Library Dependency Inputs for linking chrome.dll on Windows
++    # to get incremental linking to be faster in debug builds.
++    'incremental_chrome_dll%': '0',
++
++    # The default settings for third party code for treating
++    # warnings-as-errors. Ideally, this would not be required, however there
++    # is some third party code that takes a long time to fix/roll. So, this
++    # flag allows us to have warnings as errors in general to prevent
++    # regressions in most modules, while working on the bits that are
++    # remaining.
++    'win_third_party_warn_as_error%': 'true',
++
++    # This is the location of the sandbox binary. Chrome looks for this before
++    # running the zygote process. If found, and SUID, it will be used to
++    # sandbox the zygote process and, thus, all renderer processes.
++    'linux_sandbox_path%': '',
++
++    # Set this to true to enable SELinux support.
++    'selinux%': 0,
++
++    # Clang stuff.
++    'clang%': '<(clang)',
++    'make_clang_dir%': 'third_party/llvm-build/Release+Asserts',
++
++    # These two variables can be set in GYP_DEFINES while running
++    # |gclient runhooks| to let clang run a plugin in every compilation.
++    # Only has an effect if 'clang=1' is in GYP_DEFINES as well.
++    # Example:
++    #     GYP_DEFINES='clang=1 clang_load=/abs/path/to/libPrintFunctionNames.dylib clang_add_plugin=print-fns' gclient runhooks
++
++    'clang_load%': '',
++    'clang_add_plugin%': '',
++
++    # The default type of gtest.
++    'gtest_target_type%': 'executable',
++
++    # Enable sampling based profiler.
++    # See http://google-perftools.googlecode.com/svn/trunk/doc/cpuprofile.html
++    'profiling%': '0',
++
++    # Enable strict glibc debug mode.
++    'glibcxx_debug%': 0,
++
++    # Override whether we should use Breakpad on Linux. I.e. for Chrome bot.
++    'linux_breakpad%': 0,
++    # And if we want to dump symbols for Breakpad-enabled builds.
++    'linux_dump_symbols%': 0,
++    # And if we want to strip the binary after dumping symbols.
++    'linux_strip_binary%': 0,
++    # Strip the test binaries needed for Linux reliability tests.
++    'linux_strip_reliability_tests%': 0,
++
++    # Enable TCMalloc.
++    'linux_use_tcmalloc%': 1,
++
++    # Disable TCMalloc's debugallocation.
++    'linux_use_debugallocation%': 0,
++
++    # Disable TCMalloc's heapchecker.
++    'linux_use_heapchecker%': 0,
++
++    # Disable shadow stack keeping used by heapcheck to unwind the stacks
++    # better.
++    'linux_keep_shadow_stacks%': 0,
++
++    # Set to 1 to link against libgnome-keyring instead of using dlopen().
++    'linux_link_gnome_keyring%': 0,
++    # Set to 1 to link against gsettings APIs instead of using dlopen().
++    'linux_link_gsettings%': 0,
++
++    # Set Thumb compilation flags.
++    'arm_thumb%': 0,
++
++    # Set ARM fpu compilation flags (only meaningful if armv7==1 and
++    # arm_neon==0).
++    'arm_fpu%': 'vfpv3',
++
++    # Set ARM float abi compilation flag.
++    'arm_float_abi%': 'softfp',
++
++    # Enable new NPDevice API.
++    'enable_new_npdevice_api%': 0,
++
++    # Enable EGLImage support in OpenMAX
++    'enable_eglimage%': 1,
++
++    # Enable a variable used elsewhere throughout the GYP files to determine
++    # whether to compile in the sources for the GPU plugin / process.
++    'enable_gpu%': 1,
++
++    # .gyp files or targets should set chromium_code to 1 if they build
++    # Chromium-specific code, as opposed to external code.  This variable is
++    # used to control such things as the set of warnings to enable, and
++    # whether warnings are treated as errors.
++    'chromium_code%': 0,
++
++    'release_valgrind_build%': 0,
++
++    # TODO(thakis): Make this a blacklist instead, http://crbug.com/101600
++    'enable_wexit_time_destructors%': 0,
++
++    # Set to 1 to compile with the built in pdf viewer.
++    'internal_pdf%': 0,
++
++    # Set to 1 to compile with the OpenGL ES 2.0 conformance tests.
++    'internal_gles2_conform_tests%': 0,
++
++    # NOTE: When these end up in the Mac bundle, we need to replace '-' for '_'
++    # so Cocoa is happy (http://crbug.com/20441).
++    'locales': [
++      'am', 'ar', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'en-GB',
++      'en-US', 'es-419', 'es', 'et', 'fa', 'fi', 'fil', 'fr', 'gu', 'he',
++      'hi', 'hr', 'hu', 'id', 'it', 'ja', 'kn', 'ko', 'lt', 'lv',
++      'ml', 'mr', 'ms', 'nb', 'nl', 'pl', 'pt-BR', 'pt-PT', 'ro', 'ru',
++      'sk', 'sl', 'sr', 'sv', 'sw', 'ta', 'te', 'th', 'tr', 'uk',
++      'vi', 'zh-CN', 'zh-TW',
++    ],
++
++    # Pseudo locales are special locales which are used for testing and
++    # debugging. They don't get copied to the final app. For more info,
++    # check out https://sites.google.com/a/chromium.org/dev/Home/fake-bidi
++    'pseudo_locales': [
++      'fake-bidi',
++    ],
++
++    'grit_defines': [],
++
++    # If debug_devtools is set to 1, JavaScript files for DevTools are
++    # stored as is and loaded from disk. Otherwise, a concatenated file
++    # is stored in resources.pak. It is still possible to load JS files
++    # from disk by passing --debug-devtools cmdline switch.
++    'debug_devtools%': 0,
++
++    # The Java Bridge is not compiled in by default.
++    'java_bridge%': 0,
++
++    # Code signing for iOS binaries.  The bots need to be able to disable this.
++    'chromium_ios_signing%': 1,
++
++    # This flag is only used when disable_nacl==0 and disables all those
++    # subcomponents which would require the installation of a native_client
++    # untrusted toolchain.
++    'disable_nacl_untrusted%': 0,
++
++    # Disable Dart by default.
++    'enable_dart%': 0,
++
++    # The desired version of Windows SDK can be set in ~/.gyp/include.gypi.
++    'msbuild_toolset%': '',
++
++    # Native Client is enabled by default.
++    'disable_nacl%': 0,
++
++    # Whether to build full debug version for Debug configuration on Android.
++    # Compared to full debug version, the default Debug configuration on Android
++    # has no full v8 debug, has size optimization and linker gc section, so that
++    # we can build a debug version with acceptable size and performance.
++    'android_full_debug%': 0,
++
++    # Sets the default version name and code for Android app, by default we
++    # do a developer build.
++    'android_app_version_name%': 'Developer Build',
++    'android_app_version_code%': 0,
++
++    'sas_dll_exists': 0, # '<!(<(PYTHON) <(DEPTH)/build/dir_exists.py <(sas_dll_path))',
++    'wix_exists': 0, # '<!(<(PYTHON) <(DEPTH)/build/dir_exists.py <(wix_path))',
++
++    'windows_sdk_default_path': '<(DEPTH)/third_party/platformsdk_win8/files',
++#    'directx_sdk_default_path': '<(DEPTH)/third_party/directxsdk/files',
++    'windows_sdk_path%': '<(windows_sdk_default_path)',
++
++    'conditions': [
++      #['"<!(<(PYTHON) <(DEPTH)/build/dir_exists.py <(windows_sdk_default_path))"=="True"', {
++      #  'windows_sdk_path%': '<(windows_sdk_default_path)',
++      #}, {
++      #  'windows_sdk_path%': 'C:/Program Files (x86)/Windows Kits/8.0',
++      #}],
++      #['OS=="win" and "<!(<(PYTHON) <(DEPTH)/build/dir_exists.py <(directx_sdk_default_path))"=="True"', {
++      #  'directx_sdk_path%': '<(directx_sdk_default_path)',
++      #}, {
++      #  'directx_sdk_path%': '$(DXSDK_DIR)',
++      #}],
++      # If use_official_google_api_keys is already set (to 0 or 1), we
++      # do none of the implicit checking.  If it is set to 1 and the
++      # internal keys file is missing, the build will fail at compile
++      # time.  If it is set to 0 and keys are not provided by other
++      # means, a warning will be printed at compile time.
++      ['use_official_google_api_keys==2', {
++        'use_official_google_api_keys%':
++            '<!(<(PYTHON) <(DEPTH)/google_apis/build/check_internal.py <(DEPTH)/google_apis/internal/google_chrome_api_keys.h)',
++      }],
++      ['os_posix==1 and OS!="mac" and OS!="ios"', {
++        # Figure out the python architecture to decide if we build pyauto.
++	# disabled for mozilla because windows != mac and this runs a shell script
++	#        'python_arch%': '<!(<(DEPTH)/build/linux/python_arch.sh <(sysroot)/usr/<(system_libdir)/libpython<(python_ver).so.1.0)',
++        'conditions': [
++          # TODO(glider): set clang to 1 earlier for ASan and TSan builds so
++          # that it takes effect here.
++          # disabled for Mozilla since it doesn't use this, and 'msys' messes $(CXX) up
++          ['build_with_mozilla==0 and clang==0 and asan==0 and tsan==0', {
++            # This will set gcc_version to XY if you are running gcc X.Y.*.
++            'gcc_version%': '<!(<(PYTHON) <(DEPTH)/build/compiler_version.py)',
++          }, {
++            'gcc_version%': 0,
++          }],
++          ['branding=="Chrome"', {
++            'linux_breakpad%': 1,
++          }],
++          # All Chrome builds have breakpad symbols, but only process the
++          # symbols from official builds.
++          ['(branding=="Chrome" and buildtype=="Official")', {
++            'linux_dump_symbols%': 1,
++          }],
++        ],
++      }],  # os_posix==1 and OS!="mac" and OS!="ios"
++      ['OS=="ios"', {
++        'disable_nacl%': 1,
++        'enable_gpu%': 0,
++        'icu_use_data_file_flag%': 1,
++        'use_system_bzip2%': 1,
++        'use_system_libxml%': 1,
++        'use_system_sqlite%': 1,
++
++        # The Mac SDK is set for iOS builds and passed through to Mac
++        # sub-builds. This allows the Mac sub-build SDK in an iOS build to be
++        # overridden from the command line the same way it is for a Mac build.
++        'mac_sdk%': '<!(<(PYTHON) <(DEPTH)/build/mac/find_sdk.py 10.6)',
++
++        # iOS SDK and deployment target support.  The iOS 5.0 SDK is actually
++        # what is required, but the value is left blank so when it is set in
++        # the project files it will be the "current" iOS SDK.  Forcing 5.0
++        # even though it is "current" causes Xcode to spit out a warning for
++        # every single project file for not using the "current" SDK.
++        'ios_sdk%': '',
++        'ios_sdk_path%': '',
++        'ios_deployment_target%': '4.3',
++
++        'conditions': [
++          # ios_product_name is set to the name of the .app bundle as it should
++          # appear on disk.
++          ['branding=="Chrome"', {
++            'ios_product_name%': 'Chrome',
++          }, { # else: branding!="Chrome"
++            'ios_product_name%': 'Chromium',
++          }],
++          ['branding=="Chrome" and buildtype=="Official"', {
++            'ios_breakpad%': 1,
++          }, { # else: branding!="Chrome" or buildtype!="Official"
++            'ios_breakpad%': 0,
++          }],
++        ],
++      }],  # OS=="ios"
++      ['OS=="android"', {
++        # Location of Android NDK.
++        'variables': {
++          'variables': {
++            'variables': {
++              'android_ndk_root%': '<!(/bin/echo -n $ANDROID_NDK_ROOT)',
++            },
++            'android_ndk_root%': '<(android_ndk_root)',
++            'conditions': [
++              ['target_arch == "ia32"', {
++                'android_app_abi%': 'x86',
++                'android_ndk_sysroot%': '<(android_ndk_root)/platforms/android-9/arch-x86',
++              }],
++              ['target_arch=="arm"', {
++                'android_ndk_sysroot%': '<(android_ndk_root)/platforms/android-9/arch-arm',
++                'conditions': [
++                  ['armv7==0', {
++                    'android_app_abi%': 'armeabi',
++                  }, {
++                    'android_app_abi%': 'armeabi-v7a',
++                  }],
++                ],
++              }],
++              ['target_arch=="arm64"', {
++                'android_app_abi%': 'arm64-v8a',
++                'android_ndk_sysroot%': '<(android_ndk_root)/platforms/android-21/arch-arm64',
++              }],
++            ],
++          },
++          'android_ndk_root%': '<(android_ndk_root)',
++          'android_app_abi%': '<(android_app_abi)',
++          'android_ndk_sysroot%': '<(android_ndk_sysroot)',
++        },
++        'android_ndk_root%': '<(android_ndk_root)',
++        'android_ndk_sysroot': '<(android_ndk_sysroot)',
++        'android_ndk_include': '<(android_ndk_sysroot)/usr/include',
++        'android_ndk_lib': '<(android_ndk_sysroot)/usr/lib',
++        'android_app_abi%': '<(android_app_abi)',
++
++        # Location of the "strip" binary, used by both gyp and scripts.
++        'android_strip%' : '<!(/bin/echo -n <(android_toolchain)/*-strip)',
++
++        # Provides an absolute path to PRODUCT_DIR (e.g. out/Release). Used
++        # to specify the output directory for Ant in the Android build.
++        'ant_build_out': '`cd <(PRODUCT_DIR) && pwd -P`',
++
++        # Uses Android's crash report system
++        'linux_breakpad%': 0,
++
++        # Always uses openssl.
++        'use_openssl%': 1,
++
++        'proprietary_codecs%': '<(proprietary_codecs)',
++        'enable_task_manager%': 0,
++        'safe_browsing%': 0,
++        'configuration_policy%': 0,
++        'input_speech%': 0,
++        'enable_web_intents%': 0,
++        'enable_automation%': 0,
++        'java_bridge%': 1,
++        'build_ffmpegsumo%': 0,
++        'linux_use_tcmalloc%': 0,
++
++        # Disable Native Client.
++        'disable_nacl%': 1,
++
++        # Android does not support background apps.
++        'enable_background%': 0,
++
++        # Sessions are store separately in the Java side.
++        'enable_session_service%': 0,
++
++        # Set to 1 once we have a notification system for Android.
++        # http://crbug.com/115320
++        'notifications%': 0,
++
++        'p2p_apis%' : 0,
++
++        # TODO(jrg): when 'gtest_target_type'=='shared_library' and
++        # OS==android, make all gtest_targets depend on
++        # testing/android/native_test.gyp:native_test_apk.
++        'gtest_target_type%': 'shared_library',
++
++        # Uses system APIs for decoding audio and video.
++        'use_libffmpeg%': '0',
++
++        # Always use the chromium skia. The use_system_harfbuzz needs to
++        # match use_system_skia.
++        'use_system_skia%': '0',
++        'use_system_harfbuzz%': '0',
++
++        # Configure crash reporting and build options based on release type.
++        'conditions': [
++          ['buildtype=="Official"', {
++            # Only report crash dumps for Official builds.
++            'linux_breakpad%': 1,
++          }, {
++            'linux_breakpad%': 0,
++          }],
++        ],
++
++        # When building as part of the Android system, use system libraries
++        # where possible to reduce ROM size.
++        # TODO(steveblock): Investigate using the system version of sqlite.
++        'use_system_sqlite%': 0,  # '<(android_build_type)',
++        'use_system_expat%': '<(android_build_type)',
++        'use_system_icu%': '<(android_build_type)',
++        'use_system_stlport%': '<(android_build_type)',
++
++        # Copy it out one scope.
++        'android_build_type%': '<(android_build_type)',
++      }],  # OS=="android"
++      ['OS=="mac"', {
++        'variables': {
++          # Mac OS X SDK and deployment target support.  The SDK identifies
++          # the version of the system headers that will be used, and
++          # corresponds to the MAC_OS_X_VERSION_MAX_ALLOWED compile-time
++          # macro.  "Maximum allowed" refers to the operating system version
++          # whose APIs are available in the headers.  The deployment target
++          # identifies the minimum system version that the built products are
++          # expected to function on.  It corresponds to the
++          # MAC_OS_X_VERSION_MIN_REQUIRED compile-time macro.  To ensure these
++          # macros are available, #include <AvailabilityMacros.h>.  Additional
++          # documentation on these macros is available at
++          # http://developer.apple.com/mac/library/technotes/tn2002/tn2064.html#SECTION3
++          # Chrome normally builds with the Mac OS X 10.6 SDK and sets the
++          # deployment target to 10.6.  Other projects, such as O3D, may
++          # override these defaults.
++
++          # Normally, mac_sdk_min is used to find an SDK that Xcode knows
++          # about that is at least the specified version. In official builds,
++          # the SDK must match mac_sdk_min exactly. If the SDK is installed
++          # someplace that Xcode doesn't know about, set mac_sdk_path to the
++          # path to the SDK; when set to a non-empty string, SDK detection
++          # based on mac_sdk_min will be bypassed entirely.
++          'mac_sdk_min%': '10.6',
++          'mac_sdk_path%': '',
++
++          'mac_deployment_target%': '10.6',
++        },
++
++        'mac_sdk_min': '<(mac_sdk_min)',
++        'mac_sdk_path': '<(mac_sdk_path)',
++        'mac_deployment_target': '<(mac_deployment_target)',
++
++        # Enable clang on mac by default!
++        'clang%': 1,
++
++        # Compile in Breakpad support by default so that it can be
++        # tested, even if it is not enabled by default at runtime.
++        'mac_breakpad_compiled_in%': 1,
++        'conditions': [
++          # mac_product_name is set to the name of the .app bundle as it should
++          # appear on disk.  This duplicates data from
++          # chrome/app/theme/chromium/BRANDING and
++          # chrome/app/theme/google_chrome/BRANDING, but is necessary to get
++          # these names into the build system.
++          ['branding=="Chrome"', {
++            'mac_product_name%': 'Google Chrome',
++          }, { # else: branding!="Chrome"
++            'mac_product_name%': 'Chromium',
++          }],
++
++          ['branding=="Chrome" and buildtype=="Official"', {
++            'mac_sdk%': '<!(<(PYTHON) <(DEPTH)/build/mac/find_sdk.py --verify <(mac_sdk_min) --sdk_path=<(mac_sdk_path))',
++            # Enable uploading crash dumps.
++            'mac_breakpad_uploads%': 1,
++            # Enable dumping symbols at build time for use by Mac Breakpad.
++            'mac_breakpad%': 1,
++            # Enable Keystone auto-update support.
++            'mac_keystone%': 1,
++          }, { # else: branding!="Chrome" or buildtype!="Official"
++            'mac_sdk%': '<!(<(PYTHON) <(DEPTH)/build/mac/find_sdk.py <(mac_sdk_min))',
++            'mac_breakpad_uploads%': 0,
++            'mac_breakpad%': 0,
++            'mac_keystone%': 0,
++          }],
++        ],
++      }],  # OS=="mac"
++
++      ['OS=="win"', {
++        'conditions': [
++          ['component=="shared_library"', {
++            'win_use_allocator_shim%': 0,
++          }],
++          ['component=="shared_library" and "<(GENERATOR)"=="ninja"', {
++            # Only enabled by default for ninja because it's buggy in VS.
++            # Not enabled for component=static_library because some targets
++            # are too large and the toolchain fails due to the size of the
++            # .obj files.
++            'incremental_chrome_dll%': 1,
++          }],
++          # Don't do incremental linking for large modules on 32-bit.
++          ['MSVS_OS_BITS==32', {
++            'msvs_large_module_debug_link_mode%': '1',  # No
++          },{
++            'msvs_large_module_debug_link_mode%': '2',  # Yes
++          }],
++          ['MSVS_VERSION=="2010e" or MSVS_VERSION=="2008e" or MSVS_VERSION=="2005e"', {
++            'msvs_express%': 1,
++            'secure_atl%': 0,
++          },{
++            'msvs_express%': 0,
++            'secure_atl%': 1,
++          }],
++        ],
++        'nacl_win64_defines': [
++          # This flag is used to minimize dependencies when building
++          # Native Client loader for 64-bit Windows.
++          'NACL_WIN64',
++        ],
++      }],
++
++      ['os_posix==1 and chromeos==0 and OS!="android"', {
++        'use_cups%': 1,
++      }, {
++        'use_cups%': 0,
++      }],
++
++      # Native Client glibc toolchain is enabled by default except on arm.
++      ['target_arch=="arm"', {
++        'disable_glibc%': 1,
++      }, {
++        'disable_glibc%': 0,
++      }],
++
++      # Disable SSE2 when building for ARM or MIPS.
++      ['target_arch=="arm" or target_arch=="mipsel"', {
++        'disable_sse2%': 1,
++      }, {
++        'disable_sse2%': '<(disable_sse2)',
++      }],
++
++      # Set the relative path from this file to the GYP file of the JPEG
++      # library used by Chromium.
++      ['use_system_libjpeg==1 or use_libjpeg_turbo==0', {
++        # Configuration for using the system libjeg is here.
++        'libjpeg_gyp_path': '../third_party/libjpeg/libjpeg.gyp',
++      }, {
++        'libjpeg_gyp_path': '../third_party/libjpeg_turbo/libjpeg.gyp',
++      }],
++
++      # Options controlling the use of GConf (the classic GNOME configuration
++      # system) and GIO, which contains GSettings (the new GNOME config system).
++      ['chromeos==1', {
++        'use_gconf%': 0,
++        'use_gio%': 0,
++      }, {
++        'use_gconf%': 1,
++        'use_gio%': 1,
++      }],
++
++      # Set up -D and -E flags passed into grit.
++      ['branding=="Chrome"', {
++        # TODO(mmoss) The .grd files look for _google_chrome, but for
++        # consistency they should look for google_chrome_build like C++.
++        'grit_defines': ['-D', '_google_chrome',
++                         '-E', 'CHROMIUM_BUILD=google_chrome'],
++      }, {
++        'grit_defines': ['-D', '_chromium',
++                         '-E', 'CHROMIUM_BUILD=chromium'],
++      }],
++      ['chromeos==1', {
++        'grit_defines': ['-D', 'chromeos', '-D', 'scale_factors=2x'],
++      }],
++      ['toolkit_views==1', {
++        'grit_defines': ['-D', 'toolkit_views'],
++      }],
++      ['use_aura==1', {
++        'grit_defines': ['-D', 'use_aura'],
++      }],
++      ['use_ash==1', {
++        'grit_defines': ['-D', 'use_ash'],
++      }],
++      ['use_nss==1', {
++        'grit_defines': ['-D', 'use_nss'],
++      }],
++      ['file_manager_extension==1', {
++        'grit_defines': ['-D', 'file_manager_extension'],
++      }],
++      ['remoting==1', {
++        'grit_defines': ['-D', 'remoting'],
++      }],
++      ['use_titlecase_in_grd_files==1', {
++        'grit_defines': ['-D', 'use_titlecase'],
++      }],
++      ['use_third_party_translations==1', {
++        'grit_defines': ['-D', 'use_third_party_translations'],
++        'locales': [
++          'ast', 'bs', 'ca@valencia', 'en-AU', 'eo', 'eu', 'gl', 'hy', 'ia',
++          'ka', 'ku', 'kw', 'ms', 'ug'
++        ],
++      }],
++      ['OS=="android"', {
++        'grit_defines': ['-D', 'android'],
++      }],
++      ['OS=="mac"', {
++        'grit_defines': ['-D', 'scale_factors=2x'],
++      }],
++      ['OS == "ios"', {
++        'grit_defines': [
++          # define for iOS specific resources.
++          '-D', 'ios',
++          # iOS uses a whitelist to filter resources.
++          '-w', '<(DEPTH)/build/ios/grit_whitelist.txt'
++        ],
++      }],
++      ['enable_extensions==1', {
++        'grit_defines': ['-D', 'enable_extensions'],
++      }],
++      ['enable_printing==1', {
++        'grit_defines': ['-D', 'enable_printing'],
++      }],
++      ['enable_themes==1', {
++        'grit_defines': ['-D', 'enable_themes'],
++      }],
++      ['use_oem_wallpaper==1', {
++        'grit_defines': ['-D', 'use_oem_wallpaper'],
++      }],
++      ['clang_use_chrome_plugins==1 and OS!="win"', {
++        'clang_chrome_plugins_flags': [
++          '<!@(<(DEPTH)/tools/clang/scripts/plugin_flags.sh)'
++        ],
++      }],
++
++      ['enable_web_intents_tag==1', {
++        'grit_defines': ['-D', 'enable_web_intents_tag'],
++      }],
++
++      ['asan==1', {
++        'clang%': 1,
++      }],
++      ['asan==1 and OS=="mac"', {
++        # See http://crbug.com/145503.
++        'component': "static_library",
++      }],
++      ['tsan==1', {
++        'clang%': 1,
++      }],
++
++      ['OS=="linux" and clang_type_profiler==1', {
++        'clang%': 1,
++        'clang_use_chrome_plugins%': 0,
++        'make_clang_dir%': 'third_party/llvm-allocated-type/Linux_x64',
++      }],
++
++      # On valgrind bots, override the optimizer settings so we don't inline too
++      # much and make the stacks harder to figure out.
++      #
++      # TODO(rnk): Kill off variables that no one else uses and just implement
++      # them under a build_for_tool== condition.
++      ['build_for_tool=="memcheck" or build_for_tool=="tsan"', {
++        # gcc flags
++        'mac_debug_optimization': '1',
++        'mac_release_optimization': '1',
++        'release_optimize': '1',
++        'no_gc_sections': 1,
++        'debug_extra_cflags': '-g -fno-inline -fno-omit-frame-pointer '
++                              '-fno-builtin -fno-optimize-sibling-calls',
++        'release_extra_cflags': '-g -fno-inline -fno-omit-frame-pointer '
++                                '-fno-builtin -fno-optimize-sibling-calls',
++
++        # MSVS flags for TSan on Pin and Windows.
++        'win_debug_RuntimeChecks': '0',
++        'win_debug_disable_iterator_debugging': '1',
++        'win_debug_Optimization': '1',
++        'win_debug_InlineFunctionExpansion': '0',
++        'win_release_InlineFunctionExpansion': '0',
++        'win_release_OmitFramePointers': '0',
++
++        'linux_use_tcmalloc': 1,
++        'release_valgrind_build': 1,
++        'werror': '',
++        'component': 'static_library',
++        'use_system_zlib': 0,
++      }],
++
++      # Build tweaks for DrMemory.
++      # TODO(rnk): Combine with tsan config to share the builder.
++      # http://crbug.com/108155
++      ['build_for_tool=="drmemory"', {
++        # These runtime checks force initialization of stack vars which blocks
++        # DrMemory's uninit detection.
++        'win_debug_RuntimeChecks': '0',
++        # Iterator debugging is slow.
++        'win_debug_disable_iterator_debugging': '1',
++        # Try to disable optimizations that mess up stacks in a release build.
++        'win_release_InlineFunctionExpansion': '0',
++        'win_release_OmitFramePointers': '0',
++        # Ditto for debug, to support bumping win_debug_Optimization.
++        'win_debug_InlineFunctionExpansion': 0,
++        'win_debug_OmitFramePointers': 0,
++        # Keep the code under #ifndef NVALGRIND.
++        'release_valgrind_build': 1,
++      }],
++    ],
++
++    # List of default apps to install in new profiles.  The first list contains
++    # the source files as found in svn.  The second list, used only for linux,
++    # contains the destination location for each of the files.  When a crx
++    # is added or removed from the list, the chrome/browser/resources/
++    # default_apps/external_extensions.json file must also be updated.
++    'default_apps_list': [
++      'browser/resources/default_apps/external_extensions.json',
++      'browser/resources/default_apps/gmail.crx',
++      'browser/resources/default_apps/search.crx',
++      'browser/resources/default_apps/youtube.crx',
++      'browser/resources/default_apps/drive.crx',
++      'browser/resources/default_apps/docs.crx',
++    ],
++    'default_apps_list_linux_dest': [
++      '<(PRODUCT_DIR)/default_apps/external_extensions.json',
++      '<(PRODUCT_DIR)/default_apps/gmail.crx',
++      '<(PRODUCT_DIR)/default_apps/search.crx',
++      '<(PRODUCT_DIR)/default_apps/youtube.crx',
++      '<(PRODUCT_DIR)/default_apps/drive.crx',
++      '<(PRODUCT_DIR)/default_apps/docs.crx',
++    ],
++  },
++  'target_defaults': {
++    'variables': {
++      # The condition that operates on chromium_code is in a target_conditions
++      # section, and will not have access to the default fallback value of
++      # chromium_code at the top of this file, or to the chromium_code
++      # variable placed at the root variables scope of .gyp files, because
++      # those variables are not set at target scope.  As a workaround,
++      # if chromium_code is not set at target scope, define it in target scope
++      # to contain whatever value it has during early variable expansion.
++      # That's enough to make it available during target conditional
++      # processing.
++      'chromium_code%': '<(chromium_code)',
++
++      # See http://msdn.microsoft.com/en-us/library/aa652360(VS.71).aspx
++      'win_release_Optimization%': '2', # 2 = /Os
++      'win_debug_Optimization%': '0',   # 0 = /Od
++
++      # See http://msdn.microsoft.com/en-us/library/2kxx5t2c(v=vs.80).aspx
++      # Tri-state: blank is default, 1 on, 0 off
++      'win_release_OmitFramePointers%': '0',
++      # Tri-state: blank is default, 1 on, 0 off
++      'win_debug_OmitFramePointers%': '',
++
++      # See http://msdn.microsoft.com/en-us/library/8wtf2dfz(VS.71).aspx
++      'win_debug_RuntimeChecks%': '3',    # 3 = all checks enabled, 0 = off
++
++      # See http://msdn.microsoft.com/en-us/library/47238hez(VS.71).aspx
++      'win_debug_InlineFunctionExpansion%': '',    # empty = default, 0 = off,
++      'win_release_InlineFunctionExpansion%': '2', # 1 = only __inline, 2 = max
++
++      # VS inserts quite a lot of extra checks to algorithms like
++      # std::partial_sort in Debug build which make them O(N^2)
++      # instead of O(N*logN). This is particularly slow under memory
++      # tools like ThreadSanitizer so we want it to be disablable.
++      # See http://msdn.microsoft.com/en-us/library/aa985982(v=VS.80).aspx
++      'win_debug_disable_iterator_debugging%': '0',
++
++      'release_extra_cflags%': '',
++      'debug_extra_cflags%': '',
++
++      'release_valgrind_build%': '<(release_valgrind_build)',
++
++      # the non-qualified versions are widely assumed to be *nix-only
++      'win_release_extra_cflags%': '',
++      'win_debug_extra_cflags%': '',
++
++      # TODO(thakis): Make this a blacklist instead, http://crbug.com/101600
++      'enable_wexit_time_destructors%': '<(enable_wexit_time_destructors)',
++
++      # Only used by Windows build for now.  Can be used to build into a
++      # differet output directory, e.g., a build_dir_prefix of VS2010_ would
++      # output files in src/build/VS2010_{Debug,Release}.
++      'build_dir_prefix%': '',
++
++      # Targets are by default not nacl untrusted code.
++      'nacl_untrusted_build%': 0,
++
++      'conditions': [
++        ['OS=="win" and component=="shared_library"', {
++          # See http://msdn.microsoft.com/en-us/library/aa652367.aspx
++          'win_release_RuntimeLibrary%': '2', # 2 = /MD (nondebug DLL)
++          'win_debug_RuntimeLibrary%': '3',   # 3 = /MDd (debug DLL)
++        }, {
++          # See http://msdn.microsoft.com/en-us/library/aa652367.aspx
++          'win_release_RuntimeLibrary%': '0', # 0 = /MT (nondebug static)
++          'win_debug_RuntimeLibrary%': '1',   # 1 = /MTd (debug static)
++        }],
++        ['OS=="ios"', {
++          # See http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Optimize-Options.html
++          'mac_release_optimization%': 's', # Use -Os unless overridden
++          'mac_debug_optimization%': '0',   # Use -O0 unless overridden
++        }, {
++          # See http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Optimize-Options.html
++          'mac_release_optimization%': '3', # Use -O3 unless overridden
++          'mac_debug_optimization%': '0',   # Use -O0 unless overridden
++        }],
++      ],
++    },
++    'conditions': [
++      ['OS=="linux" and linux_use_tcmalloc==1 and clang_type_profiler==1', {
++        'cflags_cc!': ['-fno-rtti'],
++        'cflags_cc+': [
++          '-frtti',
++          '-gline-tables-only',
++          '-fintercept-allocation-functions',
++        ],
++        'defines': ['TYPE_PROFILING'],
++        'dependencies': [
++          '<(DEPTH)/base/allocator/allocator.gyp:type_profiler',
++        ],
++      }],
++      ['OS=="win" and "<(msbuild_toolset)"!=""', {
++        'msbuild_toolset': '<(msbuild_toolset)',
++      }],
++      ['branding=="Chrome"', {
++        'defines': ['GOOGLE_CHROME_BUILD'],
++      }, {  # else: branding!="Chrome"
++        'defines': ['CHROMIUM_BUILD'],
++      }],
++      ['OS=="mac" and component=="shared_library"', {
++        'xcode_settings': {
++          'DYLIB_INSTALL_NAME_BASE': '@rpath',
++          'LD_RUNPATH_SEARCH_PATHS': [
++            # For unbundled binaries.
++            '@loader_path/.',
++            # For bundled binaries, to get back from Binary.app/Contents/MacOS.
++            '@loader_path/../../..',
++          ],
++        },
++      }],
++      ['branding=="Chrome" and (OS=="win" or OS=="mac")', {
++        'defines': ['ENABLE_RLZ'],
++      }],
++      ['component=="shared_library"', {
++        'defines': ['COMPONENT_BUILD'],
++      }],
++      ['toolkit_views==1', {
++        'defines': ['TOOLKIT_VIEWS=1'],
++      }],
++      ['ui_compositor_image_transport==1', {
++        'defines': ['UI_COMPOSITOR_IMAGE_TRANSPORT'],
++      }],
++      ['use_aura==1', {
++        'defines': ['USE_AURA=1'],
++      }],
++      ['use_ash==1', {
++        'defines': ['USE_ASH=1'],
++      }],
++      ['use_libjpeg_turbo==1', {
++        'defines': ['USE_LIBJPEG_TURBO=1'],
++      }],
++      ['use_nss==1', {
++        'defines': ['USE_NSS=1'],
++      }],
++      ['enable_one_click_signin==1', {
++        'defines': ['ENABLE_ONE_CLICK_SIGNIN'],
++      }],
++      ['toolkit_uses_gtk==1 and toolkit_views==0', {
++        # TODO(erg): We are progressively sealing up use of deprecated features
++        # in gtk in preparation for an eventual porting to gtk3.
++        'defines': ['GTK_DISABLE_SINGLE_INCLUDES=1'],
++      }],
++      ['chromeos==1', {
++        'defines': ['OS_CHROMEOS=1'],
++      }],
++      ['use_xi2_mt!=0', {
++        'defines': ['USE_XI2_MT=<(use_xi2_mt)'],
++      }],
++      ['file_manager_extension==1', {
++        'defines': ['FILE_MANAGER_EXTENSION=1'],
++      }],
++      ['profiling==1', {
++        'defines': ['ENABLE_PROFILING=1'],
++      }],
++      ['OS=="linux" and glibcxx_debug==1', {
++        'defines': ['_GLIBCXX_DEBUG=1',],
++        'cflags_cc!': ['-fno-rtti'],
++        'cflags_cc+': ['-frtti', '-g'],
++      }],
++      ['OS=="linux"', {
++        # we need lrint(), which is ISOC99, and Xcode
++	# already forces -std=c99 for mac below
++        'defines': ['_ISOC99_SOURCE=1'],
++      }],
++      ['remoting==1', {
++        'defines': ['ENABLE_REMOTING=1'],
++      }],
++      ['enable_webrtc==1', {
++        'defines': ['ENABLE_WEBRTC=1'],
++      }],
++      ['proprietary_codecs==1', {
++        'defines': ['USE_PROPRIETARY_CODECS'],
++      }],
++      ['enable_pepper_threading==1', {
++        'defines': ['ENABLE_PEPPER_THREADING'],
++      }],
++      ['enable_viewport==1', {
++        'defines': ['ENABLE_VIEWPORT'],
++      }],
++      ['configuration_policy==1', {
++        'defines': ['ENABLE_CONFIGURATION_POLICY'],
++      }],
++      ['input_speech==1', {
++        'defines': ['ENABLE_INPUT_SPEECH'],
++      }],
++      ['notifications==1', {
++        'defines': ['ENABLE_NOTIFICATIONS'],
++      }],
++      ['enable_hidpi==1', {
++        'defines': ['ENABLE_HIDPI=1'],
++      }],
++      ['fastbuild!=0', {
++
++        'conditions': [
++          # For Windows and Mac, we don't genererate debug information.
++          ['OS=="win" or OS=="mac"', {
++            'msvs_settings': {
++              'VCLinkerTool': {
++                'GenerateDebugInformation': 'false',
++              },
++              'VCCLCompilerTool': {
++                'DebugInformationFormat': '0',
++              }
++            },
++            'xcode_settings': {
++              'GCC_GENERATE_DEBUGGING_SYMBOLS': 'NO',
++            },
++          }, { # else: OS != "win", generate less debug information.
++            'variables': {
++              'debug_extra_cflags': '-g1',
++            },
++          }],
++          # Clang creates chubby debug information, which makes linking very
++          # slow. For now, don't create debug information with clang.  See
++          # http://crbug.com/70000
++          ['(OS=="linux" or OS=="android") and clang==1', {
++            'variables': {
++              'debug_extra_cflags': '-g0',
++            },
++          }],
++        ],  # conditions for fastbuild.
++      }],  # fastbuild!=0
++      ['dcheck_always_on!=0', {
++        'defines': ['DCHECK_ALWAYS_ON=1'],
++      }],  # dcheck_always_on!=0
++      ['selinux==1', {
++        'defines': ['CHROMIUM_SELINUX=1'],
++      }],
++      ['win_use_allocator_shim==0', {
++        'conditions': [
++          ['OS=="win"', {
++            'defines': ['NO_TCMALLOC'],
++          }],
++        ],
++      }],
++      ['enable_gpu==1', {
++        'defines': [
++          'ENABLE_GPU=1',
++        ],
++      }],
++      ['use_openssl==1', {
++        'defines': [
++          'USE_OPENSSL=1',
++        ],
++      }],
++      ['enable_eglimage==1', {
++        'defines': [
++          'ENABLE_EGLIMAGE=1',
++        ],
++      }],
++      ['use_skia==1', {
++        'defines': [
++          'USE_SKIA=1',
++        ],
++      }],
++      ['coverage!=0', {
++        'conditions': [
++          ['OS=="mac" or OS=="ios"', {
++            'xcode_settings': {
++              'GCC_INSTRUMENT_PROGRAM_FLOW_ARCS': 'YES',  # -fprofile-arcs
++              'GCC_GENERATE_TEST_COVERAGE_FILES': 'YES',  # -ftest-coverage
++            },
++          }],
++          ['OS=="mac"', {
++            # Add -lgcov for types executable, shared_library, and
++            # loadable_module; not for static_library.
++            # This is a delayed conditional.
++            'target_conditions': [
++              ['_type!="static_library"', {
++                'xcode_settings': { 'OTHER_LDFLAGS': [ '-lgcov' ] },
++              }],
++            ],
++          }],
++          ['OS=="linux" or OS=="android"', {
++            'cflags': [ '-ftest-coverage',
++                        '-fprofile-arcs' ],
++            'link_settings': { 'libraries': [ '-lgcov' ] },
++          }],
++          # Finally, for Windows, we simply turn on profiling.
++          ['OS=="win"', {
++            'msvs_settings': {
++              'VCLinkerTool': {
++                'Profile': 'true',
++              },
++              'VCCLCompilerTool': {
++                # /Z7, not /Zi, so coverage is happyb
++                'DebugInformationFormat': '1',
++                'AdditionalOptions': ['/Yd'],
++              }
++            }
++         }],  # OS==win
++        ],  # conditions for coverage
++      }],  # coverage!=0
++      ['OS=="win"', {
++        'defines': [
++          '__STD_C',
++          '_CRT_SECURE_NO_DEPRECATE',
++          '_SCL_SECURE_NO_DEPRECATE',
++        ],
++        'include_dirs': [
++          '<(DEPTH)/third_party/wtl/include',
++        ],
++        'conditions': [
++          ['win_z7!=0', {
++            'msvs_settings': {
++              # Generates debug info when win_z7=1
++              # even if fastbuild=1 (that makes GenerateDebugInformation false).
++              'VCLinkerTool': {
++                'GenerateDebugInformation': 'true',
++              },
++              'VCCLCompilerTool': {
++                'DebugInformationFormat': '1',
++              }
++            }
++          }],
++        ],  # win_z7!=0
++      }],  # OS==win
++      ['enable_task_manager==1', {
++        'defines': [
++          'ENABLE_TASK_MANAGER=1',
++        ],
++      }],
++      ['enable_web_intents==1', {
++        'defines': [
++          'ENABLE_WEB_INTENTS=1',
++        ],
++      }],
++      ['enable_extensions==1', {
++        'defines': [
++          'ENABLE_EXTENSIONS=1',
++        ],
++      }],
++      ['OS=="win" and branding=="Chrome"', {
++        'defines': ['ENABLE_SWIFTSHADER'],
++      }],
++      ['enable_dart==1', {
++        'defines': ['WEBKIT_USING_DART=1'],
++      }],
++      ['enable_plugin_installation==1', {
++        'defines': ['ENABLE_PLUGIN_INSTALLATION=1'],
++      }],
++      ['enable_protector_service==1', {
++        'defines': ['ENABLE_PROTECTOR_SERVICE=1'],
++      }],
++      ['enable_session_service==1', {
++        'defines': ['ENABLE_SESSION_SERVICE=1'],
++      }],
++      ['enable_themes==1', {
++        'defines': ['ENABLE_THEMES=1'],
++      }],
++      ['enable_background==1', {
++        'defines': ['ENABLE_BACKGROUND=1'],
++      }],
++      ['enable_automation==1', {
++        'defines': ['ENABLE_AUTOMATION=1'],
++      }],
++      ['enable_printing==1', {
++        'defines': ['ENABLE_PRINTING=1'],
++      }],
++      ['enable_captive_portal_detection==1', {
++        'defines': ['ENABLE_CAPTIVE_PORTAL_DETECTION=1'],
++      }],
++      ['disable_ftp_support==1', {
++        'defines': ['DISABLE_FTP_SUPPORT=1'],
++      }],
++    ],  # conditions for 'target_defaults'
++    'target_conditions': [
++      ['enable_wexit_time_destructors==1', {
++        'conditions': [
++          [ 'clang==1', {
++            'cflags': [
++              '-Wexit-time-destructors',
++            ],
++            'xcode_settings': {
++              'WARNING_CFLAGS': [
++                '-Wexit-time-destructors',
++              ],
++            },
++          }],
++        ],
++      }],
++      ['chromium_code==0', {
++        'conditions': [
++          [ 'os_posix==1 and OS!="mac" and OS!="ios"', {
++            # We don't want to get warnings from third-party code,
++            # so remove any existing warning-enabling flags like -Wall.
++            'cflags!': [
++              '-Wall',
++              '-Wextra',
++            ],
++            'cflags_cc': [
++              # Don't warn about hash_map in third-party code.
++              '-Wno-deprecated',
++            ],
++            'cflags': [
++              # Don't warn about printf format problems.
++              # This is off by default in gcc but on in Ubuntu's gcc(!).
++              '-Wno-format',
++            ],
++            'cflags_cc!': [
++              # TODO(fischman): remove this.
++              # http://code.google.com/p/chromium/issues/detail?id=90453
++              '-Wsign-compare',
++            ]
++          }],
++          # TODO: Fix all warnings on chromeos too.
++          [ 'os_posix==1 and OS!="mac" and OS!="ios" and (clang!=1 or chromeos==1)', {
++            'cflags!': [
++              '-Werror',
++            ],
++          }],
++          [ 'os_posix==1 and os_bsd!=1 and OS!="mac" and OS!="android"', {
++            'cflags': [
++              # Don't warn about ignoring the return value from e.g. close().
++              # This is off by default in some gccs but on by default in others.
++              # BSD systems do not support this option, since they are usually
++              # using gcc 4.2.1, which does not have this flag yet.
++              '-Wno-unused-result',
++            ],
++          }],
++          [ 'OS=="win"', {
++            'defines': [
++              '_CRT_SECURE_NO_DEPRECATE',
++              '_CRT_NONSTDC_NO_WARNINGS',
++              '_CRT_NONSTDC_NO_DEPRECATE',
++              '_SCL_SECURE_NO_DEPRECATE',
++            ],
++            'msvs_disabled_warnings': [4800],
++            'msvs_settings': {
++              'VCCLCompilerTool': {
++                'WarningLevel': '3',
++                'WarnAsError': '<(win_third_party_warn_as_error)',
++                'Detect64BitPortabilityProblems': 'false',
++              },
++            },
++            'conditions': [
++              ['buildtype=="Official"', {
++                'msvs_settings': {
++                  'VCCLCompilerTool': { 'WarnAsError': 'false' },
++                }
++              }],
++            ],
++          }],
++          # TODO(darin): Unfortunately, some third_party code depends on base/
++          [ 'OS=="win" and component=="shared_library"', {
++            'msvs_disabled_warnings': [
++              4251,  # class 'std::xx' needs to have dll-interface.
++            ],
++          }],
++          [ 'OS=="mac" or OS=="ios"', {
++            'xcode_settings': {
++              'WARNING_CFLAGS!': ['-Wall', '-Wextra'],
++            },
++            'conditions': [
++              ['buildtype=="Official"', {
++                'xcode_settings': {
++                  'GCC_TREAT_WARNINGS_AS_ERRORS': 'NO',    # -Werror
++                },
++              }],
++            ],
++          }],
++          [ 'OS=="ios"', {
++            'xcode_settings': {
++              # TODO(ios): Fix remaining warnings in third-party code, then
++              # remove this; the Mac cleanup didn't get everything that's
++              # flagged in an iOS build.
++              'GCC_TREAT_WARNINGS_AS_ERRORS': 'NO',
++              'RUN_CLANG_STATIC_ANALYZER': 'NO',
++            },
++          }],
++        ],
++      }, {
++        'includes': [
++           # Rules for excluding e.g. foo_win.cc from the build on non-Windows.
++          'filename_rules.gypi',
++        ],
++        # In Chromium code, we define __STDC_FORMAT_MACROS in order to get the
++        # C99 macros on Mac and Linux.
++        'defines': [
++          '__STDC_FORMAT_MACROS',
++        ],
++        'conditions': [
++          ['OS=="win"', {
++            # turn on warnings for signed/unsigned mismatch on chromium code.
++            'msvs_settings': {
++              'VCCLCompilerTool': {
++                'AdditionalOptions': ['/we4389'],
++              },
++            },
++          }],
++          ['OS=="win" and component=="shared_library"', {
++            'msvs_disabled_warnings': [
++              4251,  # class 'std::xx' needs to have dll-interface.
++            ],
++          }],
++        ],
++      }],
++    ],  # target_conditions for 'target_defaults'
++    'default_configuration': 'Debug',
++    'configurations': {
++      # VCLinkerTool LinkIncremental values below:
++      #   0 == default
++      #   1 == /INCREMENTAL:NO
++      #   2 == /INCREMENTAL
++      # Debug links incremental, Release does not.
++      #
++      # Abstract base configurations to cover common attributes.
++      #
++      'Common_Base': {
++        'abstract': 1,
++        'msvs_configuration_attributes': {
++          'OutputDirectory': '<(DEPTH)\\build\\<(build_dir_prefix)$(ConfigurationName)',
++          'IntermediateDirectory': '$(OutDir)\\obj\\$(ProjectName)',
++          'CharacterSet': '1',
++        },
++      },
++      'x86_Base': {
++        'abstract': 1,
++        'msvs_settings': {
++          'VCLinkerTool': {
++            'TargetMachine': '1',
++          },
++        },
++        'msvs_configuration_platform': 'Win32',
++      },
++      'x64_Base': {
++        'abstract': 1,
++        'msvs_configuration_platform': 'x64',
++        'msvs_settings': {
++          'VCLinkerTool': {
++            'TargetMachine': '17', # x86 - 64
++            'AdditionalLibraryDirectories!':
++              ['<(windows_sdk_path)/Lib/win8/um/x86'],
++            'AdditionalLibraryDirectories':
++              ['<(windows_sdk_path)/Lib/win8/um/x64'],
++          },
++          'VCLibrarianTool': {
++            'AdditionalLibraryDirectories!':
++              ['<(windows_sdk_path)/Lib/win8/um/x86'],
++            'AdditionalLibraryDirectories':
++              ['<(windows_sdk_path)/Lib/win8/um/x64'],
++          },
++        },
++        'defines': [
++          # Not sure if tcmalloc works on 64-bit Windows.
++          'NO_TCMALLOC',
++        ],
++      },
++      'Debug_Base': {
++        'abstract': 1,
++        'defines': [
++          'DYNAMIC_ANNOTATIONS_ENABLED=1',
++          'WTF_USE_DYNAMIC_ANNOTATIONS=1',
++        ],
++        'xcode_settings': {
++          'COPY_PHASE_STRIP': 'NO',
++          'GCC_OPTIMIZATION_LEVEL': '<(mac_debug_optimization)',
++          'OTHER_CFLAGS': [
++            '<@(debug_extra_cflags)',
++          ],
++        },
++        'msvs_settings': {
++          'VCCLCompilerTool': {
++            'Optimization': '<(win_debug_Optimization)',
++            'PreprocessorDefinitions': ['_DEBUG'],
++            'BasicRuntimeChecks': '<(win_debug_RuntimeChecks)',
++            'RuntimeLibrary': '<(win_debug_RuntimeLibrary)',
++            'conditions': [
++              # According to MSVS, InlineFunctionExpansion=0 means
++              # "default inlining", not "/Ob0".
++              # Thus, we have to handle InlineFunctionExpansion==0 separately.
++              ['win_debug_InlineFunctionExpansion==0', {
++                'AdditionalOptions': ['/Ob0'],
++              }],
++              ['win_debug_InlineFunctionExpansion!=""', {
++                'InlineFunctionExpansion':
++                  '<(win_debug_InlineFunctionExpansion)',
++              }],
++              ['win_debug_disable_iterator_debugging==1', {
++                'PreprocessorDefinitions': ['_HAS_ITERATOR_DEBUGGING=0'],
++              }],
++
++              # if win_debug_OmitFramePointers is blank, leave as default
++              ['win_debug_OmitFramePointers==1', {
++                'OmitFramePointers': 'true',
++              }],
++              ['win_debug_OmitFramePointers==0', {
++                'OmitFramePointers': 'false',
++                # The above is not sufficient (http://crbug.com/106711): it
++                # simply eliminates an explicit "/Oy", but both /O2 and /Ox
++                # perform FPO regardless, so we must explicitly disable.
++                # We still want the false setting above to avoid having
++                # "/Oy /Oy-" and warnings about overriding.
++                'AdditionalOptions': ['/Oy-'],
++              }],
++            ],
++            'AdditionalOptions': [ '<@(win_debug_extra_cflags)', ],
++          },
++          'VCLinkerTool': {
++            'LinkIncremental': '<(msvs_debug_link_incremental)',
++            # ASLR makes debugging with windbg difficult because Chrome.exe and
++            # Chrome.dll share the same base name. As result, windbg will
++            # name the Chrome.dll module like chrome_<base address>, where
++            # <base address> typically changes with each launch. This in turn
++            # means that breakpoints in Chrome.dll don't stick from one launch
++            # to the next. For this reason, we turn ASLR off in debug builds.
++            # Note that this is a three-way bool, where 0 means to pick up
++            # the default setting, 1 is off and 2 is on.
++            'RandomizedBaseAddress': 1,
++          },
++          'VCResourceCompilerTool': {
++            'PreprocessorDefinitions': ['_DEBUG'],
++          },
++        },
++        'conditions': [
++          ['OS=="linux" or OS=="android"', {
++            'target_conditions': [
++              ['_toolset=="target"', {
++                'cflags': [
++                  '<@(debug_extra_cflags)',
++                ],
++              }],
++            ],
++          }],
++          # Disabled on iOS because it was causing a crash on startup.
++          # TODO(michelea): investigate, create a reduced test and possibly
++          # submit a radar.
++          ['release_valgrind_build==0 and OS!="ios"', {
++            'xcode_settings': {
++              'OTHER_CFLAGS': [
++                '-fstack-protector-all',  # Implies -fstack-protector
++              ],
++            },
++          }],
++        ],
++      },
++      'Release_Base': {
++        'abstract': 1,
++        'defines': [
++          'NDEBUG',
++        ],
++        'xcode_settings': {
++          'DEAD_CODE_STRIPPING': 'YES',  # -Wl,-dead_strip
++          'GCC_OPTIMIZATION_LEVEL': '<(mac_release_optimization)',
++          'OTHER_CFLAGS': [ '<@(release_extra_cflags)', ],
++        },
++        'msvs_settings': {
++          'VCCLCompilerTool': {
++            'RuntimeLibrary': '<(win_release_RuntimeLibrary)',
++            'conditions': [
++              # In official builds, each target will self-select
++              # an optimization level.
++              ['buildtype!="Official"', {
++                  'Optimization': '<(win_release_Optimization)',
++                },
++              ],
++              # According to MSVS, InlineFunctionExpansion=0 means
++              # "default inlining", not "/Ob0".
++              # Thus, we have to handle InlineFunctionExpansion==0 separately.
++              ['win_release_InlineFunctionExpansion==0', {
++                'AdditionalOptions': ['/Ob0'],
++              }],
++              ['win_release_InlineFunctionExpansion!=""', {
++                'InlineFunctionExpansion':
++                  '<(win_release_InlineFunctionExpansion)',
++              }],
++
++              # if win_release_OmitFramePointers is blank, leave as default
++              ['win_release_OmitFramePointers==1', {
++                'OmitFramePointers': 'true',
++              }],
++              ['win_release_OmitFramePointers==0', {
++                'OmitFramePointers': 'false',
++                # The above is not sufficient (http://crbug.com/106711): it
++                # simply eliminates an explicit "/Oy", but both /O2 and /Ox
++                # perform FPO regardless, so we must explicitly disable.
++                # We still want the false setting above to avoid having
++                # "/Oy /Oy-" and warnings about overriding.
++                'AdditionalOptions': ['/Oy-'],
++              }],
++            ],
++            'AdditionalOptions': [ '<@(win_release_extra_cflags)', ],
++          },
++          'VCLinkerTool': {
++            # LinkIncremental is a tri-state boolean, where 0 means default
++            # (i.e., inherit from parent solution), 1 means false, and
++            # 2 means true.
++            'LinkIncremental': '1',
++            # This corresponds to the /PROFILE flag which ensures the PDB
++            # file contains FIXUP information (growing the PDB file by about
++            # 5%) but does not otherwise alter the output binary. This
++            # information is used by the Syzygy optimization tool when
++            # decomposing the release image.
++            'Profile': 'true',
++          },
++        },
++        'conditions': [
++          ['msvs_use_common_release', {
++            'includes': ['release.gypi'],
++          }],
++          ['release_valgrind_build==0', {
++            'defines': [
++              'NVALGRIND',
++              'DYNAMIC_ANNOTATIONS_ENABLED=0',
++            ],
++          }, {
++            'defines': [
++              'DYNAMIC_ANNOTATIONS_ENABLED=1',
++              'WTF_USE_DYNAMIC_ANNOTATIONS=1',
++            ],
++          }],
++          ['win_use_allocator_shim==0', {
++            'defines': ['NO_TCMALLOC'],
++          }],
++          ['OS=="linux"', {
++            'target_conditions': [
++              ['_toolset=="target"', {
++                'cflags': [
++                  '<@(release_extra_cflags)',
++                ],
++              }],
++            ],
++          }],
++        ],
++      },
++      #
++      # Concrete configurations
++      #
++      'Debug': {
++        'inherit_from': ['Common_Base', 'x86_Base', 'Debug_Base'],
++      },
++      'Release': {
++        'inherit_from': ['Common_Base', 'x86_Base', 'Release_Base'],
++      },
++      'conditions': [
++        [ 'OS=="win"', {
++          # TODO(bradnelson): add a gyp mechanism to make this more graceful.
++          'Debug_x64': {
++            'inherit_from': ['Common_Base', 'x64_Base', 'Debug_Base'],
++          },
++          'Release_x64': {
++            'inherit_from': ['Common_Base', 'x64_Base', 'Release_Base'],
++          },
++        }],
++      ],
++    },
++  },
++  'conditions': [
++    ['os_posix==1 and OS!="mac" and OS!="ios"', {
++      'target_defaults': {
++        # Enable -Werror by default, but put it in a variable so it can
++        # be disabled in ~/.gyp/include.gypi on the valgrind builders.
++        'variables': {
++          'werror%': '-Werror',
++          'libraries_for_target%': '',
++        },
++        'defines': [
++          '_FILE_OFFSET_BITS=64',
++        ],
++        'cflags': [
++          '<(werror)',  # See note above about the werror variable.
++          '-pthread',
++          '-fno-exceptions',
++          '-fno-strict-aliasing',  # See http://crbug.com/32204
++          '-Wall',
++          # TODO(evan): turn this back on once all the builds work.
++          # '-Wextra',
++          # Don't warn about unused function params.  We use those everywhere.
++          '-Wno-unused-parameter',
++          # Don't warn about the "struct foo f = {0};" initialization pattern.
++          '-Wno-missing-field-initializers',
++          # Don't export any symbols (for example, to plugins we dlopen()).
++          # Note: this is *required* to make some plugins work.
++          '-fvisibility=hidden',
++          '-pipe',
++        ],
++        'cflags_cc': [
++          '-fno-rtti',
++          '-fno-threadsafe-statics',
++          # Make inline functions have hidden visiblity by default.
++          # Surprisingly, not covered by -fvisibility=hidden.
++          '-fvisibility-inlines-hidden',
++          # GCC turns on -Wsign-compare for C++ under -Wall, but clang doesn't,
++          # so we specify it explicitly.
++          # TODO(fischman): remove this if http://llvm.org/PR10448 obsoletes it.
++          # http://code.google.com/p/chromium/issues/detail?id=90453
++          '-Wsign-compare',
++        ],
++        'ldflags': [
++          '-pthread', '-Wl,-z,noexecstack',
++        ],
++        'libraries' : [
++          '<(libraries_for_target)',
++        ],
++        'configurations': {
++          'Debug_Base': {
++            'variables': {
++              'debug_optimize%': '0',
++            },
++            'defines': [
++              '_DEBUG',
++            ],
++            'cflags': [
++              '-O>(debug_optimize)',
++              '-g',
++            ],
++            'conditions' : [
++              ['OS=="android" and android_full_debug==0', {
++                # Some configurations are copied from Release_Base to reduce
++                # the binary size.
++                'variables': {
++                  'debug_optimize%': 's',
++                },
++                'cflags': [
++                  '-fomit-frame-pointer',
++                  '-fdata-sections',
++                  '-ffunction-sections',
++                ],
++                'ldflags': [
++                  '-Wl,-O1',
++                  '-Wl,--as-needed',
++                  '-Wl,--gc-sections',
++                ],
++              }],
++            ],
++          },
++          'Release_Base': {
++            'variables': {
++              'release_optimize%': '2',
++              # Binaries become big and gold is unable to perform GC
++              # and remove unused sections for some of test targets
++              # on 32 bit platform.
++              # (This is currently observed only in chromeos valgrind bots)
++              # The following flag is to disable --gc-sections linker
++              # option for these bots.
++              'no_gc_sections%': 0,
++
++              # TODO(bradnelson): reexamine how this is done if we change the
++              # expansion of configurations
++              'release_valgrind_build%': 0,
++            },
++            'cflags': [
++              '-O<(release_optimize)',
++              # Don't emit the GCC version ident directives, they just end up
++              # in the .comment section taking up binary size.
++              '-fno-ident',
++              # Put data and code in their own sections, so that unused symbols
++              # can be removed at link time with --gc-sections.
++              '-fdata-sections',
++              '-ffunction-sections',
++            ],
++            'ldflags': [
++              # Specifically tell the linker to perform optimizations.
++              # See http://lwn.net/Articles/192624/ .
++              '-Wl,-O1',
++              '-Wl,--as-needed',
++            ],
++            'conditions' : [
++              ['no_gc_sections==0', {
++                'ldflags': [
++                  '-Wl,--gc-sections',
++                ],
++              }],
++              ['OS=="android"', {
++                'variables': {
++                  'release_optimize%': 's',
++                },
++                'cflags': [
++                  '-fomit-frame-pointer',
++                ],
++              }],
++              ['clang==1', {
++                'cflags!': [
++                  '-fno-ident',
++                ],
++              }],
++              ['profiling==1', {
++                'cflags': [
++                  '-fno-omit-frame-pointer',
++                  '-g',
++                ],
++              }],
++            ],
++          },
++        },
++        'variants': {
++          'coverage': {
++            'cflags': ['-fprofile-arcs', '-ftest-coverage'],
++            'ldflags': ['-fprofile-arcs'],
++          },
++          'profile': {
++            'cflags': ['-pg', '-g'],
++            'ldflags': ['-pg'],
++          },
++          'symbols': {
++            'cflags': ['-g'],
++          },
++        },
++        'conditions': [
++          ['target_arch=="ia32"', {
++            'target_conditions': [
++              ['_toolset=="target"', {
++                'asflags': [
++                  # Needed so that libs with .s files (e.g. libicudata.a)
++                  # are compatible with the general 32-bit-ness.
++                  '-32',
++                ],
++                # All floating-point computations on x87 happens in 80-bit
++                # precision.  Because the C and C++ language standards allow
++                # the compiler to keep the floating-point values in higher
++                # precision than what's specified in the source and doing so
++                # is more efficient than constantly rounding up to 64-bit or
++                # 32-bit precision as specified in the source, the compiler,
++                # especially in the optimized mode, tries very hard to keep
++                # values in x87 floating-point stack (in 80-bit precision)
++                # as long as possible. This has important side effects, that
++                # the real value used in computation may change depending on
++                # how the compiler did the optimization - that is, the value
++                # kept in 80-bit is different than the value rounded down to
++                # 64-bit or 32-bit. There are possible compiler options to
++                # make this behavior consistent (e.g. -ffloat-store would keep
++                # all floating-values in the memory, thus force them to be
++                # rounded to its original precision) but they have significant
++                # runtime performance penalty.
++                #
++                # -mfpmath=sse -msse2 makes the compiler use SSE instructions
++                # which keep floating-point values in SSE registers in its
++                # native precision (32-bit for single precision, and 64-bit
++                # for double precision values). This means the floating-point
++                # value used during computation does not change depending on
++                # how the compiler optimized the code, since the value is
++                # always kept in its specified precision.
++                'conditions': [
++                  ['branding=="Chromium" and disable_sse2==0', {
++                    'cflags': [
++                      '-march=pentium4',
++                      '-msse2',
++                      '-mfpmath=sse',
++                    ],
++                  }],
++                  # ChromeOS targets Pinetrail, which is sse3, but most of the
++                  # benefit comes from sse2 so this setting allows ChromeOS
++                  # to build on other CPUs.  In the future -march=atom would
++                  # help but requires a newer compiler.
++                  ['chromeos==1 and disable_sse2==0', {
++                    'cflags': [
++                      '-msse2',
++                    ],
++                  }],
++                  # Install packages have started cropping up with
++                  # different headers between the 32-bit and 64-bit
++                  # versions, so we have to shadow those differences off
++                  # and make sure a 32-bit-on-64-bit build picks up the
++                  # right files.
++                  # For android build, use NDK headers instead of host headers
++                  ['host_arch!="ia32" and OS!="android"', {
++                    'include_dirs+': [
++                      '/usr/include32',
++                    ],
++                  }],
++                ],
++               'target_conditions': [
++                 ['_toolset=="target" and OS!="android"', {
++                    # -mmmx allows mmintrin.h to be used for mmx intrinsics.
++                    # video playback is mmx and sse2 optimized.
++                    'cflags': [
++                      '-m32',
++                      '-mmmx',
++                    ],
++                    'ldflags': [
++                      '-m32',
++                    ],
++                    'cflags_mozilla': [
++                      '-m32',
++                      '-mmmx',
++                    ],
++                  }],
++                ],
++              }],
++            ],
++          }],
++          ['target_arch=="arm"', {
++            'target_conditions': [
++              ['_toolset=="target"', {
++                'cflags_cc': [
++                  # The codesourcery arm-2009q3 toolchain warns at that the ABI
++                  # has changed whenever it encounters a varargs function. This
++                  # silences those warnings, as they are not helpful and
++                  # clutter legitimate warnings.
++                  '-Wno-abi',
++                ],
++                'conditions': [
++                  ['arm_thumb==1', {
++                    'cflags': [
++                    '-mthumb',
++                    ]
++                  }],
++                  ['armv7==1', {
++                    'cflags': [
++                      '-march=armv7-a',
++                      '-mtune=cortex-a8',
++                      '-mfloat-abi=<(arm_float_abi)',
++                    ],
++                    'conditions': [
++                      ['arm_neon==1', {
++                        'cflags': [ '-mfpu=neon', ],
++                      }, {
++                        'cflags': [ '-mfpu=<(arm_fpu)', ],
++                      }],
++                    ],
++                  }],
++                  ['OS=="android"', {
++                    # Most of the following flags are derived from what Android
++                    # uses by default when building for arm, reference for which
++                    # can be found in the following file in the Android NDK:
++                    # toolchains/arm-linux-androideabi-4.4.3/setup.mk
++                    'cflags': [
++                      # The tree-sra optimization (scalar replacement for
++                      # aggregates enabling subsequent optimizations) leads to
++                      # invalid code generation when using the Android NDK's
++                      # compiler (r5-r7). This can be verified using
++                      # TestWebKitAPI's WTF.Checked_int8_t test.
++                      '-fno-tree-sra',
++                      '-fuse-ld=gold',
++                      '-Wno-psabi',
++                    ],
++                    # Android now supports .relro sections properly.
++                    # NOTE: While these flags enable the generation of .relro
++                    # sections, the generated libraries can still be loaded on
++                    # older Android platform versions.
++                    'ldflags': [
++                        '-Wl,-z,relro',
++                        '-Wl,-z,now',
++                        '-fuse-ld=gold',
++                    ],
++                    'conditions': [
++                      ['arm_thumb == 1', {
++                        # Android toolchain doesn't support -mimplicit-it=thumb
++                        'cflags!': [ '-Wa,-mimplicit-it=thumb', ],
++                        'cflags': [ '-mthumb-interwork', ],
++                      }],
++                      ['armv7==0', {
++                        # Flags suitable for Android emulator
++                        'cflags': [
++                          '-march=armv5te',
++                          '-mtune=xscale',
++                          '-msoft-float',
++                        ],
++                        'defines': [
++                          '__ARM_ARCH_5__',
++                          '__ARM_ARCH_5T__',
++                          '__ARM_ARCH_5E__',
++                          '__ARM_ARCH_5TE__',
++                        ],
++                      }],
++                      ['clang==1', {
++                        'cflags!': [
++                          # Clang does not support the following options.
++                          '-mthumb-interwork',
++                          '-finline-limit=64',
++                          '-fno-tree-sra',
++                          '-fuse-ld=gold',
++                          '-Wno-psabi',
++                        ],
++                      }],
++                    ],
++                  }],
++                ],
++              }],
++            ],
++          }],
++          ['linux_fpic==1', {
++            'cflags': [
++              '-fPIC',
++            ],
++            'ldflags': [
++              '-fPIC',
++            ],
++          }],
++          ['sysroot!=""', {
++            'target_conditions': [
++              ['_toolset=="target"', {
++                'cflags': [
++                  '--sysroot=<(sysroot)',
++                ],
++                'ldflags': [
++                  '--sysroot=<(sysroot)',
++                ],
++              }]]
++          }],
++          ['clang==1', {
++            'cflags': [
++              '-Wheader-hygiene',
++              # Clang spots more unused functions.
++              '-Wno-unused-function',
++              # Don't die on dtoa code that uses a char as an array index.
++              '-Wno-char-subscripts',
++              # Especially needed for gtest macros using enum values from Mac
++              # system headers.
++              # TODO(pkasting): In C++11 this is legal, so this should be
++              # removed when we change to that.  (This is also why we don't
++              # bother fixing all these cases today.)
++              '-Wno-unnamed-type-template-args',
++              # This (rightyfully) complains about 'override', which we use
++              # heavily.
++              '-Wno-c++11-extensions',
++
++              # Warns on switches on enums that cover all enum values but
++              # also contain a default: branch. Chrome is full of that.
++              '-Wno-covered-switch-default',
++
++              # TODO(thakis): Remove this.
++              '-Wno-implicit-conversion-floating-point-to-bool',
++            ],
++            'cflags!': [
++              # Clang doesn't seem to know know this flag.
++              '-mfpmath=sse',
++            ],
++          }],
++          ['clang==1 and clang_use_chrome_plugins==1', {
++            'cflags': [
++              '<@(clang_chrome_plugins_flags)',
++            ],
++          }],
++          ['clang==1 and clang_load!=""', {
++            'cflags': [
++              '-Xclang', '-load', '-Xclang', '<(clang_load)',
++            ],
++          }],
++          ['clang==1 and clang_add_plugin!=""', {
++            'cflags': [
++              '-Xclang', '-add-plugin', '-Xclang', '<(clang_add_plugin)',
++            ],
++          }],
++          ['clang==1 and "<(GENERATOR)"=="ninja"', {
++            'cflags': [
++              # See http://crbug.com/110262
++              '-fcolor-diagnostics',
++            ],
++          }],
++          ['asan==1', {
++            'target_conditions': [
++              ['_toolset=="target"', {
++                'cflags': [
++                  '-faddress-sanitizer',
++                  '-fno-omit-frame-pointer',
++                ],
++                'ldflags': [
++                  '-faddress-sanitizer',
++                ],
++                'defines': [
++                  'ADDRESS_SANITIZER',
++                ],
++              }],
++            ],
++          }],
++          ['tsan==1', {
++            'target_conditions': [
++              ['_toolset=="target"', {
++                'cflags': [
++                  '-fthread-sanitizer',
++                  '-fno-omit-frame-pointer',
++                  '-fPIE',
++                ],
++                'ldflags': [
++                  '-fthread-sanitizer',
++                ],
++                'defines': [
++                  'THREAD_SANITIZER',
++                  'DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL=1',
++                ],
++                'target_conditions': [
++                  ['_type=="executable"', {
++                    'ldflags': [
++                      '-pie',
++                    ],
++                  }],
++                ],
++              }],
++            ],
++          }],
++          ['order_profiling!=0 and (chromeos==1 or OS=="linux")', {
++            'target_conditions' : [
++              ['_toolset=="target"', {
++                'cflags': [
++                  '-finstrument-functions',
++                  # Allow mmx intrinsics to inline, so that the
++                  # compiler can expand the intrinsics.
++                  '-finstrument-functions-exclude-file-list=mmintrin.h',
++                ],
++              }],
++            ],
++          }],
++          ['linux_breakpad==1', {
++            'cflags': [ '-g' ],
++            'defines': ['USE_LINUX_BREAKPAD'],
++          }],
++          ['linux_use_heapchecker==1', {
++            'variables': {'linux_use_tcmalloc%': 1},
++            'defines': ['USE_HEAPCHECKER'],
++          }],
++          ['linux_use_tcmalloc==0', {
++            'defines': ['NO_TCMALLOC'],
++          }],
++          ['linux_keep_shadow_stacks==1', {
++            'defines': ['KEEP_SHADOW_STACKS'],
++            'cflags': [
++              '-finstrument-functions',
++              # Allow mmx intrinsics to inline, so that the compiler can expand
++              # the intrinsics.
++              '-finstrument-functions-exclude-file-list=mmintrin.h',
++            ],
++          }],
++          ['linux_use_gold_flags==1', {
++            'ldflags': [
++              # Experimentation found that using four linking threads
++              # saved ~20% of link time.
++              # https://groups.google.com/a/chromium.org/group/chromium-dev/browse_thread/thread/281527606915bb36
++              '-Wl,--threads',
++              '-Wl,--thread-count=4',
++            ],
++            'conditions': [
++              ['release_valgrind_build==0', {
++                'target_conditions': [
++                  ['_toolset=="target"', {
++                    'ldflags': [
++                      # There seems to be a conflict of --icf and -pie
++                      # in gold which can generate crashy binaries. As
++                      # a security measure, -pie takes precendence for
++                      # now.
++                      #'-Wl,--icf=safe',
++                      '-Wl,--icf=none',
++                    ],
++                  }],
++                ],
++              }],
++            ],
++          }],
++          ['linux_use_gold_binary==1', {
++            'variables': {
++              'conditions': [
++                ['inside_chromium_build==1', {
++                  # We pass the path to gold to the compiler.  gyp leaves
++                  # unspecified what the cwd is when running the compiler,
++                  # so the normal gyp path-munging fails us.  This hack
++                  # gets the right path.
++                  'gold_path': '<(PRODUCT_DIR)/../../third_party/gold',
++                }, {
++                  'gold_path': '<(PRODUCT_DIR)/../../Source/WebKit/chromium/third_party/gold',
++                }]
++              ]
++            },
++            'ldflags': [
++              # Put our gold binary in the search path for the linker.
++              '-B<(gold_path)',
++            ],
++          }],
++        ],
++      },
++    }],
++    # FreeBSD-specific options; note that most FreeBSD options are set above,
++    # with Linux.
++    ['OS=="freebsd"', {
++      'target_defaults': {
++        'ldflags': [
++          '-Wl,--no-keep-memory',
++        ],
++      },
++    }],
++    # Android-specific options; note that most are set above with Linux.
++    ['OS=="android"', {
++      'variables': {
++        # This is the id for the archived chrome symbols. Each build that
++        # archives symbols is assigned an id which is then added to GYP_DEFINES.
++        # This is written to the device log on crashes just prior to dropping a
++        # tombstone. Tools can determine the location of the archived symbols
++        # from the id.
++        'chrome_symbols_id%': '',
++        'conditions': [
++          # Use shared stlport library when system one used.
++          # Figure this out early since it needs symbols from libgcc.a, so it
++          # has to be before that in the set of libraries.
++          ['use_system_stlport==1', {
++            'android_stlport_library': 'stlport',
++          }, {
++            'android_stlport_library': 'stlport_static',
++          }],
++        ],
++
++        # Placing this variable here prevents from forking libvpx, used
++        # by remoting.  Remoting is off, so it needn't built,
++        # so forking it's deps seems like overkill.
++        # But this variable need defined to properly run gyp.
++        # A proper solution is to have an OS==android conditional
++        # in third_party/libvpx/libvpx.gyp to define it.
++        'libvpx_path': 'lib/linux/arm',
++      },
++      'target_defaults': {
++        'variables': {
++          'release_extra_cflags%': '',
++        },
++
++        'target_conditions': [
++          # Settings for building device targets using Android's toolchain.
++          # These are based on the setup.mk file from the Android NDK.
++          #
++          # The NDK Android executable link step looks as follows:
++          #  $LDFLAGS
++          #  $(TARGET_CRTBEGIN_DYNAMIC_O)  <-- crtbegin.o
++          #  $(PRIVATE_OBJECTS)            <-- The .o that we built
++          #  $(PRIVATE_STATIC_LIBRARIES)   <-- The .a that we built
++          #  $(TARGET_LIBGCC)              <-- libgcc.a
++          #  $(PRIVATE_SHARED_LIBRARIES)   <-- The .so that we built
++          #  $(PRIVATE_LDLIBS)             <-- System .so
++          #  $(TARGET_CRTEND_O)            <-- crtend.o
++          #
++          # For now the above are approximated for executables by adding
++          # crtbegin.o to the end of the ldflags and 'crtend.o' to the end
++          # of 'libraries'.
++          #
++          # The NDK Android shared library link step looks as follows:
++          #  $LDFLAGS
++          #  $(PRIVATE_OBJECTS)            <-- The .o that we built
++          #  -l,--whole-archive
++          #  $(PRIVATE_WHOLE_STATIC_LIBRARIES)
++          #  -l,--no-whole-archive
++          #  $(PRIVATE_STATIC_LIBRARIES)   <-- The .a that we built
++          #  $(TARGET_LIBGCC)              <-- libgcc.a
++          #  $(PRIVATE_SHARED_LIBRARIES)   <-- The .so that we built
++          #  $(PRIVATE_LDLIBS)             <-- System .so
++          #
++          # For now, assume that whole static libraries are not needed.
++          #
++          # For both executables and shared libraries, add the proper
++          # libgcc.a to the start of libraries which puts it in the
++          # proper spot after .o and .a files get linked in.
++          #
++          # TODO: The proper thing to do longer-tem would be proper gyp
++          # support for a custom link command line.
++          ['_toolset=="target"', {
++           'conditions': [
++           ['build_with_mozilla==0', {
++            'cflags!': [
++              '-pthread',  # Not supported by Android toolchain.
++            ],
++            'cflags': [
++              '-ffunction-sections',
++              '-funwind-tables',
++              '-g',
++              '-fstack-protector',
++              '-fno-short-enums',
++              '-finline-limit=64',
++              '-Wa,--noexecstack',
++              '<@(release_extra_cflags)',
++            ],
++            'ldflags!': [
++              '-pthread',  # Not supported by Android toolchain.
++            ],
++            'ldflags': [
++              '-nostdlib',
++              '-Wl,--no-undefined',
++              # Don't export symbols from statically linked libraries.
++              '-Wl,--exclude-libs=ALL',
++            ],
++            'libraries': [
++              '-l<(android_stlport_library)',
++              # Manually link the libgcc.a that the cross compiler uses.
++              '<!(<(android_toolchain)/*-gcc -print-libgcc-file-name)',
++              '-lc',
++              '-ldl',
++              '-lstdc++',
++              '-lm',
++            ],
++            'conditions': [
++              ['android_upstream_bringup==1', {
++                'defines': ['ANDROID_UPSTREAM_BRINGUP=1',],
++              }],
++              ['clang==1', {
++                'cflags': [
++                  # Work around incompatibilities between bionic and clang
++                  # headers.
++                  '-D__compiler_offsetof=__builtin_offsetof',
++                  '-Dnan=__builtin_nan',
++                ],
++                'conditions': [
++                  ['target_arch=="arm"', {
++                    'cflags': [
++                      '-target arm-linux-androideabi',
++                      '-mllvm -arm-enable-ehabi',
++                    ],
++                    'ldflags': [
++                      '-target arm-linux-androideabi',
++                    ],
++                  }],
++                  ['target_arch=="ia32"', {
++                    'cflags': [
++                      '-target x86-linux-androideabi',
++                    ],
++                    'ldflags': [
++                      '-target x86-linux-androideabi',
++                    ],
++                  }],
++                ],
++              }],
++              ['android_build_type==0', {
++                'defines': [
++                  # The NDK has these things, but doesn't define the constants
++                  # to say that it does. Define them here instead.
++                  'HAVE_SYS_UIO_H',
++                ],
++                'cflags': [
++                  '--sysroot=<(android_ndk_sysroot)',
++                ],
++                'ldflags': [
++                  '--sysroot=<(android_ndk_sysroot)',
++                ],
++              }],
++              ['android_build_type==1', {
++                'include_dirs': [
++                  # OpenAL headers from the Android tree.
++                  '<(android_src)/frameworks/wilhelm/include',
++                ],
++                'cflags': [
++                  # Chromium builds its own (non-third-party) code with
++                  # -Werror to make all warnings into errors. However, Android
++                  # enables warnings that Chromium doesn't, so some of these
++                  # extra warnings trip and break things.
++                  # For now, we leave these warnings enabled but prevent them
++                  # from being treated as errors.
++                  #
++                  # Things that are part of -Wextra:
++                  '-Wno-error=extra', # Enabled by -Wextra, but no specific flag
++                  '-Wno-error=ignored-qualifiers',
++                  '-Wno-error=type-limits',
++                  # Other things unrelated to -Wextra:
++                  '-Wno-error=non-virtual-dtor',
++                  '-Wno-error=sign-promo',
++                ],
++                'cflags_cc': [
++                  # Disabling c++0x-compat should be handled in WebKit, but
++                  # this currently doesn't work because gcc_version is not set
++                  # correctly when building with the Android build system.
++                  # TODO(torne): Fix this in WebKit.
++                  '-Wno-error=c++0x-compat',
++                ],
++              }],
++              ['android_build_type==1 and chromium_code==0', {
++                'cflags': [
++                  # There is a class of warning which:
++                  #  1) Android always enables and also treats as errors
++                  #  2) Chromium ignores in third party code
++                  # For now, I am leaving these warnings enabled but preventing
++                  # them from being treated as errors here.
++                  '-Wno-error=address',
++                  '-Wno-error=format-security',
++                  '-Wno-error=non-virtual-dtor',
++                  '-Wno-error=return-type',
++                  '-Wno-error=sequence-point',
++                ],
++              }],
++              ['target_arch == "arm"', {
++                'ldflags': [
++                  # Enable identical code folding to reduce size.
++                  '-Wl,--icf=safe',
++                ],
++              }],
++              # NOTE: The stlport header include paths below are specified in
++              # cflags rather than include_dirs because they need to come
++              # after include_dirs. Think of them like system headers, but
++              # don't use '-isystem' because the arm-linux-androideabi-4.4.3
++              # toolchain (circa Gingerbread) will exhibit strange errors.
++              # The include ordering here is important; change with caution.
++              ['use_system_stlport==1', {
++                'cflags': [
++                  # For libstdc++/include, which is used by stlport.
++                  '-I<(android_src)/bionic',
++                  '-I<(android_src)/external/stlport/stlport',
++                ],
++              }, { # else: use_system_stlport!=1
++                'cflags': [
++                  '-I<(android_ndk_root)/sources/cxx-stl/stlport/stlport',
++                ],
++                'conditions': [
++                  ['target_arch=="arm" and armv7==1', {
++                    'ldflags': [
++                      '-L<(android_ndk_root)/sources/cxx-stl/stlport/libs/armeabi-v7a',
++                    ],
++                  }],
++                  ['target_arch=="arm" and armv7==0', {
++                    'ldflags': [
++                      '-L<(android_ndk_root)/sources/cxx-stl/stlport/libs/armeabi',
++                    ],
++                  }],
++                  ['target_arch=="ia32"', {
++                    'ldflags': [
++                      '-L<(android_ndk_root)/sources/cxx-stl/stlport/libs/x86',
++                    ],
++                  }],
++                ],
++              }],
++              ['target_arch=="ia32"', {
++                # The x86 toolchain currently has problems with stack-protector.
++                'cflags!': [
++                  '-fstack-protector',
++                ],
++                'cflags': [
++                  '-fno-stack-protector',
++                ],
++              }],
++            ],
++            'target_conditions': [
++              ['_type=="executable"', {
++                'ldflags': [
++                  '-Bdynamic',
++                  '-Wl,-dynamic-linker,/system/bin/linker',
++                  '-Wl,--gc-sections',
++                  '-Wl,-z,nocopyreloc',
++                  # crtbegin_dynamic.o should be the last item in ldflags.
++                  '<(android_ndk_lib)/crtbegin_dynamic.o',
++                ],
++                'libraries': [
++                  # crtend_android.o needs to be the last item in libraries.
++                  # Do not add any libraries after this!
++                  '<(android_ndk_lib)/crtend_android.o',
++                ],
++              }],
++              ['_type=="shared_library" or _type=="loadable_module"', {
++                'ldflags': [
++                  '-Wl,-shared,-Bsymbolic',
++                  # crtbegin_so.o should be the last item in ldflags.
++                  '<(android_ndk_lib)/crtbegin_so.o',
++                ],
++                'libraries': [
++                  # crtend_so.o needs to be the last item in libraries.
++                  # Do not add any libraries after this!
++                  '<(android_ndk_lib)/crtend_so.o',
++                ],
++              }],
++            ],
++
++           }], # build_with_mozilla== 0
++
++            ],
++            'defines': [
++              'ANDROID',
++              '__GNU_SOURCE=1',  # Necessary for clone()
++              'USE_STLPORT=1',
++              '_STLP_USE_PTR_SPECIALIZATIONS=1',
++              'CHROME_SYMBOLS_ID="<(chrome_symbols_id)"',
++            ],
++           }],
++          # Settings for building host targets using the system toolchain.
++          ['_toolset=="host"', {
++            'cflags!': [
++              # Due to issues in Clang build system, using ASan on 32-bit
++              # binaries on x86_64 host is problematic.
++              # TODO(eugenis): re-enable.
++              '-faddress-sanitizer',
++            ],
++            'ldflags!': [
++              '-faddress-sanitizer',
++              '-Wl,-z,noexecstack',
++              '-Wl,--gc-sections',
++              '-Wl,-O1',
++              '-Wl,--as-needed',
++            ],
++            'sources/': [
++              ['exclude', '_android(_unittest)?\\.cc$'],
++              ['exclude', '(^|/)android/']
++            ],
++          }],
++        ],
++      },
++    }],
++    ['OS=="solaris"', {
++      'cflags!': ['-fvisibility=hidden'],
++      'cflags_cc!': ['-fvisibility-inlines-hidden'],
++    }],
++    ['OS=="mac" or OS=="ios"', {
++      'target_defaults': {
++        'mac_bundle': 0,
++        'xcode_settings': {
++          'ALWAYS_SEARCH_USER_PATHS': 'NO',
++          'GCC_C_LANGUAGE_STANDARD': 'c99',         # -std=c99
++          'GCC_CW_ASM_SYNTAX': 'NO',                # No -fasm-blocks
++          'GCC_ENABLE_CPP_EXCEPTIONS': 'NO',        # -fno-exceptions
++          'GCC_ENABLE_CPP_RTTI': 'NO',              # -fno-rtti
++          'GCC_ENABLE_PASCAL_STRINGS': 'NO',        # No -mpascal-strings
++          # GCC_INLINES_ARE_PRIVATE_EXTERN maps to -fvisibility-inlines-hidden
++          'GCC_INLINES_ARE_PRIVATE_EXTERN': 'YES',
++          'GCC_OBJC_CALL_CXX_CDTORS': 'YES',        # -fobjc-call-cxx-cdtors
++          'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES',      # -fvisibility=hidden
++          'GCC_THREADSAFE_STATICS': 'NO',           # -fno-threadsafe-statics
++          'GCC_TREAT_WARNINGS_AS_ERRORS': 'YES',    # -Werror
++          'GCC_VERSION': '4.2',
++          'GCC_WARN_ABOUT_MISSING_NEWLINE': 'YES',  # -Wnewline-eof
++          'USE_HEADERMAP': 'NO',
++          'WARNING_CFLAGS': [
++            '-Wall',
++            '-Wendif-labels',
++            '-Wextra',
++            # Don't warn about unused function parameters.
++            '-Wno-unused-parameter',
++            # Don't warn about the "struct foo f = {0};" initialization
++            # pattern.
++            '-Wno-missing-field-initializers',
++          ],
++          'conditions': [
++            ['chromium_mac_pch', {'GCC_PRECOMPILE_PREFIX_HEADER': 'YES'},
++                                 {'GCC_PRECOMPILE_PREFIX_HEADER': 'NO'}
++            ],
++          ],
++        },
++        'target_conditions': [
++          ['_type!="static_library"', {
++            'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-search_paths_first']},
++          }],
++          ['_mac_bundle', {
++            'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-ObjC']},
++          }],
++        ],  # target_conditions
++      },  # target_defaults
++    }],  # OS=="mac" or OS=="ios"
++    ['OS=="mac"', {
++      'target_defaults': {
++        'variables': {
++          # These should end with %, but there seems to be a bug with % in
++          # variables that are intended to be set to different values in
++          # different targets, like these.
++          'mac_pie': 1,        # Most executables can be position-independent.
++          'mac_real_dsym': 0,  # Fake .dSYMs are fine in most cases.
++          # Strip debugging symbols from the target.
++          'mac_strip': '<(mac_strip_release)',
++        },
++        'xcode_settings': {
++          'GCC_DYNAMIC_NO_PIC': 'NO',               # No -mdynamic-no-pic
++                                                    # (Equivalent to -fPIC)
++          # MACOSX_DEPLOYMENT_TARGET maps to -mmacosx-version-min
++          'MACOSX_DEPLOYMENT_TARGET': '<(mac_deployment_target)',
++          # Keep pch files below xcodebuild/.
++          'SHARED_PRECOMPS_DIR': '$(CONFIGURATION_BUILD_DIR)/SharedPrecompiledHeaders',
++          'OTHER_CFLAGS': [
++            '-fno-strict-aliasing',  # See http://crbug.com/32204
++          ],
++          'conditions': [
++            ['clang==1', {
++              'CC': '$(SOURCE_ROOT)/<(clang_dir)/clang',
++              'LDPLUSPLUS': '$(SOURCE_ROOT)/<(clang_dir)/clang++',
++
++              # Don't use -Wc++0x-extensions, which Xcode 4 enables by default
++              # when buliding with clang. This warning is triggered when the
++              # override keyword is used via the OVERRIDE macro from
++              # base/compiler_specific.h.
++              'CLANG_WARN_CXX0X_EXTENSIONS': 'NO',
++
++              'GCC_VERSION': 'com.apple.compilers.llvm.clang.1_0',
++              'WARNING_CFLAGS': [
++                '-Wheader-hygiene',
++                # Don't die on dtoa code that uses a char as an array index.
++                # This is required solely for base/third_party/dmg_fp/dtoa.cc.
++                '-Wno-char-subscripts',
++                # Clang spots more unused functions.
++                '-Wno-unused-function',
++                # See comments on this flag higher up in this file.
++                '-Wno-unnamed-type-template-args',
++                # This (rightyfully) complains about 'override', which we use
++                # heavily.
++                '-Wno-c++11-extensions',
++
++                # Warns on switches on enums that cover all enum values but
++                # also contain a default: branch. Chrome is full of that.
++                '-Wno-covered-switch-default',
++
++                # TODO(thakis): Remove this.
++                '-Wno-implicit-conversion-floating-point-to-bool',
++              ],
++            }],
++            ['clang==1 and clang_use_chrome_plugins==1', {
++              'OTHER_CFLAGS': [
++                '<@(clang_chrome_plugins_flags)',
++              ],
++            }],
++            ['clang==1 and clang_load!=""', {
++              'OTHER_CFLAGS': [
++                '-Xclang', '-load', '-Xclang', '<(clang_load)',
++              ],
++            }],
++            ['clang==1 and clang_add_plugin!=""', {
++              'OTHER_CFLAGS': [
++                '-Xclang', '-add-plugin', '-Xclang', '<(clang_add_plugin)',
++              ],
++            }],
++            ['clang==1 and "<(GENERATOR)"=="ninja"', {
++              'OTHER_CFLAGS': [
++                # See http://crbug.com/110262
++                '-fcolor-diagnostics',
++              ],
++            }],
++          ],
++        },
++        'conditions': [
++          ['clang==1', {
++            'variables': {
++              'clang_dir': '../third_party/llvm-build/Release+Asserts/bin',
++            },
++          }],
++          ['asan==1', {
++            'xcode_settings': {
++              'OTHER_CFLAGS': [
++                '-faddress-sanitizer',
++              ],
++            },
++            'defines': [
++              'ADDRESS_SANITIZER',
++            ],
++          }],
++        ],
++        'target_conditions': [
++          ['_type!="static_library"', {
++            'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-search_paths_first']},
++            'conditions': [
++              ['asan==1', {
++                'xcode_settings': {
++                  'OTHER_LDFLAGS': [
++                    '-faddress-sanitizer',
++                  ],
++                },
++              }],
++            ],
++          }],
++          ['_mac_bundle', {
++            'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-ObjC']},
++          }],
++          ['_type=="executable"', {
++            'postbuilds': [
++              {
++                # Arranges for data (heap) pages to be protected against
++                # code execution when running on Mac OS X 10.7 ("Lion"), and
++                # ensures that the position-independent executable (PIE) bit
++                # is set for ASLR when running on Mac OS X 10.5 ("Leopard").
++                'variables': {
++                  # Define change_mach_o_flags in a variable ending in _path
++                  # so that GYP understands it's a path and performs proper
++                  # relativization during dict merging.
++                  'change_mach_o_flags':
++                      'mac/change_mach_o_flags_from_xcode.sh',
++                  'change_mach_o_flags_options%': [
++                  ],
++                  'target_conditions': [
++                    ['mac_pie==0 or release_valgrind_build==1', {
++                      # Don't enable PIE if it's unwanted. It's unwanted if
++                      # the target specifies mac_pie=0 or if building for
++                      # Valgrind, because Valgrind doesn't understand slide.
++                      # See the similar mac_pie/release_valgrind_build check
++                      # below.
++                      'change_mach_o_flags_options': [
++                        '--no-pie',
++                      ],
++                    }],
++                  ],
++                },
++                'postbuild_name': 'Change Mach-O Flags',
++                'action': [
++                   '$(srcdir)$(os_sep)build$(os_sep)<(change_mach_o_flags)',
++                  '>@(change_mach_o_flags_options)',
++                ],
++              },
++            ],
++            'conditions': [
++              ['asan==1', {
++                'variables': {
++                 'asan_saves_file': 'asan.saves',
++                },
++                'xcode_settings': {
++                  'CHROMIUM_STRIP_SAVE_FILE': '<(asan_saves_file)',
++                },
++              }],
++            ],
++            'target_conditions': [
++              ['mac_pie==1 and release_valgrind_build==0', {
++                # Turn on position-independence (ASLR) for executables. When
++                # PIE is on for the Chrome executables, the framework will
++                # also be subject to ASLR.
++                # Don't do this when building for Valgrind, because Valgrind
++                # doesn't understand slide. TODO: Make Valgrind on Mac OS X
++                # understand slide, and get rid of the Valgrind check.
++                'xcode_settings': {
++                  'OTHER_LDFLAGS': [
++                    '-Wl,-pie',  # Position-independent executable (MH_PIE)
++                  ],
++                },
++              }],
++            ],
++          }],
++          ['(_type=="executable" or _type=="shared_library" or \
++             _type=="loadable_module") and mac_strip!=0', {
++            'target_conditions': [
++              ['mac_real_dsym == 1', {
++                # To get a real .dSYM bundle produced by dsymutil, set the
++                # debug information format to dwarf-with-dsym.  Since
++                # strip_from_xcode will not be used, set Xcode to do the
++                # stripping as well.
++                'configurations': {
++                  'Release_Base': {
++                    'xcode_settings': {
++                      'DEBUG_INFORMATION_FORMAT': 'dwarf-with-dsym',
++                      'DEPLOYMENT_POSTPROCESSING': 'YES',
++                      'STRIP_INSTALLED_PRODUCT': 'YES',
++                      'target_conditions': [
++                        ['_type=="shared_library" or _type=="loadable_module"', {
++                          # The Xcode default is to strip debugging symbols
++                          # only (-S).  Local symbols should be stripped as
++                          # well, which will be handled by -x.  Xcode will
++                          # continue to insert -S when stripping even when
++                          # additional flags are added with STRIPFLAGS.
++                          'STRIPFLAGS': '-x',
++                        }],  # _type=="shared_library" or _type=="loadable_module"'
++                      ],  # target_conditions
++                    },  # xcode_settings
++                  },  # configuration "Release"
++                },  # configurations
++              }, {  # mac_real_dsym != 1
++                # To get a fast fake .dSYM bundle, use a post-build step to
++                # produce the .dSYM and strip the executable.  strip_from_xcode
++                # only operates in the Release configuration.
++                'postbuilds': [
++                  {
++                    'variables': {
++                      # Define strip_from_xcode in a variable ending in _path
++                      # so that gyp understands it's a path and performs proper
++                      # relativization during dict merging.
++                      'strip_from_xcode': 'mac/strip_from_xcode',
++                    },
++                    'postbuild_name': 'Strip If Needed',
++                    'action': ['$(srcdir)$(os_sep)build$(os_sep)<(strip_from_xcode)'],
++                  },
++                ],  # postbuilds
++              }],  # mac_real_dsym
++            ],  # target_conditions
++          }],  # (_type=="executable" or _type=="shared_library" or
++               #  _type=="loadable_module") and mac_strip!=0
++        ],  # target_conditions
++      },  # target_defaults
++    }],  # OS=="mac"
++    ['OS=="ios"', {
++      'target_defaults': {
++        'xcode_settings' : {
++          'GCC_VERSION': 'com.apple.compilers.llvm.clang.1_0',
++
++          # This next block is mostly common with the 'mac' section above,
++          # but keying off (or setting) 'clang' isn't valid for iOS as it
++          # also seems to mean using the custom build of clang.
++
++          # Don't use -Wc++0x-extensions, which Xcode 4 enables by default
++          # when buliding with clang. This warning is triggered when the
++          # override keyword is used via the OVERRIDE macro from
++          # base/compiler_specific.h.
++          'CLANG_WARN_CXX0X_EXTENSIONS': 'NO',
++          'WARNING_CFLAGS': [
++            '-Wheader-hygiene',
++            # Don't die on dtoa code that uses a char as an array index.
++            # This is required solely for base/third_party/dmg_fp/dtoa.cc.
++            '-Wno-char-subscripts',
++            # Clang spots more unused functions.
++            '-Wno-unused-function',
++            # See comments on this flag higher up in this file.
++            '-Wno-unnamed-type-template-args',
++            # This (rightyfully) complains about 'override', which we use
++            # heavily.
++            '-Wno-c++11-extensions',
++          ],
++        },
++        'target_conditions': [
++          ['_type=="executable"', {
++            'configurations': {
++              'Release_Base': {
++                'xcode_settings': {
++                  'DEPLOYMENT_POSTPROCESSING': 'YES',
++                  'STRIP_INSTALLED_PRODUCT': 'YES',
++                },
++              },
++            },
++            'xcode_settings': {
++              'conditions': [
++                ['chromium_ios_signing', {
++                  # iOS SDK wants everything for device signed.
++                  'CODE_SIGN_IDENTITY[sdk=iphoneos*]': 'iPhone Developer',
++                }, {
++                  'CODE_SIGNING_REQUIRED': 'NO',
++                  'CODE_SIGN_IDENTITY[sdk=iphoneos*]': '',
++                }],
++              ],
++            },
++          }],
++        ],  # target_conditions
++      },  # target_defaults
++    }],  # OS=="ios"
++    ['OS=="win"', {
++      'target_defaults': {
++        'defines': [
++          'WIN32',
++          '_WINDOWS',
++          'NOMINMAX',
++          '_CRT_RAND_S',
++          'CERT_CHAIN_PARA_HAS_EXTRA_FIELDS',
++          'WIN32_LEAN_AND_MEAN',
++          '_ATL_NO_OPENGL',
++        ],
++        'conditions': [
++          ['build_with_mozilla==0', {
++              'defines': [
++                '_WIN32_WINNT=0x0602',
++                'WINVER=0x0602',
++              ],
++          }],
++          ['buildtype=="Official"', {
++              # In official builds, targets can self-select an optimization
++              # level by defining a variable named 'optimize', and setting it
++              # to one of
++              # - "size", optimizes for minimal code size - the default.
++              # - "speed", optimizes for speed over code size.
++              # - "max", whole program optimization and link-time code
++              #   generation. This is very expensive and should be used
++              #   sparingly.
++              'variables': {
++                'optimize%': 'size',
++              },
++              'target_conditions': [
++                ['optimize=="size"', {
++                    'msvs_settings': {
++                      'VCCLCompilerTool': {
++                        # 1, optimizeMinSpace, Minimize Size (/O1)
++                        'Optimization': '1',
++                        # 2, favorSize - Favor small code (/Os)
++                        'FavorSizeOrSpeed': '2',
++                      },
++                    },
++                  },
++                ],
++                ['optimize=="speed"', {
++                    'msvs_settings': {
++                      'VCCLCompilerTool': {
++                        # 2, optimizeMaxSpeed, Maximize Speed (/O2)
++                        'Optimization': '2',
++                        # 1, favorSpeed - Favor fast code (/Ot)
++                        'FavorSizeOrSpeed': '1',
++                      },
++                    },
++                  },
++                ],
++                ['optimize=="max"', {
++                    'msvs_settings': {
++                      'VCCLCompilerTool': {
++                        # 2, optimizeMaxSpeed, Maximize Speed (/O2)
++                        'Optimization': '2',
++                        # 1, favorSpeed - Favor fast code (/Ot)
++                        'FavorSizeOrSpeed': '1',
++                        # This implies link time code generation.
++                        'WholeProgramOptimization': 'true',
++                      },
++                    },
++                  },
++                ],
++              ],
++            },
++          ],
++          ['component=="static_library"', {
++            'defines': [
++              '_HAS_EXCEPTIONS=0',
++            ],
++          }],
++          ['MSVS_VERSION=="2008"', {
++            'defines': [
++              '_HAS_TR1=0',
++            ],
++          }],
++          ['secure_atl', {
++            'defines': [
++              '_SECURE_ATL',
++            ],
++          }],
++        ],
++        'msvs_system_include_dirs': [
++          '<(windows_sdk_path)/Include/shared',
++          '<(windows_sdk_path)/Include/um',
++          '<(windows_sdk_path)/Include/winrt',
++#          '<(directx_sdk_path)/Include',
++          '$(VSInstallDir)/VC/atlmfc/include',
++        ],
++        'msvs_cygwin_dirs': ['<(DEPTH)/third_party/cygwin'],
++        'msvs_disabled_warnings': [4351, 4396, 4503, 4819,
++          # TODO(maruel): These warnings are level 4. They will be slowly
++          # removed as code is fixed.
++          4100, 4121, 4125, 4127, 4130, 4131, 4189, 4201, 4238, 4244, 4245,
++          4310, 4355, 4428, 4481, 4505, 4510, 4512, 4530, 4610, 4611, 4701,
++          4702, 4706,
++        ],
++        'msvs_settings': {
++          'VCCLCompilerTool': {
++            'AdditionalOptions': ['/MP'],
++            'MinimalRebuild': 'false',
++            'BufferSecurityCheck': 'true',
++            'EnableFunctionLevelLinking': 'true',
++            'RuntimeTypeInfo': 'false',
++            'WarningLevel': '4',
++            'WarnAsError': 'true',
++            'DebugInformationFormat': '3',
++            'conditions': [
++              ['component=="shared_library"', {
++                'ExceptionHandling': '1',  # /EHsc
++              }, {
++                'ExceptionHandling': '0',
++              }],
++            ],
++          },
++          'VCLibrarianTool': {
++            'AdditionalOptions': ['/ignore:4221'],
++            'AdditionalLibraryDirectories': [
++#              '<(directx_sdk_path)/Lib/x86',
++              '<(windows_sdk_path)/Lib/win8/um/x86',
++            ],
++          },
++          'VCLinkerTool': {
++            'AdditionalDependencies': [
++              'wininet.lib',
++              'dnsapi.lib',
++              'version.lib',
++              'msimg32.lib',
++              'ws2_32.lib',
++              'usp10.lib',
++              'dbghelp.lib',
++              'winmm.lib',
++              'shlwapi.lib',
++            ],
++
++            'conditions': [
++              ['msvs_express', {
++                # Explicitly required when using the ATL with express
++                'AdditionalDependencies': [
++                  'atlthunk.lib',
++                ],
++
++                # ATL 8.0 included in WDK 7.1 makes the linker to generate
++                # almost eight hundred LNK4254 and LNK4078 warnings:
++                #   - warning LNK4254: section 'ATL' (50000040) merged into
++                #     '.rdata' (40000040) with different attributes
++                #   - warning LNK4078: multiple 'ATL' sections found with
++                #     different attributes
++                'AdditionalOptions': ['/ignore:4254', '/ignore:4078'],
++              }],
++              ['MSVS_VERSION=="2005e"', {
++                # Non-express versions link automatically to these
++                'AdditionalDependencies': [
++                  'advapi32.lib',
++                  'comdlg32.lib',
++                  'ole32.lib',
++                  'shell32.lib',
++                  'user32.lib',
++                  'winspool.lib',
++                ],
++              }],
++            ],
++            'AdditionalLibraryDirectories': [
++#              '<(directx_sdk_path)/Lib/x86', XXXX
++              '<(windows_sdk_path)/Lib/win8/um/x86',
++            ],
++            'GenerateDebugInformation': 'true',
++            'MapFileName': '$(OutDir)\\$(TargetName).map',
++            'ImportLibrary': '$(OutDir)\\lib\\$(TargetName).lib',
++            'FixedBaseAddress': '1',
++            # SubSystem values:
++            #   0 == not set
++            #   1 == /SUBSYSTEM:CONSOLE
++            #   2 == /SUBSYSTEM:WINDOWS
++            # Most of the executables we'll ever create are tests
++            # and utilities with console output.
++            'SubSystem': '1',
++          },
++          'VCMIDLTool': {
++            'GenerateStublessProxies': 'true',
++            'TypeLibraryName': '$(InputName).tlb',
++            'OutputDirectory': '$(IntDir)',
++            'HeaderFileName': '$(InputName).h',
++            'DLLDataFileName': '$(InputName).dlldata.c',
++            'InterfaceIdentifierFileName': '$(InputName)_i.c',
++            'ProxyFileName': '$(InputName)_p.c',
++          },
++          'VCResourceCompilerTool': {
++            'Culture' : '1033',
++            'AdditionalIncludeDirectories': [
++              '<(DEPTH)',
++              '<(SHARED_INTERMEDIATE_DIR)',
++            ],
++          },
++        },
++      },
++    }],
++    ['disable_nacl==1', {
++      'target_defaults': {
++        'defines': [
++          'DISABLE_NACL',
++        ],
++      },
++    }],
++    ['OS=="win" and msvs_use_common_linker_extras', {
++      'target_defaults': {
++        'msvs_settings': {
++          'VCLinkerTool': {
++            'DelayLoadDLLs': [
++              'dbghelp.dll',
++              'dwmapi.dll',
++              'shell32.dll',
++              'uxtheme.dll',
++            ],
++          },
++        },
++        'configurations': {
++          'x86_Base': {
++            'msvs_settings': {
++              'VCLinkerTool': {
++                'AdditionalOptions': [
++                  '/safeseh',
++                  '/dynamicbase',
++                  '/ignore:4199',
++                  '/ignore:4221',
++                  '/nxcompat',
++                ],
++              },
++            },
++          },
++          'x64_Base': {
++            'msvs_settings': {
++              'VCLinkerTool': {
++                'AdditionalOptions': [
++                  # safeseh is not compatible with x64
++                  '/dynamicbase',
++                  '/ignore:4199',
++                  '/ignore:4221',
++                  '/nxcompat',
++                ],
++              },
++            },
++          },
++        },
++      },
++    }],
++    ['enable_new_npdevice_api==1', {
++      'target_defaults': {
++        'defines': [
++          'ENABLE_NEW_NPDEVICE_API',
++        ],
++      },
++    }],
++    ['clang==1', {
++      'conditions': [
++        ['OS=="android"', {
++          # Android could use the goma with clang.
++          'make_global_settings': [
++            ['CC', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} ${CHROME_SRC}/<(make_clang_dir)/bin/clang)'],
++            ['CXX', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} ${CHROME_SRC}/<(make_clang_dir)/bin/clang++)'],
++            ['LINK', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} ${CHROME_SRC}/<(make_clang_dir)/bin/clang++)'],
++            ['CC.host', '$(CC)'],
++            ['CXX.host', '$(CXX)'],
++            ['LINK.host', '$(LINK)'],
++          ],
++        }, {
++          'make_global_settings': [
++            ['CC', '<(make_clang_dir)/bin/clang'],
++            ['CXX', '<(make_clang_dir)/bin/clang++'],
++            ['LINK', '$(CXX)'],
++            ['CC.host', '$(CC)'],
++            ['CXX.host', '$(CXX)'],
++            ['LINK.host', '$(LINK)'],
++          ],
++        }],
++      ],
++    }],
++    ['OS=="android" and clang==0', {
++      # Hardcode the compiler names in the Makefile so that
++      # it won't depend on the environment at make time.
++      'make_global_settings': [
++        ['CC', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <(android_toolchain)/*-gcc)'],
++        ['CXX', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <(android_toolchain)/*-g++)'],
++        ['LINK', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <(android_toolchain)/*-gcc)'],
++        ['CC.host', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <!(which gcc))'],
++        ['CXX.host', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <!(which g++))'],
++        ['LINK.host', '<!(/bin/echo -n ${ANDROID_GOMA_WRAPPER} <!(which g++))'],
++      ],
++    }],
++  ],
++  'xcode_settings': {
++    # DON'T ADD ANYTHING NEW TO THIS BLOCK UNLESS YOU REALLY REALLY NEED IT!
++    # This block adds *project-wide* configuration settings to each project
++    # file.  It's almost always wrong to put things here.  Specify your
++    # custom xcode_settings in target_defaults to add them to targets instead.
++
++    'conditions': [
++      # In an Xcode Project Info window, the "Base SDK for All Configurations"
++      # setting sets the SDK on a project-wide basis. In order to get the
++      # configured SDK to show properly in the Xcode UI, SDKROOT must be set
++      # here at the project level.
++      ['OS=="mac"', {
++        'conditions': [
++          ['mac_sdk_path==""', {
++            'SDKROOT': 'macosx<(mac_sdk)',  # -isysroot
++          }, {
++            'SDKROOT': '<(mac_sdk_path)',  # -isysroot
++          }],
++        ],
++      }],
++      ['OS=="ios"', {
++        'conditions': [
++          ['ios_sdk_path==""', {
++            'SDKROOT': 'iphoneos<(ios_sdk)',  # -isysroot
++          }, {
++            'SDKROOT': '<(ios_sdk_path)',  # -isysroot
++          }],
++        ],
++      }],
++      ['OS=="ios"', {
++        # Just build armv7 since iOS 4.3+ only supports armv7.
++        'ARCHS': '$(ARCHS_UNIVERSAL_IPHONE_OS)',
++        'IPHONEOS_DEPLOYMENT_TARGET': '<(ios_deployment_target)',
++        # Target both iPhone and iPad.
++        'TARGETED_DEVICE_FAMILY': '1,2',
++      }],
++    ],
++
++    # The Xcode generator will look for an xcode_settings section at the root
++    # of each dict and use it to apply settings on a file-wide basis.  Most
++    # settings should not be here, they should be in target-specific
++    # xcode_settings sections, or better yet, should use non-Xcode-specific
++    # settings in target dicts.  SYMROOT is a special case, because many other
++    # Xcode variables depend on it, including variables such as
++    # PROJECT_DERIVED_FILE_DIR.  When a source group corresponding to something
++    # like PROJECT_DERIVED_FILE_DIR is added to a project, in order for the
++    # files to appear (when present) in the UI as actual files and not red
++    # red "missing file" proxies, the correct path to PROJECT_DERIVED_FILE_DIR,
++    # and therefore SYMROOT, needs to be set at the project level.
++    'SYMROOT': '<(DEPTH)/xcodebuild',
++  },
++}
+diff --git a/build/gyp_includes/filename_rules.gypi b/build/gyp_includes/filename_rules.gypi
+new file mode 100644
+--- /dev/null
++++ b/build/gyp_includes/filename_rules.gypi
+@@ -0,0 +1,96 @@
++# Copyright (c) 2012 The Chromium Authors. All rights reserved.
++# Use of this source code is governed by a BSD-style license that can be
++# found in the LICENSE file.
++
++# This gypi file defines the patterns used for determining whether a
++# file is excluded from the build on a given platform.  It is
++# included by common.gypi for chromium_code.
++
++{
++  'target_conditions': [
++    ['OS!="win" or >(nacl_untrusted_build)==1', {
++      'sources/': [ ['exclude', '_win(_unittest)?\\.(h|cc)$'],
++                    ['exclude', '(^|/)win/'],
++                    ['exclude', '(^|/)win_[^/]*\\.(h|cc)$'] ],
++    }],
++    ['OS!="mac" or >(nacl_untrusted_build)==1', {
++      'sources/': [ ['exclude', '_(cocoa|mac)(_unittest)?\\.(h|cc|mm?)$'],
++                    ['exclude', '(^|/)(cocoa|mac)/'] ],
++    }],
++    ['OS!="ios" or >(nacl_untrusted_build)==1', {
++      'sources/': [ ['exclude', '_ios(_unittest)?\\.(h|cc|mm?)$'],
++                    ['exclude', '(^|/)ios/'] ],
++    }],
++    ['(OS!="mac" and OS!="ios") or >(nacl_untrusted_build)==1', {
++      'sources/': [ ['exclude', '\\.mm?$' ] ],
++    }],
++    # Do not exclude the linux files on *BSD since most of them can be
++    # shared at this point.
++    # In case a file is not needed, it is going to be excluded later on.
++    # TODO(evan): the above is not correct; we shouldn't build _linux
++    # files on non-linux.
++    ['OS!="linux" and OS!="solaris" and <(os_bsd)!=1 or >(nacl_untrusted_build)==1', {
++      'sources/': [
++        ['exclude', '_linux(_unittest)?\\.(h|cc)$'],
++        ['exclude', '(^|/)linux/'],
++      ],
++    }],
++    ['OS!="android"', {
++      'sources/': [
++        ['exclude', '_android(_unittest)?\\.cc$'],
++        ['exclude', '(^|/)android/'],
++      ],
++    }],
++    ['OS=="win" and >(nacl_untrusted_build)==0', {
++      'sources/': [
++        ['exclude', '_posix(_unittest)?\\.(h|cc)$'],
++        ['exclude', '(^|/)posix/'],
++      ],
++    }],
++    ['<(chromeos)!=1 or >(nacl_untrusted_build)==1', {
++      'sources/': [ ['exclude', '_chromeos(_unittest)?\\.(h|cc)$'] ]
++    }],
++    ['>(nacl_untrusted_build)==0', {
++      'sources/': [
++        ['exclude', '_nacl(_unittest)?\\.(h|cc)$'],
++      ],
++    }],
++    ['OS!="linux" and OS!="solaris" and <(os_bsd)!=1 or >(nacl_untrusted_build)==1', {
++      'sources/': [
++        ['exclude', '_xdg(_unittest)?\\.(h|cc)$'],
++      ],
++    }],
++    ['<(use_x11)!=1 or >(nacl_untrusted_build)==1', {
++      'sources/': [
++        ['exclude', '_(x|x11)(_unittest)?\\.(h|cc)$'],
++        ['exclude', '(^|/)x11_[^/]*\\.(h|cc)$'],
++      ],
++    }],
++    ['(<(toolkit_uses_gtk)!=1 or >(nacl_untrusted_build)==1) and (build_with_mozilla==0)', {
++      'sources/': [
++        ['exclude', '_gtk(_browsertest|_unittest)?\\.(h|cc)$'],
++        ['exclude', '(^|/)gtk/'],
++        ['exclude', '(^|/)gtk_[^/]*\\.(h|cc)$'],
++      ],
++    }],
++    ['<(toolkit_views)==0 or >(nacl_untrusted_build)==1', {
++      'sources/': [ ['exclude', '_views\\.(h|cc)$'] ]
++    }],
++    ['<(use_aura)==0 or >(nacl_untrusted_build)==1', {
++      'sources/': [ ['exclude', '_aura(_unittest)?\\.(h|cc)$'],
++                    ['exclude', '(^|/)aura/'],
++      ]
++    }],
++    ['<(use_aura)==0 or <(use_x11)==0 or >(nacl_untrusted_build)==1', {
++      'sources/': [ ['exclude', '_aurax11\\.(h|cc)$'] ]
++    }],
++    ['<(use_aura)==0 or OS!="win" or >(nacl_untrusted_build)==1', {
++      'sources/': [ ['exclude', '_aurawin\\.(h|cc)$'] ]
++    }],
++    ['<(use_ash)==0 or >(nacl_untrusted_build)==1', {
++      'sources/': [ ['exclude', '_ash(_unittest)?\\.(h|cc)$'],
++                    ['exclude', '(^|/)ash/'],
++      ]
++    }],
++  ]
++}
+diff --git a/build/gyp_includes/internal/release_defaults.gypi b/build/gyp_includes/internal/release_defaults.gypi
+new file mode 100644
+--- /dev/null
++++ b/build/gyp_includes/internal/release_defaults.gypi
+@@ -0,0 +1,18 @@
++# Copyright (c) 2011 The Chromium Authors. All rights reserved.
++# Use of this source code is governed by a BSD-style license that can be
++# found in the LICENSE file.
++{
++  'msvs_settings': {
++    'VCCLCompilerTool': {
++      'StringPooling': 'true',
++    },
++    'VCLinkerTool': {
++      # No incremental linking.
++      'LinkIncremental': '1',
++      # Eliminate Unreferenced Data (/OPT:REF).
++      'OptimizeReferences': '2',
++      # Folding on (/OPT:ICF).
++      'EnableCOMDATFolding': '2',
++    },
++  },
++}
+diff --git a/build/gyp_includes/internal/release_impl.gypi b/build/gyp_includes/internal/release_impl.gypi
+new file mode 100644
+--- /dev/null
++++ b/build/gyp_includes/internal/release_impl.gypi
+@@ -0,0 +1,17 @@
++# Copyright (c) 2011 The Chromium Authors. All rights reserved.
++# Use of this source code is governed by a BSD-style license that can be
++# found in the LICENSE file.
++{
++  'includes': ['release_defaults.gypi'],
++  'msvs_settings': {
++    'VCCLCompilerTool': {
++      'OmitFramePointers': 'false',
++      # The above is not sufficient (http://crbug.com/106711): it
++      # simply eliminates an explicit "/Oy", but both /O2 and /Ox
++      # perform FPO regardless, so we must explicitly disable.
++      # We still want the false setting above to avoid having
++      # "/Oy /Oy-" and warnings about overriding.
++      'AdditionalOptions': ['/Oy-'],
++    },
++  },
++}
+diff --git a/build/gyp_includes/internal/release_impl_official.gypi b/build/gyp_includes/internal/release_impl_official.gypi
+new file mode 100644
+--- /dev/null
++++ b/build/gyp_includes/internal/release_impl_official.gypi
+@@ -0,0 +1,43 @@
++# Copyright (c) 2011 The Chromium Authors. All rights reserved.
++# Use of this source code is governed by a BSD-style license that can be
++# found in the LICENSE file.
++{
++  'includes': ['release_defaults.gypi'],
++  'defines': ['OFFICIAL_BUILD'],
++  'msvs_settings': {
++    'VCCLCompilerTool': {
++      'InlineFunctionExpansion': '2',
++      'EnableIntrinsicFunctions': 'true',
++      'EnableFiberSafeOptimizations': 'true',
++      'OmitFramePointers': 'false',
++      # The above is not sufficient (http://crbug.com/106711): it
++      # simply eliminates an explicit "/Oy", but both /O2 and /Ox
++      # perform FPO regardless, so we must explicitly disable.
++      # We still want the false setting above to avoid having
++      # "/Oy /Oy-" and warnings about overriding.
++      'AdditionalOptions': ['/Oy-'],
++    },
++    'VCLibrarianTool': {
++      'AdditionalOptions': [
++        '/ltcg',
++        '/expectedoutputsize:120000000'
++      ],
++    },
++    'VCLinkerTool': {
++      'AdditionalOptions': [
++        '/time',
++        # This may reduce memory fragmentation during linking.
++        # The expected size is 40*1024*1024, which gives us about 10M of
++        # headroom as of Dec 16, 2011.
++        '/expectedoutputsize:41943040',
++      ],
++      'LinkTimeCodeGeneration': '1',
++      # The /PROFILE flag causes the linker to add a "FIXUP" debug stream to
++      # the generated PDB. According to MSDN documentation, this flag is only
++      # available (or perhaps supported) in the Enterprise (team development)
++      # version of Visual Studio. If this blocks your official build, simply
++      # comment out this line, then  re-run "gclient runhooks".
++      'Profile': 'true',
++    },
++  },
++}
+diff --git a/build/gyp_includes/release.gypi b/build/gyp_includes/release.gypi
+new file mode 100644
+--- /dev/null
++++ b/build/gyp_includes/release.gypi
+@@ -0,0 +1,17 @@
++{
++  'conditions': [
++    # Handle build types.
++    ['buildtype=="Dev"', {
++      'includes': ['internal/release_impl.gypi'],
++    }],
++    ['buildtype=="Official"', {
++      'includes': ['internal/release_impl_official.gypi'],
++    }],
++    # TODO(bradnelson): may also need:
++    #     checksenabled
++    #     coverage
++    #     dom_stats
++    #     pgo_instrument
++    #     pgo_optimize
++  ],
++}
+diff --git a/build/virtualenv_packages.txt b/build/virtualenv_packages.txt
+--- a/build/virtualenv_packages.txt
++++ b/build/virtualenv_packages.txt
+@@ -10,16 +10,17 @@ mozilla.pth:third_party/python/attrs/src
+ mozilla.pth:third_party/python/blessings
+ mozilla.pth:third_party/python/compare-locales
+ mozilla.pth:third_party/python/configobj
+ mozilla.pth:third_party/python/cram
+ mozilla.pth:third_party/python/dlmanager
+ mozilla.pth:third_party/python/enum34
+ mozilla.pth:third_party/python/fluent
+ mozilla.pth:third_party/python/futures
++mozilla.pth:third_party/python/gyp/pylib
+ mozilla.pth:third_party/python/hglib
+ mozilla.pth:third_party/python/mohawk
+ mozilla.pth:third_party/python/mozilla-version
+ mozilla.pth:third_party/python/pathlib2
+ mozilla.pth:third_party/python/jsmin
+ optional:setup.py:third_party/python/psutil:build_ext:--inplace
+ mozilla.pth:third_party/python/psutil
+ mozilla.pth:third_party/python/pylru
+@@ -57,15 +58,14 @@ mozilla.pth:tools
+ mozilla.pth:testing/web-platform
+ mozilla.pth:testing/web-platform/tests/tools/wptrunner
+ mozilla.pth:testing/web-platform/tests/tools/wptserve
+ mozilla.pth:testing/web-platform/tests/tools/six
+ mozilla.pth:testing/xpcshell
+ mozilla.pth:third_party/python/mock-1.0.0
+ mozilla.pth:xpcom/typelib/xpt/tools
+ mozilla.pth:tools/docs
+-mozilla.pth:media/webrtc/trunk/tools/gyp/pylib
+ mozilla.pth:third_party/python/cbor2
+ mozilla.pth:third_party/python/pyasn1
+ mozilla.pth:third_party/python/pyasn1-modules
+ mozilla.pth:third_party/python/rsa
+ mozilla.pth:third_party/python/PyECC
+ optional:packages.txt:comm/build/virtualenv_packages.txt
+diff --git a/python/mozbuild/mozbuild/frontend/gyp_reader.py b/python/mozbuild/mozbuild/frontend/gyp_reader.py
+--- a/python/mozbuild/mozbuild/frontend/gyp_reader.py
++++ b/python/mozbuild/mozbuild/frontend/gyp_reader.py
+@@ -35,17 +35,17 @@ sys.modules['gyp.generator.mozbuild'] = 
+ # build/gyp_chromium does this:
+ #   script_dir = os.path.dirname(os.path.realpath(__file__))
+ #   chrome_src = os.path.abspath(os.path.join(script_dir, os.pardir))
+ #   sys.path.insert(0, os.path.join(chrome_src, 'tools', 'gyp', 'pylib'))
+ # We're not importing gyp_chromium, but we want both script_dir and
+ # chrome_src for the default includes, so go backwards from the pylib
+ # directory, which is the parent directory of gyp module.
+ chrome_src = mozpath.abspath(mozpath.join(mozpath.dirname(gyp.__file__),
+-    '../../../..'))
++    '../../../../..'))
+ script_dir = mozpath.join(chrome_src, 'build')
+ 
+ 
+ def encode(value):
+     if isinstance(value, unicode):
+         return value.encode('utf-8')
+     return value
+ 
+@@ -381,38 +381,33 @@ class GypProcessor(object):
+         # gyp expects plain str instead of unicode. The frontend code gives us
+         # unicode strings, so convert them.
+         path = encode(path)
+         if bool(config.substs['_MSC_VER']):
+             # This isn't actually used anywhere in this generator, but it's needed
+             # to override the registry detection of VC++ in gyp.
+             os.environ['GYP_MSVS_OVERRIDE_PATH'] = 'fake_path'
+ 
+-            # TODO bug 1371485 upgrade vendored version of GYP to something that
+-            # doesn't barf when MSVS_VERSION==2017.
+-            msvs_version = config.substs['MSVS_VERSION']
+-            if msvs_version == '2017':
+-                warnings.warn('MSVS_VERSION being set to 2015 to appease GYP')
+-                msvs_version = '2015'
+-            os.environ['GYP_MSVS_VERSION'] = msvs_version
++            os.environ['GYP_MSVS_VERSION'] = config.substs['MSVS_VERSION']
+ 
+         params = {
+             b'parallel': False,
+             b'generator_flags': {},
+             b'build_files': [path],
+             b'root_targets': None,
+         }
+ 
+         if gyp_dir_attrs.no_chromium:
+             includes = []
+             depth = mozpath.dirname(path)
+         else:
+             depth = chrome_src
+             # Files that gyp_chromium always includes
+-            includes = [encode(mozpath.join(script_dir, 'common.gypi'))]
++            includes = [encode(mozpath.join(script_dir, 'gyp_includes',
++                                            'common.gypi'))]
+             finder = FileFinder(chrome_src)
+             includes.extend(encode(mozpath.join(chrome_src, name))
+                             for name, _ in finder.find('*/supplement.gypi'))
+ 
+         str_vars = dict((name, encode(value)) for name, value in
+                         gyp_dir_attrs.variables.items())
+         self._gyp_loader_future = executor.submit(load_gyp, [path], b'mozbuild',
+                                                   str_vars, includes,

+ 40 - 0
rel-257/ian/patches/1371485-5-63a1.patch

@@ -0,0 +1,40 @@
+# HG changeset patch
+# User Dan Minor <dminor@mozilla.com>
+# Date 1529691931 14400
+# Node ID 4828ebf3834b76ebc27a8f848adfade8b5b1b31b
+# Parent  ca0c14e77e36e95e73043204cdff663e5f69f481
+Bug 1371485 - Fix gflags root; r=chmanchester
+
+Summary:
+I think the webrtc.org gtests are the only user of gflags in tree. We can switch
+over to using gn to build this when we start building the tests using gn,
+which is Bug 1430779.
+
+Tags: #secure-revision
+
+Bug #: 1371485
+
+Differential Revision: https://phabricator.services.mozilla.com/D1802
+
+diff --git a/media/webrtc/trunk/third_party/gflags/gflags.gyp b/media/webrtc/trunk/third_party/gflags/gflags.gyp
+--- a/media/webrtc/trunk/third_party/gflags/gflags.gyp
++++ b/media/webrtc/trunk/third_party/gflags/gflags.gyp
+@@ -9,17 +9,17 @@
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ 
+ {
+   'variables': {
+-    'gflags_root': '<(DEPTH)/third_party/gflags',
++    'gflags_root': '/media/webrtc/trunk/third_party/gflags',
+     'conditions': [
+       ['OS=="win"', {
+         'gflags_gen_arch_root': '<(gflags_root)/gen/win',
+       }, {
+         'gflags_gen_arch_root': '<(gflags_root)/gen/posix',
+       }],
+     ],
+   },

+ 39 - 0
rel-257/ian/patches/1371485-6-63a1.patch

@@ -0,0 +1,39 @@
+# HG changeset patch
+# User Dan Minor <dminor@mozilla.com>
+# Date 1530108062 14400
+# Node ID 3810cdc004413fa8931c85895b052ca4c109a0b0
+# Parent  58fbc1a759d27403f2154ce65562100ae7e3b736
+Bug 1371485 - Remove OS X find_sdk.py check; r=chmanchester
+
+Summary:
+We're currently returning a fake value on all of our automation builds. Might
+as well not run the script at all.
+
+Tags: #secure-revision
+
+Bug #: 1371485
+
+Differential Revision: https://phabricator.services.mozilla.com/D1803
+
+diff --git a/build/gyp_includes/common.gypi b/build/gyp_includes/common.gypi
+--- a/build/gyp_includes/common.gypi
++++ b/build/gyp_includes/common.gypi
+@@ -1172,17 +1172,17 @@
+             'mac_sdk%': '<!(<(PYTHON) <(DEPTH)/build/mac/find_sdk.py --verify <(mac_sdk_min) --sdk_path=<(mac_sdk_path))',
+             # Enable uploading crash dumps.
+             'mac_breakpad_uploads%': 1,
+             # Enable dumping symbols at build time for use by Mac Breakpad.
+             'mac_breakpad%': 1,
+             # Enable Keystone auto-update support.
+             'mac_keystone%': 1,
+           }, { # else: branding!="Chrome" or buildtype!="Official"
+-            'mac_sdk%': '<!(<(PYTHON) <(DEPTH)/build/mac/find_sdk.py <(mac_sdk_min))',
++            'mac_sdk%': '', #'<!(<(PYTHON) <(DEPTH)/build/mac/find_sdk.py <(mac_sdk_min))',
+             'mac_breakpad_uploads%': 0,
+             'mac_breakpad%': 0,
+             'mac_keystone%': 0,
+           }],
+         ],
+       }],  # OS=="mac"
+ 
+       ['OS=="win"', {

+ 39 - 0
rel-257/ian/patches/1371485-7-63a1.patch

@@ -0,0 +1,39 @@
+# HG changeset patch
+# User Dan Minor <dminor@mozilla.com>
+# Date 1530129107 14400
+# Node ID 10a13ff35172d437e1f012fb6b16abf00387b863
+# Parent  61f1601e652564247d9dfd91777c26a84acb6034
+Bug 1371485 - Update gyp path in make-source-package.sh; r=chmanchester
+
+Reviewers: chmanchester
+
+Tags: #secure-revision
+
+Bug #: 1371485
+
+Differential Revision: https://phabricator.services.mozilla.com/D2034
+
+diff --git a/js/src/make-source-package.sh b/js/src/make-source-package.sh
+--- a/js/src/make-source-package.sh
++++ b/js/src/make-source-package.sh
+@@ -124,18 +124,18 @@ case $cmd in
+         ${TOPSRCDIR}/third_party/python \
+         ${tgtpath}/third_party
+     ${MKDIR} -p ${tgtpath}/dom/bindings
+     cp -pPR \
+         ${TOPSRCDIR}/dom/bindings/mozwebidlcodegen \
+         ${tgtpath}/dom/bindings
+     ${MKDIR} -p ${tgtpath}/media/webrtc/trunk/tools
+     cp -pPR \
+-        ${TOPSRCDIR}/media/webrtc/trunk/tools/gyp \
+-        ${tgtpath}/media/webrtc/trunk/tools
++        ${TOPSRCDIR}/third_party/python/gyp \
++        ${tgtpath}/third_party/python
+     ${MKDIR} -p ${tgtpath}/testing
+     cp -pPR \
+         ${TOPSRCDIR}/testing/mozbase \
+         ${tgtpath}/testing
+     ${MKDIR} -p ${tgtpath}/modules
+     cp -pPR \
+        ${TOPSRCDIR}/modules/fdlibm \
+        ${tgtpath}/modules/fdlibm

+ 34 - 0
rel-257/ian/patches/1371485-8-63a1.patch

@@ -0,0 +1,34 @@
+# HG changeset patch
+# User Dan Minor <dminor@mozilla.com>
+# Date 1531162121 14400
+# Node ID acc0d8ae4c88ad5978714b8b2344d02034dce24d
+# Parent  8f3ee465cb14e7cb1ec232f50937e67b4b0244db
+Bug 1371485 - Moving gyp requires a clobber; r=chmanchester
+
+Summary:
+It looks like we need a clobber in order for the build system to properly find
+gyp at its new location.
+
+Reviewers: chmanchester
+
+Tags: #secure-revision
+
+Bug #: 1371485
+
+Differential Revision: https://phabricator.services.mozilla.com/D2035
+
+diff --git a/CLOBBER b/CLOBBER
+--- a/CLOBBER
++++ b/CLOBBER
+@@ -17,9 +17,9 @@
+ #
+ # Modifying this file will now automatically clobber the buildbot machines \o/
+ #
+ 
+ # Are you updating CLOBBER because you think it's needed for your WebIDL
+ # changes to stick? As of bug 928195, this shouldn't be necessary! Please
+ # don't change CLOBBER for WebIDL changes any more.
+ 
+-Merge day clobber
+\ No newline at end of file
++Bug 1371485 - Moving gyp requires a clobber.

+ 342 - 0
rel-257/ian/patches/1372381-1-61a1.patch

@@ -0,0 +1,342 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1525111739 25200
+# Node ID 79f78ded94a2fb592b558e6119813ba551e7784f
+# Parent  2b10dfb5711c56bd20c0dde903a2c2f75bf2d824
+Bug 1372381 - Generate automation.py with GENERATED_FILES rather than Makefile.in r=mshal
+
+This commit also removes "DEFAULT_APP", which is unused.
+
+MozReview-Commit-ID: 5YYaC5LJqUn
+
+diff --git a/build/automation-build.mk b/build/automation-build.mk
+deleted file mode 100644
+--- a/build/automation-build.mk
++++ /dev/null
+@@ -1,67 +0,0 @@
+-# This Source Code Form is subject to the terms of the Mozilla Public
+-# 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/.
+-
+-include $(MOZILLA_DIR)/build/binary-location.mk
+-
+-browser_path := '"$(browser_path)"'
+-
+-_PROFILE_DIR = $(TARGET_DEPTH)/_profile/pgo
+-
+-ABSOLUTE_TOPSRCDIR = $(abspath $(MOZILLA_DIR))
+-_CERTS_SRC_DIR = $(ABSOLUTE_TOPSRCDIR)/build/pgo/certs
+-
+-AUTOMATION_PPARGS = 	\
+-			-DBROWSER_PATH=$(browser_path) \
+-			-DXPC_BIN_PATH='"$(DIST)/bin"' \
+-			-DBIN_SUFFIX='"$(BIN_SUFFIX)"' \
+-			-DPROFILE_DIR='"$(_PROFILE_DIR)"' \
+-			-DCERTS_SRC_DIR='"$(_CERTS_SRC_DIR)"' \
+-			-DPERL='"$(PERL)"' \
+-			$(NULL)
+-
+-ifeq ($(OS_ARCH),Darwin)
+-AUTOMATION_PPARGS += -DIS_MAC=1
+-else
+-AUTOMATION_PPARGS += -DIS_MAC=0
+-endif
+-
+-ifeq ($(OS_ARCH),Linux)
+-AUTOMATION_PPARGS += -DIS_LINUX=1
+-else
+-AUTOMATION_PPARGS += -DIS_LINUX=0
+-endif
+-
+-ifeq ($(host_os), cygwin)
+-AUTOMATION_PPARGS += -DIS_CYGWIN=1
+-endif
+-
+-ifeq ($(ENABLE_TESTS), 1)
+-AUTOMATION_PPARGS += -DIS_TEST_BUILD=1
+-else
+-AUTOMATION_PPARGS += -DIS_TEST_BUILD=0
+-endif
+-
+-ifeq ($(MOZ_DEBUG), 1)
+-AUTOMATION_PPARGS += -DIS_DEBUG_BUILD=1
+-else
+-AUTOMATION_PPARGS += -DIS_DEBUG_BUILD=0
+-endif
+-
+-ifdef MOZ_CRASHREPORTER
+-AUTOMATION_PPARGS += -DCRASHREPORTER=1
+-else
+-AUTOMATION_PPARGS += -DCRASHREPORTER=0
+-endif
+-
+-ifdef MOZ_ASAN
+-AUTOMATION_PPARGS += -DIS_ASAN=1
+-else
+-AUTOMATION_PPARGS += -DIS_ASAN=0
+-endif
+-
+-automation.py: $(MOZILLA_DIR)/build/automation.py.in $(MOZILLA_DIR)/build/automation-build.mk
+-	$(call py_action,preprocessor, \
+-	$(AUTOMATION_PPARGS) $(DEFINES) $(ACDEFINES) $< -o $@)
+-
+-GARBAGE += automation.py automation.pyc
+diff --git a/build/automation.py.in b/build/automation.py.in
+--- a/build/automation.py.in
++++ b/build/automation.py.in
+@@ -48,17 +48,16 @@ from mozscreenshot import printstatus, d
+ #expand _IS_LINUX = __IS_LINUX__ != 0
+ #ifdef IS_CYGWIN
+ #expand _IS_CYGWIN = __IS_CYGWIN__ == 1
+ #else
+ _IS_CYGWIN = False
+ #endif
+ #expand _BIN_SUFFIX = __BIN_SUFFIX__
+ 
+-#expand _DEFAULT_APP = "./" + __BROWSER_PATH__
+ #expand _CERTS_SRC_DIR = __CERTS_SRC_DIR__
+ #expand _IS_TEST_BUILD = __IS_TEST_BUILD__
+ #expand _IS_DEBUG_BUILD = __IS_DEBUG_BUILD__
+ #expand _CRASHREPORTER = __CRASHREPORTER__ == 1
+ #expand _IS_ASAN = __IS_ASAN__ == 1
+ 
+ 
+ if _IS_WIN32:
+@@ -94,17 +93,16 @@ class Automation(object):
+   IS_WIN32 = _IS_WIN32
+   IS_MAC = _IS_MAC
+   IS_LINUX = _IS_LINUX
+   IS_CYGWIN = _IS_CYGWIN
+   BIN_SUFFIX = _BIN_SUFFIX
+ 
+   UNIXISH = not IS_WIN32 and not IS_MAC
+ 
+-  DEFAULT_APP = _DEFAULT_APP
+   CERTS_SRC_DIR = _CERTS_SRC_DIR
+   IS_TEST_BUILD = _IS_TEST_BUILD
+   IS_DEBUG_BUILD = _IS_DEBUG_BUILD
+   CRASHREPORTER = _CRASHREPORTER
+   IS_ASAN = _IS_ASAN
+ 
+   # timeout, in seconds
+   DEFAULT_TIMEOUT = 60.0
+@@ -133,17 +131,16 @@ class Automation(object):
+     return [
+            "UNIXISH",
+            "IS_WIN32",
+            "IS_MAC",
+            "log",
+            "runApp",
+            "Process",
+            "DIST_BIN",
+-           "DEFAULT_APP",
+            "CERTS_SRC_DIR",
+            "environment",
+            "IS_TEST_BUILD",
+            "IS_DEBUG_BUILD",
+            "DEFAULT_TIMEOUT",
+           ]
+ 
+   class Process(subprocess.Popen):
+diff --git a/build/gen_automation.py b/build/gen_automation.py
+new file mode 100644
+--- /dev/null
++++ b/build/gen_automation.py
+@@ -0,0 +1,48 @@
++# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
++# vim: set filetype=python:
++# This Source Code Form is subject to the terms of the Mozilla Public
++# License, v. 2.0. If a copy of the MPL was not distibuted with this
++# file, You can obtain one at http://mozilla.og/MPL/2.0/.
++
++import sys
++import buildconfig
++from mozbuild.preprocessor import Preprocessor
++
++
++def main(output, input_file):
++    pp = Preprocessor()
++    pp.context.update(buildconfig.defines['ALLDEFINES'])
++
++    substs = buildconfig.substs
++
++    # Substs taken verbatim.
++    substs_vars = (
++        'BIN_SUFFIX',
++    )
++    for var in substs_vars:
++        pp.context[var] = '"%s"' % substs[var]
++
++    # Derived values.
++    for key, condition in (
++            ('IS_MAC', substs['OS_ARCH'] == 'Darwin'),
++            ('IS_LINUX', substs['OS_ARCH'] == 'Linux'),
++            ('IS_TEST_BUILD', substs.get('ENABLE_TESTS') == '1'),
++            ('IS_DEBUG_BUILD', substs.get('MOZ_DEBUG') == '1'),
++            ('CRASHREPORTER', substs.get('MOZ_CRASHREPORTER')),
++            ('IS_ASAN', substs.get('MOZ_ASAN'))):
++        if condition:
++            pp.context[key] = '1'
++        else:
++            pp.context[key] = '0'
++
++    pp.context.update({
++        'XPC_BIN_PATH': '"%s/dist/bin"' % buildconfig.topobjdir,
++        'CERTS_SRC_DIR': '"%s/build/pgo/certs"' % buildconfig.topsrcdir,
++    })
++
++    pp.out = output
++    pp.do_include(input_file)
++
++
++if __name__ == '__main__':
++    main(*sys.agv[1:])
+diff --git a/build/moz.build b/build/moz.build
+--- a/build/moz.build
++++ b/build/moz.build
+@@ -91,16 +91,30 @@ if CONFIG['MOZ_APP_BASENAME']:
+     if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'android' and CONFIG['MOZ_UPDATER']:
+         FINAL_TARGET_PP_FILES += ['update-settings.ini']
+ 
+     GENERATED_FILES += ['application.ini.h']
+     appini = GENERATED_FILES['application.ini.h']
+     appini.script = 'appini_header.py'
+     appini.inputs = ['!application.ini']
+ 
++if CONFIG['ENABLE_TESTS']:
++    GENERATED_FILES += ['automation.py']
++    auto = GENERATED_FILES['automation.py']
++    auto.script = 'gen_automation.py'
++    auto.inputs = ['automation.py.in']
++
++    TEST_HARNESS_FILES.reftest += [
++        '!automation.py',
++    ]
++
++    TEST_HARNESS_FILES.testing.mochitest += [
++        '!automation.py',
++    ]
++
+ # NOTE: Keep .gdbinit in the topsrcdir for people who run gdb from the topsrcdir.
+ OBJDIR_FILES += ['/.gdbinit']
+ 
+ # Put a .lldbinit in the bin directory and the objdir, to be picked up
+ # automatically by LLDB when we debug executables using either of those two
+ # directories as the current working directory.  The .lldbinit file will
+ # load $(topsrcdir)/.lldbinit, which is where the actual debugging commands are.
+ DEFINES['topsrcdir'] = TOPSRCDIR
+diff --git a/layout/tools/reftest/Makefile.in b/layout/tools/reftest/Makefile.in
+--- a/layout/tools/reftest/Makefile.in
++++ b/layout/tools/reftest/Makefile.in
+@@ -2,17 +2,13 @@
+ # This Source Code Form is subject to the terms of the Mozilla Public
+ # 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/.
+ 
+ _DEST_DIR = $(DEPTH)/_tests/reftest
+ 
+ include $(topsrcdir)/config/rules.mk
+ 
+-# We're installing to _tests/reftest
+-TARGET_DEPTH = ../..
+-include $(topsrcdir)/build/automation-build.mk
+-
+ # copy harness and the reftest extension bits to $(_DEST_DIR)
+ # This needs to happen after jar.mn handling from rules.mk included above.
+ # The order of the :: rules ensures that.
+ libs::
+ 	(cd $(DIST)/xpi-stage && tar $(TAR_CREATE_FLAGS) - reftest) | (cd $(_DEST_DIR) && tar -xf -)
+diff --git a/layout/tools/reftest/moz.build b/layout/tools/reftest/moz.build
+--- a/layout/tools/reftest/moz.build
++++ b/layout/tools/reftest/moz.build
+@@ -9,19 +9,17 @@ with Files('**'):
+     SCHEDULES.exclusive = ['reftest']
+ 
+ XPI_NAME = 'reftest'
+ USE_EXTENSION_MANIFEST = True
+ JAR_MANIFESTS += ['jar.mn']
+ FINAL_TARGET_PP_FILES += ['install.rdf']
+ FINAL_TARGET_FILES += ['bootstrap.js']
+ 
+-GENERATED_FILES += ['automation.py']
+ TEST_HARNESS_FILES.reftest += [
+-    '!automation.py',
+     '/build/mobile/remoteautomation.py',
+     '/build/pgo/server-locations.txt',
+     '/testing/mochitest/server.js',
+     'mach_test_package_commands.py',
+     'output.py',
+     'reftest-preferences.js',
+     'reftestcommandline.py',
+     'remotereftest.py',
+diff --git a/python/mozbuild/mozbuild/backend/tup.py b/python/mozbuild/mozbuild/backend/tup.py
+--- a/python/mozbuild/mozbuild/backend/tup.py
++++ b/python/mozbuild/mozbuild/backend/tup.py
+@@ -554,17 +554,18 @@ class TupBackend(CommonBackend):
+             extra_exports = {
+                 'buildid.h': ['MOZ_BUILD_DATE'],
+             }
+             for f in obj.outputs:
+                 exports = extra_exports.get(f)
+                 if exports:
+                     backend_file.export(exports)
+ 
+-            if any(f in obj.outputs for f in ('source-repo.h', 'buildid.h')):
++            if any(f.endswith(('automation.py', 'source-repo.h', 'buildid.h'))
++                   for f in obj.outputs):
+                 extra_outputs = [self._early_generated_files]
+             else:
+                 extra_outputs = [self._installed_files] if obj.required_for_compile else []
+                 full_inputs += [self._early_generated_files]
+ 
+             backend_file.rule(
+                 display='python {script}:{method} -> [%o]'.format(script=obj.script, method=obj.method),
+                 cmd=cmd,
+diff --git a/testing/mochitest/Makefile.in b/testing/mochitest/Makefile.in
+--- a/testing/mochitest/Makefile.in
++++ b/testing/mochitest/Makefile.in
+@@ -2,18 +2,14 @@
+ # This Source Code Form is subject to the terms of the Mozilla Public
+ # 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/.
+ 
+ 
+ _DEST_DIR = $(DEPTH)/_tests/$(relativesrcdir)
+ 
+ include $(topsrcdir)/config/rules.mk
+-# We're installing to _tests/testing/mochitest, so this is the depth
+-# necessary for relative objdir paths.
+-TARGET_DEPTH = ../../..
+-include $(topsrcdir)/build/automation-build.mk
+ 
+ libs:: 
+ 	(cd $(DIST)/xpi-stage && tar $(TAR_CREATE_FLAGS) - mochijar) | (cd $(_DEST_DIR) && tar -xf -)
+ 
+ $(_DEST_DIR):
+ 	$(NSINSTALL) -D $@
+diff --git a/testing/mochitest/moz.build b/testing/mochitest/moz.build
+--- a/testing/mochitest/moz.build
++++ b/testing/mochitest/moz.build
+@@ -23,22 +23,17 @@ if CONFIG['OS_TARGET'] != 'Android':
+     DEFINES['MOCHITEST_BOOTSTRAP'] = True
+     FINAL_TARGET_FILES += ['bootstrap.js']
+ 
+ MOCHITEST_MANIFESTS += [
+     'tests/MochiKit-1.4.2/tests/mochitest.ini',
+ ]
+ MOCHITEST_CHROME_MANIFESTS += ['chrome/chrome.ini']
+ 
+-GENERATED_FILES += [
+-    'automation.py',
+-]
+-
+ TEST_HARNESS_FILES.testing.mochitest += [
+-    '!automation.py',
+     '/build/mobile/remoteautomation.py',
+     '/build/pgo/server-locations.txt',
+     '/build/sanitizers/lsan_suppressions.txt',
+     '/build/sanitizers/ubsan_suppressions.txt',
+     '/build/valgrind/cross-architecture.sup',
+     '/build/valgrind/i386-pc-linux-gnu.sup',
+     '/build/valgrind/x86_64-pc-linux-gnu.sup',
+     '/netwerk/test/httpserver/httpd.js',

+ 118 - 0
rel-257/ian/patches/1372381-2-61a1.patch

@@ -0,0 +1,118 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1525111821 25200
+# Node ID 0a1897a68d63001f12a4dd9620ab8cefff207176
+# Parent  c3c6f8df99a9fc312e740afd5f054adfaac02efd
+Bug 1372381 - Temporarily skip certain problematic binaries in the Tup backend. r=mshal
+
+MozReview-Commit-ID: 7lopI8UQPSZ
+
+diff --git a/python/mozbuild/mozbuild/backend/tup.py b/python/mozbuild/mozbuild/backend/tup.py
+--- a/python/mozbuild/mozbuild/backend/tup.py
++++ b/python/mozbuild/mozbuild/backend/tup.py
+@@ -76,32 +76,45 @@ class BackendTupfile(object):
+         self.sources = defaultdict(list)
+         self.host_sources = defaultdict(list)
+         self.variables = {}
+         self.static_lib = None
+         self.shared_lib = None
+         self.program = None
+         self.exports = set()
+ 
++        # These files are special, ignore anything that generates them or
++        # depends on them.
++        self._skip_files = [
++            'signmar',
++            'libxul.so',
++            'libtestcrasher.so',
++        ]
++
+         self.fh = FileAvoidWrite(self.name, capture_diff=True)
+         self.fh.write('# THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT EDIT.\n')
+         self.fh.write('\n')
+ 
+     def write(self, buf):
+         self.fh.write(buf)
+ 
+     def include_rules(self):
+         if not self.rules_included:
+             self.write('include_rules\n')
+             self.rules_included = True
+ 
+     def rule(self, cmd, inputs=None, outputs=None, display=None,
+              extra_inputs=None, extra_outputs=None, check_unchanged=False):
+         inputs = inputs or []
+         outputs = outputs or []
++
++        for f in inputs + outputs:
++            if any(f.endswith(skip_file) for skip_file in self._skip_files):
++                return
++
+         display = display or ""
+         self.include_rules()
+         flags = ""
+         if check_unchanged:
+             # This flag causes tup to compare the outputs with the previous run
+             # of the command, and skip the rest of the DAG for any that are the
+             # same.
+             flags += "o"
+@@ -273,19 +286,16 @@ class TupBackend(CommonBackend):
+         return cmd
+ 
+     def _lib_paths(self, objdir, libs):
+         return [mozpath.relpath(mozpath.join(l.objdir, l.import_name), objdir)
+                 for l in libs]
+ 
+     def _gen_shared_library(self, backend_file):
+         shlib = backend_file.shared_lib
+-        if shlib.name == 'libxul.so':
+-            # This will fail to link currently due to missing rust symbols.
+-            return
+ 
+         if shlib.cxx_link:
+             mkshlib = (
+                 [backend_file.environment.substs['CXX']] +
+                 backend_file.local_flags['CXX_LDFLAGS']
+             )
+         else:
+             mkshlib = (
+@@ -303,19 +313,16 @@ class TupBackend(CommonBackend):
+         objs, _, shared_libs, os_libs, static_libs = self._expand_libs(shlib)
+         static_libs = self._lib_paths(backend_file.objdir, static_libs)
+         shared_libs = self._lib_paths(backend_file.objdir, shared_libs)
+ 
+         list_file_name = '%s.list' % shlib.name.replace('.', '_')
+         list_file = self._make_list_file(backend_file.objdir, objs, list_file_name)
+ 
+         inputs = objs + static_libs + shared_libs
+-        if any(i.endswith('libxul.so') for i in inputs):
+-            # Don't attempt to link anything that depends on libxul.
+-            return
+ 
+         symbols_file = []
+         if shlib.symbols_file:
+             inputs.append(shlib.symbols_file)
+             # TODO: Assumes GNU LD
+             symbols_file = ['-Wl,--version-script,%s' % shlib.symbols_file]
+ 
+         cmd = (
+@@ -343,19 +350,16 @@ class TupBackend(CommonBackend):
+ 
+     def _gen_program(self, backend_file):
+         cc_or_cxx = 'CXX' if backend_file.program.cxx_link else 'CC'
+         objs, _, shared_libs, os_libs, static_libs = self._expand_libs(backend_file.program)
+         static_libs = self._lib_paths(backend_file.objdir, static_libs)
+         shared_libs = self._lib_paths(backend_file.objdir, shared_libs)
+ 
+         inputs = objs + static_libs + shared_libs
+-        if any(i.endswith('libxul.so') for i in inputs):
+-            # Don't attempt to link anything that depends on libxul.
+-            return
+ 
+         list_file_name = '%s.list' % backend_file.program.name.replace('.', '_')
+         list_file = self._make_list_file(backend_file.objdir, objs, list_file_name)
+ 
+         outputs = [mozpath.relpath(backend_file.program.output_path.full_path,
+                                    backend_file.objdir)]
+         cmd = (
+             [backend_file.environment.substs[cc_or_cxx], '-o', '%o'] +

+ 383 - 0
rel-257/ian/patches/1372381-3-61a1.patch

@@ -0,0 +1,383 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1525111844 25200
+# Node ID 539a4a607ef98975ae0cde61c793723a6b1e19c5
+# Parent  f6962675bb16129403f2b24b6f8f32eccd033bd9
+Bug 1372381 - Compile host libraries, host programs, and simple programs in the Tup backend. r=mshal
+
+MozReview-Commit-ID: 2AcpqiOqSSf
+
+diff --git a/python/mozbuild/mozbuild/backend/tup.py b/python/mozbuild/mozbuild/backend/tup.py
+--- a/python/mozbuild/mozbuild/backend/tup.py
++++ b/python/mozbuild/mozbuild/backend/tup.py
+@@ -34,17 +34,20 @@ from ..frontend.data import (
+     GeneratedFile,
+     GeneratedSources,
+     HostDefines,
+     HostSources,
+     JARManifest,
+     ObjdirFiles,
+     PerSourceFlag,
+     Program,
++    SimpleProgram,
++    HostLibrary,
+     HostProgram,
++    HostSimpleProgram,
+     SharedLibrary,
+     Sources,
+     StaticLibrary,
+     VariablePassthru,
+ )
+ from ..util import (
+     FileAvoidWrite,
+     expand_variables,
+@@ -73,17 +76,19 @@ class BackendTupfile(object):
+         self.delayed_installed_files = []
+         self.per_source_flags = defaultdict(list)
+         self.local_flags = defaultdict(list)
+         self.sources = defaultdict(list)
+         self.host_sources = defaultdict(list)
+         self.variables = {}
+         self.static_lib = None
+         self.shared_lib = None
+-        self.program = None
++        self.programs = []
++        self.host_programs = []
++        self.host_library = None
+         self.exports = set()
+ 
+         # These files are special, ignore anything that generates them or
+         # depends on them.
+         self._skip_files = [
+             'signmar',
+             'libxul.so',
+             'libtestcrasher.so',
+@@ -213,21 +218,27 @@ class TupBackend(CommonBackend):
+     """
+ 
+     def _init(self):
+         CommonBackend._init(self)
+ 
+         self._backend_files = {}
+         self._cmd = MozbuildObject.from_environment()
+         self._manifest_entries = OrderedDefaultDict(set)
+-        self._compile_env_gen_files = (
++
++        # These are a hack to approximate things that are needed for the
++        # compile phase.
++        self._compile_env_files = (
++            '*.api',
+             '*.c',
++            '*.cfg',
+             '*.cpp',
+             '*.h',
+             '*.inc',
++            '*.msg',
+             '*.py',
+             '*.rs',
+         )
+ 
+         # These are 'group' dependencies - All rules that list these as an output
+         # will be built before any rules that list this as an input.
+         self._installed_idls = '$(MOZ_OBJ_ROOT)/<installed-idls>'
+         self._installed_files = '$(MOZ_OBJ_ROOT)/<installed-files>'
+@@ -342,30 +353,37 @@ class TupBackend(CommonBackend):
+             display='LINK %o'
+         )
+         backend_file.symlink_rule(mozpath.join(backend_file.objdir,
+                                                shlib.lib_name),
+                                   output=mozpath.join(self.environment.topobjdir,
+                                                       shlib.install_target,
+                                                       shlib.lib_name))
+ 
++    def _gen_programs(self, backend_file):
++        for p in backend_file.programs:
++            self._gen_program(backend_file, p)
+ 
+-    def _gen_program(self, backend_file):
+-        cc_or_cxx = 'CXX' if backend_file.program.cxx_link else 'CC'
+-        objs, _, shared_libs, os_libs, static_libs = self._expand_libs(backend_file.program)
++    def _gen_program(self, backend_file, prog):
++        cc_or_cxx = 'CXX' if prog.cxx_link else 'CC'
++        objs, _, shared_libs, os_libs, static_libs = self._expand_libs(prog)
+         static_libs = self._lib_paths(backend_file.objdir, static_libs)
+         shared_libs = self._lib_paths(backend_file.objdir, shared_libs)
+ 
+         inputs = objs + static_libs + shared_libs
+ 
+-        list_file_name = '%s.list' % backend_file.program.name.replace('.', '_')
++        list_file_name = '%s.list' % prog.name.replace('.', '_')
+         list_file = self._make_list_file(backend_file.objdir, objs, list_file_name)
+ 
+-        outputs = [mozpath.relpath(backend_file.program.output_path.full_path,
+-                                   backend_file.objdir)]
++        if isinstance(prog, SimpleProgram):
++            outputs = [prog.name]
++        else:
++            outputs = [mozpath.relpath(prog.output_path.full_path,
++                                       backend_file.objdir)]
++
+         cmd = (
+             [backend_file.environment.substs[cc_or_cxx], '-o', '%o'] +
+             backend_file.local_flags['CXX_LDFLAGS'] +
+             [list_file] +
+             backend_file.local_flags['LDFLAGS'] +
+             static_libs +
+             [backend_file.environment.substs['MOZ_PROGRAM_LDFLAGS']] +
+             shared_libs +
+@@ -375,16 +393,67 @@ class TupBackend(CommonBackend):
+         backend_file.rule(
+             cmd=cmd,
+             inputs=inputs,
+             outputs=outputs,
+             display='LINK %o'
+         )
+ 
+ 
++    def _gen_host_library(self, backend_file):
++        objs = backend_file.host_library.objs
++        inputs = objs
++        outputs = [backend_file.host_library.name]
++        cmd = (
++            [backend_file.environment.substs['HOST_AR']] +
++            [backend_file.environment.substs['HOST_AR_FLAGS'].replace('$@', '%o')] +
++            objs
++        )
++        backend_file.rule(
++            cmd=cmd,
++            inputs=inputs,
++            outputs=outputs,
++            display='AR %o'
++        )
++
++
++    def _gen_host_programs(self, backend_file):
++        for p in backend_file.host_programs:
++            self._gen_host_program(backend_file, p)
++
++
++    def _gen_host_program(self, backend_file, prog):
++        _, _, _, extra_libs, _ = self._expand_libs(prog)
++        objs = prog.objs
++        outputs = [prog.program]
++        host_libs = []
++        for lib in prog.linked_libraries:
++            if isinstance(lib, HostLibrary):
++                host_libs.append(lib)
++        host_libs = self._lib_paths(backend_file.objdir, host_libs)
++
++        inputs = objs + host_libs
++        use_cxx = any(f.endswith(('.cc', '.cpp')) for f in prog.source_files())
++        cc_or_cxx = 'HOST_CXX' if use_cxx else 'HOST_CC'
++        cmd = (
++            [backend_file.environment.substs[cc_or_cxx], '-o', '%o'] +
++            backend_file.local_flags['HOST_CXX_LDFLAGS'] +
++            backend_file.local_flags['HOST_LDFLAGS'] +
++            objs +
++            host_libs +
++            extra_libs
++        )
++        backend_file.rule(
++            cmd=cmd,
++            inputs=inputs,
++            outputs=outputs,
++            display='LINK %o'
++        )
++
++
+     def _gen_static_library(self, backend_file):
+         ar = [
+             backend_file.environment.substs['AR'],
+             backend_file.environment.substs['AR_FLAGS'].replace('$@', '%o')
+         ]
+ 
+         objs, _, shared_libs, _, static_libs = self._expand_libs(backend_file.static_lib)
+         static_libs = self._lib_paths(backend_file.objdir, static_libs)
+@@ -416,17 +485,17 @@ class TupBackend(CommonBackend):
+             return True
+ 
+         backend_file = self._get_backend_file_for(obj)
+ 
+         if isinstance(obj, GeneratedFile):
+             skip_files = []
+ 
+             if self.environment.is_artifact_build:
+-                skip_files = self._compile_env_gen_files
++                skip_files = self._compile_env_gen
+ 
+             for f in obj.outputs:
+                 if any(mozpath.match(f, p) for p in skip_files):
+                     return False
+ 
+             if backend_file.requires_delay(obj.inputs):
+                 backend_file.delayed_generated_files.append(obj)
+             else:
+@@ -458,20 +527,22 @@ class TupBackend(CommonBackend):
+         elif isinstance(obj, HostSources):
+             backend_file.host_sources[obj.canonical_suffix].extend(obj.files)
+         elif isinstance(obj, VariablePassthru):
+             backend_file.variables = obj.variables
+         elif isinstance(obj, StaticLibrary):
+             backend_file.static_lib = obj
+         elif isinstance(obj, SharedLibrary):
+             backend_file.shared_lib = obj
+-        elif isinstance(obj, HostProgram):
+-            pass
+-        elif isinstance(obj, Program):
+-            backend_file.program = obj
++        elif isinstance(obj, (HostProgram, HostSimpleProgram)):
++            backend_file.host_programs.append(obj)
++        elif isinstance(obj, HostLibrary):
++            backend_file.host_library = obj
++        elif isinstance(obj, (Program, SimpleProgram)):
++            backend_file.programs.append(obj)
+         elif isinstance(obj, DirectoryTraversal):
+             pass
+ 
+         return True
+ 
+     def consume_finished(self):
+         CommonBackend.consume_finished(self)
+ 
+@@ -479,21 +550,23 @@ class TupBackend(CommonBackend):
+         # simply write out the resulting files here.
+         for target, entries in self._manifest_entries.iteritems():
+             with self._write_file(mozpath.join(self.environment.topobjdir,
+                                                target)) as fh:
+                 fh.write(''.join('%s\n' % e for e in sorted(entries)))
+ 
+         for objdir, backend_file in sorted(self._backend_files.items()):
+             backend_file.gen_sources_rules([self._installed_files])
+-            for condition, gen_method in ((backend_file.shared_lib, self._gen_shared_library),
+-                                          (backend_file.static_lib and backend_file.static_lib.no_expand_lib,
+-                                           self._gen_static_library),
+-                                          (backend_file.program, self._gen_program)):
+-                if condition:
++            for var, gen_method in ((backend_file.shared_lib, self._gen_shared_library),
++                                    (backend_file.static_lib and backend_file.static_lib.no_expand_lib,
++                                     self._gen_static_library),
++                                    (backend_file.programs, self._gen_programs),
++                                    (backend_file.host_programs, self._gen_host_programs),
++                                    (backend_file.host_library, self._gen_host_library)):
++                if var:
+                     backend_file.export_shell()
+                     gen_method(backend_file)
+             for obj in backend_file.delayed_generated_files:
+                 self._process_generated_file(backend_file, obj)
+             for path, output, output_group in backend_file.delayed_installed_files:
+                 backend_file.symlink_rule(path, output=output, output_group=output_group)
+             with self._write_file(fh=backend_file):
+                 pass
+@@ -528,17 +601,16 @@ class TupBackend(CommonBackend):
+         if not os.path.exists(mozpath.join(self.environment.topsrcdir, ".tup")):
+             tup = self.environment.substs.get('TUP', 'tup')
+             self._cmd.run_process(cwd=self.environment.topsrcdir, log_name='tup', args=[tup, 'init'])
+ 
+     def _process_generated_file(self, backend_file, obj):
+         # TODO: These are directories that don't work in the tup backend
+         # yet, because things they depend on aren't built yet.
+         skip_directories = (
+-            'layout/style/test', # HostSimplePrograms
+             'toolkit/library', # libxul.so
+         )
+         if obj.script and obj.method and obj.relobjdir not in skip_directories:
+             backend_file.export_shell()
+             cmd = self._py_action('file_generate')
+             if obj.localized:
+                 cmd.append('--locale=en-US')
+             cmd.extend([
+@@ -601,16 +673,21 @@ class TupBackend(CommonBackend):
+ 
+         if target.startswith('_tests'):
+             # TODO: TEST_HARNESS_FILES present a few challenges for the tup
+             # backend (bug 1372381).
+             return
+ 
+         for path, files in obj.files.walk():
+             for f in files:
++                output_group = None
++                if any(mozpath.match(mozpath.basename(f), p)
++                       for p in self._compile_env_files):
++                    output_group = self._installed_files
++
+                 if not isinstance(f, ObjDirPath):
+                     backend_file = self._get_backend_file(mozpath.join(target, path))
+                     if '*' in f:
+                         if f.startswith('/') or isinstance(f, AbsolutePath):
+                             basepath, wild = os.path.split(f.full_path)
+                             if '*' in basepath:
+                                 raise Exception("Wildcards are only supported in the filename part of "
+                                                 "srcdir-relative or absolute paths.")
+@@ -624,40 +701,38 @@ class TupBackend(CommonBackend):
+                                     if '*' not in p:
+                                         yield p + '/'
+                             prefix = ''.join(_prefix(f.full_path))
+                             self.backend_input_files.add(prefix)
+                             finder = FileFinder(prefix)
+                             for p, _ in finder.find(f.full_path[len(prefix):]):
+                                 backend_file.symlink_rule(mozpath.join(prefix, p),
+                                                           output=mozpath.join(f.target_basename, p),
+-                                                          output_group=self._installed_files)
++                                                          output_group=output_group)
+                     else:
+-                        backend_file.symlink_rule(f.full_path, output=f.target_basename, output_group=self._installed_files)
++                        backend_file.symlink_rule(f.full_path, output=f.target_basename, output_group=output_group)
+                 else:
+                     if (self.environment.is_artifact_build and
+                         any(mozpath.match(f.target_basename, p) for p in self._compile_env_gen_files)):
+                         # If we have an artifact build we never would have generated this file,
+                         # so do not attempt to install it.
+                         continue
+ 
+                     # We're not generating files in these directories yet, so
+                     # don't attempt to install files generated from them.
+-                    if f.context.relobjdir not in ('layout/style/test',
+-                                                   'toolkit/library',
++                    if f.context.relobjdir not in ('toolkit/library',
+                                                    'js/src/shell'):
+                         output = mozpath.join('$(MOZ_OBJ_ROOT)', target, path,
+                                               f.target_basename)
+                         gen_backend_file = self._get_backend_file(f.context.relobjdir)
+                         if gen_backend_file.requires_delay([f]):
+-                            output_group = self._installed_files if f.target_basename.endswith('.h') else None
+                             gen_backend_file.delayed_installed_files.append((f.full_path, output, output_group))
+                         else:
+                             gen_backend_file.symlink_rule(f.full_path, output=output,
+-                                                          output_group=self._installed_files)
++                                                          output_group=output_group)
+ 
+     def _process_final_target_pp_files(self, obj, backend_file):
+         for i, (path, files) in enumerate(obj.files.walk()):
+             for f in files:
+                 self._preprocess(backend_file, f.full_path,
+                                  destdir=mozpath.join(self.environment.topobjdir, obj.install_target, path))
+ 
+     def _process_computed_flags(self, obj, backend_file):
+diff --git a/python/mozbuild/mozbuild/frontend/data.py b/python/mozbuild/mozbuild/frontend/data.py
+--- a/python/mozbuild/mozbuild/frontend/data.py
++++ b/python/mozbuild/mozbuild/frontend/data.py
+@@ -528,16 +528,24 @@ class SimpleProgram(BaseProgram):
+ 
+ 
+ class HostSimpleProgram(HostMixin, BaseProgram):
+     """Context derived container object for each program in
+     HOST_SIMPLE_PROGRAMS"""
+     SUFFIX_VAR = 'HOST_BIN_SUFFIX'
+     KIND = 'host'
+ 
++    def source_files(self):
++        for srcs in self.sources.values():
++            for f in srcs:
++                if ('host_%s' % mozpath.basename(mozpath.splitext(f)[0]) ==
++                    mozpath.splitext(self.program)[0]):
++                    return [f]
++        return []
++
+ 
+ def cargo_output_directory(context, target_var):
+     # cargo creates several directories and places its build artifacts
+     # in those directories.  The directory structure depends not only
+     # on the target, but also what sort of build we are doing.
+     rust_build_kind = 'release'
+     if context.config.substs.get('MOZ_DEBUG_RUST'):
+         rust_build_kind = 'debug'

+ 88 - 0
rel-257/ian/patches/1372381-4-61a1.patch

@@ -0,0 +1,88 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1525111844 25200
+# Node ID c2420955ce61a3e5c650b309e96564f9a494bdf8
+# Parent  d73a278cd50416fdc4b2f9bc15b096b384595ded
+Bug 1372381 - Install TEST_HARNESS_FILES in the tup backend. r=mshal
+
+MozReview-Commit-ID: 3PTtvoh8D9L
+
+diff --git a/python/mozbuild/mozbuild/backend/tup.py b/python/mozbuild/mozbuild/backend/tup.py
+--- a/python/mozbuild/mozbuild/backend/tup.py
++++ b/python/mozbuild/mozbuild/backend/tup.py
+@@ -50,16 +50,17 @@ from ..frontend.data import (
+ )
+ from ..util import (
+     FileAvoidWrite,
+     expand_variables,
+ )
+ from ..frontend.context import (
+     AbsolutePath,
+     ObjDirPath,
++    RenamedSourcePath,
+ )
+ 
+ 
+ class BackendTupfile(object):
+     """Represents a generated Tupfile.
+     """
+ 
+     def __init__(self, objdir, environment, topsrcdir, topobjdir):
+@@ -666,21 +667,16 @@ class TupBackend(CommonBackend):
+                 'dist/xpi-stage',
+                 '_tests',
+                 'dist/include',
+                 'dist/sdk',
+             ))
+             if not path:
+                 raise Exception("Cannot install to " + target)
+ 
+-        if target.startswith('_tests'):
+-            # TODO: TEST_HARNESS_FILES present a few challenges for the tup
+-            # backend (bug 1372381).
+-            return
+-
+         for path, files in obj.files.walk():
+             for f in files:
+                 output_group = None
+                 if any(mozpath.match(mozpath.basename(f), p)
+                        for p in self._compile_env_files):
+                     output_group = self._installed_files
+ 
+                 if not isinstance(f, ObjDirPath):
+@@ -697,20 +693,34 @@ class TupBackend(CommonBackend):
+                             pass
+                         else:
+                             def _prefix(s):
+                                 for p in mozpath.split(s):
+                                     if '*' not in p:
+                                         yield p + '/'
+                             prefix = ''.join(_prefix(f.full_path))
+                             self.backend_input_files.add(prefix)
++
++                            output_dir = ''
++                            # If we have a RenamedSourcePath here, the common backend
++                            # has generated this object from a jar manifest, and we
++                            # can rely on 'path' to be our destination path relative
++                            # to any wildcard match. Otherwise, the output file may
++                            # contribute to our destination directory.
++                            if not isinstance(f, RenamedSourcePath):
++                                output_dir = ''.join(_prefix(mozpath.dirname(f)))
++
+                             finder = FileFinder(prefix)
+                             for p, _ in finder.find(f.full_path[len(prefix):]):
++                                install_dir = prefix[len(obj.srcdir) + 1:]
++                                output = p
++                                if f.target_basename and '*' not in f.target_basename:
++                                    output = mozpath.join(f.target_basename, output)
+                                 backend_file.symlink_rule(mozpath.join(prefix, p),
+-                                                          output=mozpath.join(f.target_basename, p),
++                                                          output=mozpath.join(output_dir, output),
+                                                           output_group=output_group)
+                     else:
+                         backend_file.symlink_rule(f.full_path, output=f.target_basename, output_group=output_group)
+                 else:
+                     if (self.environment.is_artifact_build and
+                         any(mozpath.match(f.target_basename, p) for p in self._compile_env_gen_files)):
+                         # If we have an artifact build we never would have generated this file,
+                         # so do not attempt to install it.

+ 209 - 0
rel-257/ian/patches/1372458-63a1.patch

@@ -0,0 +1,209 @@
+# HG changeset patch
+# User Matt Woodrow <mwoodrow@mozilla.com>
+# Date 1531538749 -43200
+# Node ID d48e40cba0b40df512ba0bf0a35f5f0fea9d0b9c
+# Parent  32a9e6442c87cd05bd3dffe0343a64f2eb230846
+Bug 1372458 - Fold opacity into filter drawing rather than using a temporary surface. r=bas,mstange
+
+MozReview-Commit-ID: GOBTUhN7fcC
+
+diff --git a/gfx/2d/DrawTargetD2D1.cpp b/gfx/2d/DrawTargetD2D1.cpp
+--- a/gfx/2d/DrawTargetD2D1.cpp
++++ b/gfx/2d/DrawTargetD2D1.cpp
+@@ -230,18 +230,34 @@ void DrawTargetD2D1::DrawFilter(FilterNo
+ 
+   PrepareForDrawing(aOptions.mCompositionOp, ColorPattern(Color()));
+ 
+   mDC->SetAntialiasMode(D2DAAMode(aOptions.mAntialiasMode));
+ 
+   FilterNodeD2D1 *node = static_cast<FilterNodeD2D1 *>(aNode);
+   node->WillDraw(this);
+ 
+-  mDC->DrawImage(node->OutputEffect(), D2DPoint(aDestPoint),
+-                 D2DRect(aSourceRect));
++  if (aOptions.mAlpha == 1.0f) {
++    mDC->DrawImage(node->OutputEffect(), D2DPoint(aDestPoint),
++                   D2DRect(aSourceRect));
++    RefPtr<ID2D1Image> image;
++    node->OutputEffect()->GetOutput(getter_AddRefs(image));
++
++    Matrix mat = Matrix::Translation(aDestPoint);
++
++    RefPtr<ID2D1ImageBrush> imageBrush;
++    mDC->CreateImageBrush(image,
++                          D2D1::ImageBrushProperties(D2DRect(aSourceRect)),
++                          D2D1::BrushProperties(aOptions.mAlpha, D2DMatrix(mat)),
++                          getter_AddRefs(imageBrush));
++    mDC->FillRectangle(D2D1::RectF(aDestPoint.x, aDestPoint.y,
++                                   aDestPoint.x + aSourceRect.width,
++                                   aDestPoint.y + aSourceRect.height),
++                       imageBrush);
++  }
+ 
+   FinalizeDrawing(aOptions.mCompositionOp, ColorPattern(Color()));
+ }
+ 
+ void DrawTargetD2D1::DrawSurfaceWithShadow(SourceSurface *aSurface,
+                                            const Point &aDest,
+                                            const Color &aColor,
+                                            const Point &aOffset, Float aSigma,
+diff --git a/layout/svg/nsFilterInstance.cpp b/layout/svg/nsFilterInstance.cpp
+--- a/layout/svg/nsFilterInstance.cpp
++++ b/layout/svg/nsFilterInstance.cpp
+@@ -53,17 +53,17 @@ static UniquePtr<UserSpaceMetrics> UserS
+     return MakeUnique<SVGElementMetrics>(element);
+   }
+   return MakeUnique<NonSVGFrameUserSpaceMetrics>(aFrame);
+ }
+ 
+ void nsFilterInstance::PaintFilteredFrame(
+     nsIFrame* aFilteredFrame, gfxContext* aCtx,
+     nsSVGFilterPaintCallback* aPaintCallback, const nsRegion* aDirtyArea,
+-    imgDrawingParams& aImgParams) {
++    imgDrawingParams& aImgParams, float aOpacity) {
+   auto& filterChain = aFilteredFrame->StyleEffects()->mFilters;
+   UniquePtr<UserSpaceMetrics> metrics =
+       UserSpaceMetricsForFrame(aFilteredFrame);
+ 
+   gfxContextMatrixAutoSaveRestore autoSR(aCtx);
+   gfxSize scaleFactors = aCtx->CurrentMatrixDouble().ScaleFactors(true);
+   if (scaleFactors.IsEmpty()) {
+     return;
+@@ -84,17 +84,17 @@ void nsFilterInstance::PaintFilteredFram
+ 
+   // Hardcode InputIsTainted to true because we don't want JS to be able to
+   // read the rendered contents of aFilteredFrame.
+   nsFilterInstance instance(aFilteredFrame, aFilteredFrame->GetContent(),
+                             *metrics, filterChain, /* InputIsTainted */ true,
+                             aPaintCallback, scaleMatrixInDevUnits, aDirtyArea,
+                             nullptr, nullptr, nullptr);
+   if (instance.IsInitialized()) {
+-    instance.Render(aCtx, aImgParams);
++    instance.Render(aCtx, aImgParams, aOpacity);
+   }
+ }
+ 
+ nsRegion nsFilterInstance::GetPostFilterDirtyArea(
+     nsIFrame* aFilteredFrame, const nsRegion& aPreFilterDirtyRegion) {
+   if (aPreFilterDirtyRegion.IsEmpty()) {
+     return nsRegion();
+   }
+@@ -456,17 +456,18 @@ void nsFilterInstance::BuildSourceImage(
+ 
+   mPaintCallback->Paint(*ctx, mTargetFrame, mPaintTransform, &dirty,
+                         aImgParams);
+ 
+   mSourceGraphic.mSourceSurface = offscreenDT->Snapshot();
+   mSourceGraphic.mSurfaceRect = neededRect;
+ }
+ 
+-void nsFilterInstance::Render(gfxContext* aCtx, imgDrawingParams& aImgParams) {
++void nsFilterInstance::Render(gfxContext* aCtx, imgDrawingParams& aImgParams,
++                              float aOpacity) {
+   MOZ_ASSERT(mTargetFrame, "Need a frame for rendering");
+ 
+   if (mPrimitiveDescriptions.IsEmpty()) {
+     // An filter without any primitive. Treat it as success and paint nothing.
+     return;
+   }
+ 
+   nsIntRect filterRect =
+@@ -484,17 +485,17 @@ void nsFilterInstance::Render(gfxContext
+   BuildSourceImage(aCtx->GetDrawTarget(), aImgParams);
+   BuildSourcePaints(aImgParams);
+ 
+   FilterSupport::RenderFilterDescription(
+       aCtx->GetDrawTarget(), mFilterDescription, IntRectToRect(filterRect),
+       mSourceGraphic.mSourceSurface, mSourceGraphic.mSurfaceRect,
+       mFillPaint.mSourceSurface, mFillPaint.mSurfaceRect,
+       mStrokePaint.mSourceSurface, mStrokePaint.mSurfaceRect, mInputImages,
+-      Point(0, 0));
++      Point(0, 0), DrawOptions(aOpacity));
+ }
+ 
+ nsRegion nsFilterInstance::ComputePostFilterDirtyRegion() {
+   if (mPreFilterDirtyRegion.IsEmpty() || mPrimitiveDescriptions.IsEmpty()) {
+     return nsRegion();
+   }
+ 
+   nsIntRegion resultChangeRegion = FilterSupport::ComputeResultChangeRegion(
+diff --git a/layout/svg/nsFilterInstance.h b/layout/svg/nsFilterInstance.h
+--- a/layout/svg/nsFilterInstance.h
++++ b/layout/svg/nsFilterInstance.h
+@@ -81,17 +81,18 @@ class nsFilterInstance {
+    * Paint the given filtered frame.
+    * @param aDirtyArea The area than needs to be painted, in aFilteredFrame's
+    *   frame space (i.e. relative to its origin, the top-left corner of its
+    *   border box).
+    */
+   static void PaintFilteredFrame(nsIFrame* aFilteredFrame, gfxContext* aCtx,
+                                  nsSVGFilterPaintCallback* aPaintCallback,
+                                  const nsRegion* aDirtyArea,
+-                                 imgDrawingParams& aImgParams);
++                                 imgDrawingParams& aImgParams,
++                                 float aOpacity = 1.0f);
+ 
+   /**
+    * Returns the post-filter area that could be dirtied when the given
+    * pre-filter area of aFilteredFrame changes.
+    * @param aPreFilterDirtyRegion The pre-filter area of aFilteredFrame that has
+    *   changed, relative to aFilteredFrame, in app units.
+    */
+   static nsRegion GetPostFilterDirtyArea(nsIFrame* aFilteredFrame,
+@@ -160,17 +161,18 @@ class nsFilterInstance {
+   bool IsInitialized() const { return mInitialized; }
+ 
+   /**
+    * Draws the filter output into aDrawTarget. The area that
+    * needs to be painted must have been specified before calling this method
+    * by passing it as the aPostFilterDirtyRegion argument to the
+    * nsFilterInstance constructor.
+    */
+-  void Render(gfxContext* aCtx, imgDrawingParams& aImgParams);
++  void Render(gfxContext* aCtx, imgDrawingParams& aImgParams,
++              float aOpacity = 1.0f);
+ 
+   const FilterDescription& ExtractDescriptionAndAdditionalImages(
+       nsTArray<RefPtr<SourceSurface>>& aOutAdditionalImages) {
+     mInputImages.SwapElements(aOutAdditionalImages);
+     return mFilterDescription;
+   }
+ 
+   /**
+diff --git a/layout/svg/nsSVGIntegrationUtils.cpp b/layout/svg/nsSVGIntegrationUtils.cpp
+--- a/layout/svg/nsSVGIntegrationUtils.cpp
++++ b/layout/svg/nsSVGIntegrationUtils.cpp
+@@ -1024,32 +1024,23 @@ void nsSVGIntegrationUtils::PaintFilter(
+     return;
+   }
+ 
+   gfxContext& context = aParams.ctx;
+ 
+   gfxContextAutoSaveRestore autoSR(&context);
+   EffectOffsets offsets = MoveContextOriginToUserSpace(firstFrame, aParams);
+ 
+-  if (opacity != 1.0f) {
+-    context.PushGroupForBlendBack(gfxContentType::COLOR_ALPHA, opacity, nullptr,
+-                                  Matrix());
+-  }
+-
+   /* Paint the child and apply filters */
+   RegularFramePaintCallback callback(aParams.builder, aParams.layerManager,
+                                      offsets.offsetToUserSpaceInDevPx);
+   nsRegion dirtyRegion = aParams.dirtyRect - offsets.offsetToBoundingBox;
+ 
+   nsFilterInstance::PaintFilteredFrame(frame, &context, &callback, &dirtyRegion,
+-                                       aParams.imgParams);
+-
+-  if (opacity != 1.0f) {
+-    context.PopGroupAndBlend();
+-  }
++                                       aParams.imgParams, opacity);
+ }
+ 
+ class PaintFrameCallback : public gfxDrawingCallback {
+  public:
+   PaintFrameCallback(nsIFrame* aFrame, const nsSize aPaintServerSize,
+                      const IntSize aRenderSize, uint32_t aFlags)
+       : mFrame(aFrame),
+         mPaintServerSize(aPaintServerSize),

+ 173 - 0
rel-257/ian/patches/1376756-63a1.patch

@@ -0,0 +1,173 @@
+# HG changeset patch
+# User Samuel Thibault <samuel.thibault>
+# Date 1530065460 -10800
+#      Wed Jun 27 05:11:00 2018 +0300
+# Branch THUNDERBIRD_60_VERBRANCH
+# Node ID feccfbf2922833dbd8ff0a3f1a9966ad63561c1e
+# Parent  ecb8bcfe3e5edd70e8d428709366227abc11b0b1
+Bug 1376756 - gtk: while drawing nsTreeBodyFrame, fetch current row attributes for proper style rendering. r=karlt a=jorgk DONTBUILD
+
+diff --git a/layout/xul/tree/nsTreeBodyFrame.h b/layout/xul/tree/nsTreeBodyFrame.h
+--- a/layout/xul/tree/nsTreeBodyFrame.h
++++ b/layout/xul/tree/nsTreeBodyFrame.h
+@@ -192,16 +192,22 @@ class nsTreeBodyFrame final : public nsL
+   nsITreeBoxObject* GetTreeBoxObject() const { return mTreeBoxObject; }
+ 
+   // Get the base element, <tree> or <select>
+   mozilla::dom::Element* GetBaseElement();
+ 
+   bool GetVerticalOverflow() const { return mVerticalOverflow; }
+   bool GetHorizontalOverflow() const { return mHorizontalOverflow; }
+ 
++  // This returns the property array where atoms are stored for style during
++  // draw, whether the row currently being drawn is selected, hovered, etc.
++  const mozilla::AtomArray& GetPropertyArrayForCurrentDrawingItem() {
++    return mScratchArray;
++  }
++
+  protected:
+   friend class nsOverflowChecker;
+ 
+   // This method paints a specific column background of the tree.
+   ImgDrawResult PaintColumn(nsTreeColumn* aColumn, const nsRect& aColumnRect,
+                             nsPresContext* aPresContext,
+                             gfxContext& aRenderingContext,
+                             const nsRect& aDirtyRect);
+diff --git a/widget/gtk/gtk2drawing.c b/widget/gtk/gtk2drawing.c
+--- a/widget/gtk/gtk2drawing.c
++++ b/widget/gtk/gtk2drawing.c
+@@ -1666,17 +1666,20 @@ static gint moz_gtk_treeview_expander_pa
+   ensure_tree_view_widget();
+   gtk_widget_set_direction(gTreeViewWidget, direction);
+ 
+   style = gTreeViewWidget->style;
+ 
+   /* Because the frame we get is of the entire treeview, we can't get the
+    * precise event state of one expander, thus rendering hover and active
+    * feedback useless. */
+-  state_type = state->disabled ? GTK_STATE_INSENSITIVE : GTK_STATE_NORMAL;
++  state_type = state->disabled ? GTK_STATE_INSENSITIVE :
++               state->inHover  ? GTK_STATE_PRELIGHT :
++               state->selected ? GTK_STATE_SELECTED :
++                                 GTK_STATE_NORMAL;
+ 
+   TSOffsetStyleGCs(style, rect->x, rect->y);
+   gtk_paint_expander(style, drawable, state_type, cliprect, gTreeViewWidget,
+                      "treeview", rect->x + rect->width / 2,
+                      rect->y + rect->height / 2, expander_state);
+ 
+   return MOZ_GTK_SUCCESS;
+ }
+diff --git a/widget/gtk/gtk3drawing.cpp b/widget/gtk/gtk3drawing.cpp
+--- a/widget/gtk/gtk3drawing.cpp
++++ b/widget/gtk/gtk3drawing.cpp
+@@ -1229,16 +1229,23 @@ static gint moz_gtk_treeview_expander_pa
+                                             GtkExpanderStyle expander_state,
+                                             GtkTextDirection direction) {
+   /* Because the frame we get is of the entire treeview, we can't get the
+    * precise event state of one expander, thus rendering hover and active
+    * feedback useless. */
+   GtkStateFlags state_flags =
+       state->disabled ? GTK_STATE_FLAG_INSENSITIVE : GTK_STATE_FLAG_NORMAL;
+ 
++  if (state->inHover)
++      state_flags =
++          static_cast<GtkStateFlags>(state_flags|GTK_STATE_FLAG_PRELIGHT);
++  if (state->selected)
++      state_flags =
++          static_cast<GtkStateFlags>(state_flags|GTK_STATE_FLAG_SELECTED);
++
+   /* GTK_STATE_FLAG_ACTIVE controls expanded/colapsed state rendering
+    * in gtk_render_expander()
+    */
+   if (expander_state == GTK_EXPANDER_EXPANDED)
+     state_flags =
+         static_cast<GtkStateFlags>(state_flags | checkbox_check_state);
+   else
+     state_flags =
+diff --git a/widget/gtk/gtkdrawing.h b/widget/gtk/gtkdrawing.h
+--- a/widget/gtk/gtkdrawing.h
++++ b/widget/gtk/gtkdrawing.h
+@@ -18,16 +18,17 @@
+ #include <gdk/gdk.h>
+ #include <gtk/gtk.h>
+ #include <algorithm>
+ 
+ /*** type definitions ***/
+ typedef struct {
+   guint8 active;
+   guint8 focused;
++  guint8 selected;
+   guint8 inHover;
+   guint8 disabled;
+   guint8 isDefault;
+   guint8 canDefault;
+   /* The depressed state is for buttons which remain active for a longer period:
+    * activated toggle buttons or buttons showing a popup menu. */
+   guint8 depressed;
+   gint32 curpos; /* curpos and maxpos are used for scrollbars */
+diff --git a/widget/gtk/nsNativeThemeGTK.cpp b/widget/gtk/nsNativeThemeGTK.cpp
+--- a/widget/gtk/nsNativeThemeGTK.cpp
++++ b/widget/gtk/nsNativeThemeGTK.cpp
+@@ -14,16 +14,17 @@
+ #include "nsIFrame.h"
+ #include "nsIPresShell.h"
+ #include "nsIContent.h"
+ #include "nsViewManager.h"
+ #include "nsNameSpaceManager.h"
+ #include "nsGfxCIID.h"
+ #include "nsTransform2D.h"
+ #include "nsMenuFrame.h"
++#include "tree/nsTreeBodyFrame.h"
+ #include "prlink.h"
+ #include "nsGkAtoms.h"
+ #include "nsAttrValueInlines.h"
+ 
+ #include "mozilla/dom/HTMLInputElement.h"
+ #include "mozilla/EventStates.h"
+ #include "mozilla/Services.h"
+ 
+@@ -255,16 +256,17 @@ bool nsNativeThemeGTK::GetGtkWidgetAndSt
+       stateFrame = aFrame = aFrame->GetParent();
+     }
+ 
+     EventStates eventState = GetContentState(stateFrame, aWidgetType);
+ 
+     aState->disabled = IsDisabled(aFrame, eventState) || IsReadOnly(aFrame);
+     aState->active = eventState.HasState(NS_EVENT_STATE_ACTIVE);
+     aState->focused = eventState.HasState(NS_EVENT_STATE_FOCUS);
++    aState->selected = FALSE;
+     aState->inHover = eventState.HasState(NS_EVENT_STATE_HOVER);
+     aState->isDefault = IsDefaultButton(aFrame);
+     aState->canDefault = FALSE;  // XXX fix me
+     aState->depressed = FALSE;
+ 
+     if (aWidgetType == NS_THEME_FOCUS_OUTLINE) {
+       aState->disabled = FALSE;
+       aState->active = FALSE;
+@@ -276,16 +278,25 @@ bool nsNativeThemeGTK::GetGtkWidgetAndSt
+       aState->depressed = TRUE;  // see moz_gtk_entry_paint()
+     } else if (aWidgetType == NS_THEME_BUTTON ||
+                aWidgetType == NS_THEME_TOOLBARBUTTON ||
+                aWidgetType == NS_THEME_DUALBUTTON ||
+                aWidgetType == NS_THEME_TOOLBARBUTTON_DROPDOWN ||
+                aWidgetType == NS_THEME_MENULIST ||
+                aWidgetType == NS_THEME_MENULIST_BUTTON) {
+       aState->active &= aState->inHover;
++    } else if (aWidgetType == NS_THEME_TREETWISTY ||
++               aWidgetType == NS_THEME_TREETWISTYOPEN) {
++      nsTreeBodyFrame *treeBodyFrame = do_QueryFrame(aFrame);
++      if (treeBodyFrame) {
++        const mozilla::AtomArray& atoms =
++          treeBodyFrame->GetPropertyArrayForCurrentDrawingItem();
++        aState->selected = atoms.Contains(nsGkAtoms::selected);
++        aState->inHover = atoms.Contains(nsGkAtoms::hover);
++      }
+     }
+ 
+     if (IsFrameContentNodeInNamespace(aFrame, kNameSpaceID_XUL)) {
+       // For these widget types, some element (either a child or parent)
+       // actually has element focus, so we check the focused attribute
+       // to see whether to draw in the focused state.
+       if (aWidgetType == NS_THEME_NUMBER_INPUT ||
+           aWidgetType == NS_THEME_TEXTFIELD ||

+ 57 - 0
rel-257/ian/patches/1394825-67a1.patch

@@ -0,0 +1,57 @@
+# HG changeset patch
+# User Emilio Cobos Álvarez <emilio@crisal.io>
+# Date 1549767373 0
+# Node ID d6a02521683879d28e94e2912c09fcec1645d2f3
+# Parent  28f5b496307d590bcafa0514135872b4886ece2e
+Bug 1394825 - Update minimum clang version to 4.0. r=glandium
+
+libclang 3.9 has a bug that makes bindgen unable to distinguish some typedefs
+from the underlying type, which matters for bug 1523071.
+
+We have had quite a few workarounds for this bug and I don't really want to add
+more, since in this case it is non-trivial. I think requiring libclang 4.0+ is
+reasonable at this point.
+
+Of the distros that can't build Firefox out of the box with clang, dropping support
+for clang 3.9 would only break Ubuntu 14.04 LTS, which support ends April 2019,
+right before we release 67.
+
+Differential Revision: https://phabricator.services.mozilla.com/D18889
+
+diff --git a/build/build-clang/clang-3.9-linux64.json b/build/build-clang/clang-4.0-linux64.json
+rename from build/build-clang/clang-3.9-linux64.json
+rename to build/build-clang/clang-4.0-linux64.json
+--- a/build/build-clang/clang-3.9-linux64.json
++++ b/build/build-clang/clang-4.0-linux64.json
+@@ -1,24 +1,18 @@
+ {
+-    "llvm_revision": "289595",
++    "llvm_revision": "305830",
+     "stages": "3",
+     "build_libcxx": true,
+     "build_type": "Release",
+     "assertions": false,
+-    "llvm_repo": "https://llvm.org/svn/llvm-project/llvm/tags/RELEASE_391/final",
+-    "clang_repo": "https://llvm.org/svn/llvm-project/cfe/tags/RELEASE_391/final",
+-    "compiler_repo": "https://llvm.org/svn/llvm-project/compiler-rt/tags/RELEASE_391/final",
+-    "libcxx_repo": "https://llvm.org/svn/llvm-project/libcxx/tags/RELEASE_391/final",
+-    "libcxxabi_repo": "https://llvm.org/svn/llvm-project/libcxxabi/tags/RELEASE_391/final",
++    "llvm_repo": "https://llvm.org/svn/llvm-project/llvm/tags/RELEASE_401/final",
++    "clang_repo": "https://llvm.org/svn/llvm-project/cfe/tags/RELEASE_401/final",
++    "compiler_repo": "https://llvm.org/svn/llvm-project/compiler-rt/tags/RELEASE_401/final",
++    "libcxx_repo": "https://llvm.org/svn/llvm-project/libcxx/tags/RELEASE_401/final",
++    "libcxxabi_repo": "https://llvm.org/svn/llvm-project/libcxxabi/tags/RELEASE_401/final",
+     "python_path": "/usr/bin/python2.7",
+     "gcc_dir": "/builds/worker/workspace/build/src/gcc",
+     "cc": "/builds/worker/workspace/build/src/gcc/bin/gcc",
+     "cxx": "/builds/worker/workspace/build/src/gcc/bin/g++",
+     "as": "/builds/worker/workspace/build/src/gcc/bin/gcc",
+-    "patches": [
+-      "llvm-debug-frame.patch",
+-      "r277806.patch",
+-      "r285657.patch",
+-      "r289565-for-3.9.patch",
+-      "r313872.patch"
+-    ]
++    "patches": []
+ }

+ 95 - 0
rel-257/ian/patches/1397263-1-64a1.patch

@@ -0,0 +1,95 @@
+# HG changeset patch
+# User Ted Mielczarek <ted@mielczarek.org>
+# Date 1538612969 14400
+# Node ID 73a4e7ed19f3447370cbe5fa7b7b30fc1a41710b
+# Parent  5de362d1bd072dc5e69ae2bf57d91b079d2ae897
+Bug 1397263 - move MIDL checks to moz.configure; r=glandium
+
+diff --git a/old-configure.in b/old-configure.in
+--- a/old-configure.in
++++ b/old-configure.in
+@@ -151,17 +151,16 @@ dnl ====================================
+ 
+ WINVER=601
+ 
+ case "$target" in
+ *-mingw*)
+     if test "$GCC" != "yes"; then
+         # Check to see if we are really running in a msvc environemnt
+         _WIN32_MSVC=1
+-        AC_CHECK_PROGS(MIDL, midl)
+ 
+         # Make sure compilers are valid
+         CFLAGS="$CFLAGS -TC -nologo"
+         CXXFLAGS="$CXXFLAGS -TP -nologo"
+         AC_LANG_SAVE
+         AC_LANG_C
+         AC_TRY_COMPILE([#include <stdio.h>],
+             [ printf("Hello World\n"); ],,
+@@ -311,17 +310,16 @@ case "$target" in
+                 "$_WINDRES_MINOR_VERSION" -lt "$WINDRES_MINOR_VERSION" -o \
+                 "$_WINDRES_MAJOR_VERSION" -eq "$WINDRES_MAJOR_VERSION" -a \
+                 "$_WINDRES_MINOR_VERSION" -eq "$WINDRES_MINOR_VERSION" -a \
+                 "$_WINDRES_RELEASE_VERSION" -lt "$WINDRES_RELEASE_VERSION"
+         then
+             AC_MSG_ERROR([windres version $WINDRES_VERSION or higher is required to build.])
+         fi
+ 
+-        AC_CHECK_PROGS(MIDL, $target-widl widl)
+         if test -n "$MIDL"; then
+             case "$target" in
+             i*86-*)
+                 MIDL_FLAGS="$MIDL_FLAGS --win32 -m32"
+                 ;;
+             x86_64-*)
+                 MIDL_FLAGS="$MIDL_FLAGS --win64 -m64"
+                 ;;
+diff --git a/toolkit/moz.configure b/toolkit/moz.configure
+--- a/toolkit/moz.configure
++++ b/toolkit/moz.configure
+@@ -1217,16 +1217,45 @@ option('--enable-proxy-bypass-protection
+ 
+ @depends_if('--enable-proxy-bypass-protection')
+ def proxy_bypass_protection(_):
+     return True
+ 
+ set_config('MOZ_PROXY_BYPASS_PROTECTION', proxy_bypass_protection)
+ set_define('MOZ_PROXY_BYPASS_PROTECTION', proxy_bypass_protection)
+ 
++# MIDL
++# ==============================================================
++
++@depends(c_compiler, toolchain_prefix)
++def midl_names(c_compiler, toolchain_prefix):
++    if c_compiler and c_compiler.type in ['gcc', 'clang']:
++        # mingw
++        widl = ('widl', )
++        if toolchain_prefix:
++            prefixed = tuple('%s%s' % (p, 'widl') for p in toolchain_prefix)
++            widl = prefixed + widl
++        return widl
++
++    return ('midl',)
++
++@depends(target, '--enable-compile-environment')
++def check_for_midl(target, compile_environment):
++    if target.os != 'WINNT':
++        return
++
++    if compile_environment:
++        return True
++
++
++midl = check_prog('MIDL', midl_names, when=check_for_midl, allow_missing=True)
++
++# Needed until we move MIDL_FLAGS and --disable-accessibility from old-configure
++add_old_configure_assignment('MIDL', midl)
++
+ # Addon signing
+ # ==============================================================
+ 
+ option('--with-unsigned-addon-scopes',
+        nargs='+', choices=('app', 'system'),
+        help='Addon scopes where signature is not required')
+ 
+ @depends('--with-unsigned-addon-scopes')

+ 459 - 0
rel-257/ian/patches/1397263-2-64a1.patch

@@ -0,0 +1,459 @@
+# HG changeset patch
+# User Nathan Froyd <froydnj@mozilla.com>
+# Date 1538612969 14400
+# Node ID b4dec9b774a82ccbe834eeb9727186e793699e97
+# Parent  30656c817ea7b3145ddc524b94463d81eda0e256
+Bug 1397263 - move AS checks to toolchain.configure; r=glandium
+
+This is a fairly straightforward port of the AS tool checks from old-configure
+to toolchain.configure. AS is a little quirky in that we currently do a
+normal-looking check for it, but then override that value to be the C compiler
+for non-Windows builds, and ml[64]/armasm64 for Windows builds.
+
+After migrating those checks, the only things left in the MOZ_DEFAULT_COMPILER
+macro in compiler-opts.m4 were some unused bits, so I removed them:
+* Setting of CPP/CXXCPP, which are set in toolchain.configure now
+* Setting HOST_LDFLAGS to empty, which doesn't seem particularly useful.
+
+There was also a quirky old test that the assembler was ml[64] when js-ctypes
+is enabled that I removed, I don't think it provides any value since this
+patch will ensure that we're using the right assembler for Windows builds.
+
+diff --git a/build/autoconf/compiler-opts.m4 b/build/autoconf/compiler-opts.m4
+--- a/build/autoconf/compiler-opts.m4
++++ b/build/autoconf/compiler-opts.m4
+@@ -1,44 +1,14 @@
+ dnl This Source Code Form is subject to the terms of the Mozilla Public
+ dnl License, v. 2.0. If a copy of the MPL was not distributed with this
+ dnl file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ 
+ dnl Add compiler specific options
+ 
+-AC_DEFUN([MOZ_DEFAULT_COMPILER],
+-[
+-dnl Default to MSVC for win32 and gcc-4.2 for darwin
+-dnl ==============================================================
+-if test -z "$CROSS_COMPILE"; then
+-case "$target" in
+-*-mingw*)
+-    if test -z "$CPP"; then CPP="$CC -E -nologo"; fi
+-    if test -z "$CXXCPP"; then CXXCPP="$CXX -TP -E -nologo"; ac_cv_prog_CXXCPP="$CXXCPP"; fi
+-    if test -z "$AS"; then
+-        case "${target_cpu}" in
+-        i*86)
+-            AS=ml;
+-            ;;
+-        x86_64)
+-            AS=ml64;
+-            ;;
+-        esac
+-    fi
+-    if test -z "$MIDL"; then MIDL=midl; fi
+-
+-    # need override this flag since we don't use $(LDFLAGS) for this.
+-    if test -z "$HOST_LDFLAGS" ; then
+-        HOST_LDFLAGS=" "
+-    fi
+-    ;;
+-esac
+-fi
+-])
+-
+ dnl ============================================================================
+ dnl C++ rtti
+ dnl We don't use it in the code, but it can be usefull for debugging, so give
+ dnl the user the option of enabling it.
+ dnl ============================================================================
+ AC_DEFUN([MOZ_RTTI],
+ [
+ MOZ_ARG_ENABLE_BOOL(cpp-rtti,
+diff --git a/build/moz.configure/toolchain.configure b/build/moz.configure/toolchain.configure
+--- a/build/moz.configure/toolchain.configure
++++ b/build/moz.configure/toolchain.configure
+@@ -774,16 +774,43 @@ def default_cxx_compilers(c_compiler, ot
+             return (os.path.join(dir, file.replace('clang', 'clang++')),)
+ 
+         return (c_compiler.compiler,)
+ 
+     return default_cxx_compilers
+ 
+ 
+ @template
++def provided_program(env_var):
++    '''Template handling cases where a program can be specified either as a
++    path or as a path with applicable arguments.
++    '''
++
++    @depends_if(env_var)
++    @imports(_from='itertools', _import='takewhile')
++    @imports(_from='mozbuild.shellutil', _import='split', _as='shell_split')
++    def provided(cmd):
++        # Assume the first dash-prefixed item (and any subsequent items) are
++        # command-line options, the item before the dash-prefixed item is
++        # the program we're looking for, and anything before that is a wrapper
++        # of some kind (e.g. sccache).
++        cmd = shell_split(cmd[0])
++
++        without_flags = list(takewhile(lambda x: not x.startswith('-'), cmd))
++
++        return namespace(
++            wrapper=without_flags[:-1],
++            program=without_flags[-1],
++            flags=cmd[len(without_flags):],
++        )
++
++    return provided
++
++
++@template
+ def compiler(language, host_or_target, c_compiler=None, other_compiler=None,
+              other_c_compiler=None):
+     '''Template handling the generic base checks for the compiler for the
+     given `language` on the given platform (`host_or_target`).
+     `host_or_target` is either `host` or `target` (the @depends functions
+     from init.configure.
+     When the language is 'C++', `c_compiler` is the result of the `compiler`
+     template for the language 'C' for the same `host_or_target`.
+@@ -818,41 +845,24 @@ def compiler(language, host_or_target, c
+     }[language]()
+ 
+     what = 'the %s %s compiler' % (host_or_target_str, language)
+ 
+     option(env=var, nargs=1, help='Path to %s' % what)
+ 
+     # Handle the compiler given by the user through one of the CC/CXX/HOST_CC/
+     # HOST_CXX variables.
+-    @depends_if(var)
+-    @imports(_from='itertools', _import='takewhile')
+-    @imports(_from='mozbuild.shellutil', _import='split', _as='shell_split')
+-    def provided_compiler(cmd):
+-        # Historically, the compiler variables have contained more than the
+-        # path to the compiler itself. So for backwards compatibility, try to
+-        # find what is what in there, assuming the first dash-prefixed item is
+-        # a compiler option, the item before that is the compiler, and anything
+-        # before that is a compiler wrapper.
+-        cmd = shell_split(cmd[0])
+-
+-        without_flags = list(takewhile(lambda x: not x.startswith('-'), cmd))
+-
+-        return namespace(
+-            wrapper=without_flags[:-1],
+-            compiler=without_flags[-1],
+-            flags=cmd[len(without_flags):],
+-        )
++    provided_compiler = provided_program(var)
+ 
+     # Normally, we'd use `var` instead of `_var`, but the interaction with
+     # old-configure complicates things, and for now, we a) can't take the plain
+     # result from check_prog as CC/CXX/HOST_CC/HOST_CXX and b) have to let
+     # old-configure AC_SUBST it (because it's autoconf doing it, not us)
+     compiler = check_prog('_%s' % var, what=what, progs=default_compilers,
+-                          input=provided_compiler.compiler,
++                          input=provided_compiler.program,
+                           paths=toolchain_search_path)
+ 
+     @depends(compiler, provided_compiler, compiler_wrapper, host_or_target)
+     @checking('whether %s can be used' % what, lambda x: bool(x))
+     @imports(_from='mozbuild.shellutil', _import='quote')
+     def valid_compiler(compiler, provided_compiler, compiler_wrapper,
+                        host_or_target):
+         wrapper = list(compiler_wrapper or ())
+@@ -1570,16 +1580,81 @@ def select_linker(linker, c_compiler, de
+     )
+ 
+ 
+ set_config('LD_IS_BFD', depends(select_linker.KIND)
+            (lambda x: x == 'bfd' or None))
+ set_config('LINKER_LDFLAGS', select_linker.LINKER_FLAG)
+ 
+ 
++# Assembler detection
++# ==============================================================
++
++js_option(env='AS', nargs=1, help='Path to the assembler')
++
++@depends(target, c_compiler)
++def as_info(target, c_compiler):
++    if c_compiler.type in ('msvc', 'clang-cl'):
++        ml = {
++            'x86': 'ml',
++            'x86_64': 'ml64',
++            'aarch64': 'armasm64.exe',
++        }.get(target.cpu)
++        return namespace(
++            type='masm',
++            names=(ml, )
++        )
++    # When building with anything but MSVC, we just use the C compiler as the assembler.
++    return namespace(
++        type='gcc',
++        names=(c_compiler.compiler, )
++    )
++
++# One would expect the assembler to be specified merely as a program.  But in
++# cases where the assembler is passed down into js/, it can be specified in
++# the same way as CC: a program + a list of argument flags.  We might as well
++# permit the same behavior in general, even though it seems somewhat unusual.
++# So we have to do the same sort of dance as we did above with
++# `provided_compiler`.
++provided_assembler = provided_program('AS')
++assembler = check_prog('_AS', input=provided_assembler.program,
++                       what='the assembler', progs=as_info.names)
++
++@depends(as_info, assembler, provided_assembler, c_compiler)
++def as_with_flags(as_info, assembler, provided_assembler, c_compiler):
++    if provided_assembler:
++        return provided_assembler.wrapper + \
++            [provided_assembler.program] + \
++            provided_assembler.flags
++
++    if as_info.type == 'masm':
++        return assembler
++
++    assert as_info.type == 'gcc'
++
++    # Need to add compiler wrappers and flags as appropriate.
++    return c_compiler.wrapper + [assembler] + c_compiler.flags
++
++
++add_old_configure_assignment('AS', as_with_flags)
++
++@depends(as_info, target)
++def as_dash_c_flag(as_info, target):
++    # armasm64 doesn't understand -c.
++    if as_info.type == 'masm' and target.cpu == 'aarch64':
++        return ''
++    else:
++        return '-c'
++
++
++set_config('AS_DASH_C_FLAG', as_dash_c_flag)
++
++# clang plugin handling
++# ==============================================================
++
+ js_option('--enable-clang-plugin', env='ENABLE_CLANG_PLUGIN',
+           help="Enable building with the mozilla clang plugin")
+ 
+ add_old_configure_assignment('ENABLE_CLANG_PLUGIN',
+                              depends_if('--enable-clang-plugin')(lambda _: True))
+ 
+ js_option('--enable-mozsearch-plugin', env='ENABLE_MOZSEARCH_PLUGIN',
+           help="Enable building with the mozsearch indexer plugin")
+diff --git a/js/src/old-configure.in b/js/src/old-configure.in
+--- a/js/src/old-configure.in
++++ b/js/src/old-configure.in
+@@ -58,18 +58,16 @@ dnl ====================================
+ MISSING_X=
+ 
+ dnl Initialize the Pthread test variables early so they can be
+ dnl  overridden by each platform.
+ dnl ========================================================
+ USE_PTHREADS=
+ _PTHREAD_LDFLAGS=""
+ 
+-MOZ_DEFAULT_COMPILER
+-
+ if test -z "$JS_STANDALONE"; then
+   autoconfmk=autoconf-js.mk
+ fi
+ AC_SUBST(autoconfmk)
+ 
+ if test -n "$JS_STANDALONE"; then
+   jsconfdefs=$_objdir/js/src/js-confdefs.h
+ else
+@@ -394,20 +392,17 @@ AC_SUBST(MOZJS_MAJOR_VERSION)
+ AC_SUBST(MOZJS_MINOR_VERSION)
+ AC_SUBST(MOZJS_PATCH_VERSION)
+ AC_SUBST(MOZJS_ALPHA)
+ 
+ 
+ dnl ========================================================
+ dnl set the defaults first
+ dnl ========================================================
+-AS_BIN=$AS
+ AR_EXTRACT='$(AR) x'
+-AS='$(CC)'
+-AS_DASH_C_FLAG='-c'
+ MOZ_USER_DIR=".mozilla"
+ 
+ MOZ_FIX_LINK_PATHS="-Wl,-rpath-link,${DIST}/bin -Wl,-rpath-link,${prefix}/lib"
+ 
+ dnl Configure platform-specific CPU architecture compiler options.
+ dnl ==============================================================
+ MOZ_ARCH_OPTS
+ 
+@@ -663,19 +658,16 @@ case "$target" in
+         MOZ_OPTIMIZE_FLAGS="-O2"
+ 
+         WIN32_CONSOLE_EXE_LDFLAGS=-mconsole
+         WIN32_GUI_EXE_LDFLAGS=-mwindows
+     else
+         TARGET_COMPILER_ABI=msvc
+         HOST_CC='$(CC)'
+         HOST_CXX='$(CXX)'
+-        if test "$AS_BIN"; then
+-            AS="$(basename "$AS_BIN")"
+-        fi
+         AR='lib'
+         AR_FLAGS='-NOLOGO -OUT:$@'
+         AR_EXTRACT=
+         RANLIB='echo not_ranlib'
+         STRIP='echo not_strip'
+         PKG_SKIP_STRIP=1
+         WIN32_SUBSYSTEM_VERSION=6.01
+         WIN32_CONSOLE_EXE_LDFLAGS=-SUBSYSTEM:CONSOLE,$WIN32_SUBSYSTEM_VERSION
+@@ -1685,25 +1677,16 @@ AC_SUBST_LIST(EDITLINE_LIBS)
+ 
+ dnl ========================================================
+ dnl =
+ dnl = Standalone module options
+ dnl =
+ dnl ========================================================
+ MOZ_ARG_HEADER(Standalone module options (Not for building Mozilla))
+ 
+-if test "$JS_HAS_CTYPES"; then
+-  dnl JS_HAS_CTYPES is defined by Python configure. This check remains
+-  dnl as long as determining $AS remains in old-configure.
+-  dnl Error out if we're on MSVC and MASM is unavailable.
+-  if test -n "$_MSC_VER" -a \( "$AS" != "ml.exe" -a "$AS" != "ml64.exe" \); then
+-    AC_MSG_ERROR([\"$AS\" is not a suitable assembler to build js-ctypes. If you are building with MS Visual Studio 8 Express, you may download the MASM 8.0 package, upgrade to Visual Studio 9 Express, or install the Vista SDK. Or do not use --enable-ctypes.])
+-  fi
+-fi
+-
+ dnl ========================================================
+ dnl =
+ dnl = Options for generating the shell as a script
+ dnl =
+ dnl ========================================================
+ 
+ MOZ_ARG_WITH_STRING(qemu-exe,
+ [  --with-qemu-exe=path   Use path as an arm emulator on host platforms],
+@@ -1718,19 +1701,17 @@ dnl ====================================
+ dnl =
+ dnl = Maintainer debug option (no --enable equivalent)
+ dnl =
+ dnl ========================================================
+ 
+ AC_SUBST(AR)
+ AC_SUBST(AR_FLAGS)
+ AC_SUBST(AR_EXTRACT)
+-AC_SUBST(AS)
+ AC_SUBST_LIST(ASFLAGS)
+-AC_SUBST(AS_DASH_C_FLAG)
+ AC_SUBST(RC)
+ AC_SUBST(RCFLAGS)
+ AC_SUBST(WINDRES)
+ AC_SUBST(IMPLIB)
+ AC_SUBST(FILTER)
+ AC_SUBST_LIST(MOZ_DEBUG_LDFLAGS)
+ AC_SUBST(WARNINGS_AS_ERRORS)
+ AC_SUBST(LIBICONV)
+diff --git a/old-configure.in b/old-configure.in
+--- a/old-configure.in
++++ b/old-configure.in
+@@ -73,18 +73,16 @@ dnl ====================================
+ MISSING_X=
+ 
+ dnl Initialize the Pthread test variables early so they can be
+ dnl  overridden by each platform.
+ dnl ========================================================
+ MOZ_USE_PTHREADS=
+ _PTHREAD_LDFLAGS=""
+ 
+-MOZ_DEFAULT_COMPILER
+-
+ if test "$COMPILE_ENVIRONMENT"; then
+     MOZ_ANDROID_NDK
+ fi # COMPILE_ENVIRONMENT
+ 
+ case "$target" in
+ *-android*|*-linuxandroid*)
+     AC_DEFINE(ANDROID)
+     ;;
+@@ -431,20 +429,17 @@ AC_PATH_XTRA
+ 
+ XCFLAGS="$X_CFLAGS"
+ 
+ fi # COMPILE_ENVIRONMENT
+ 
+ dnl ========================================================
+ dnl set the defaults first
+ dnl ========================================================
+-AS_BIN=$AS
+ AR_EXTRACT='$(AR) x'
+-AS='$(CC)'
+-AS_DASH_C_FLAG='-c'
+ MOZ_USER_DIR=".mozilla"
+ 
+ MOZ_FIX_LINK_PATHS="-Wl,-rpath-link,${DIST}/bin -Wl,-rpath-link,${prefix}/lib"
+ 
+ MOZ_FS_LAYOUT=unix
+ 
+ dnl Configure platform-specific CPU architecture compiler options.
+ dnl ==============================================================
+@@ -859,19 +854,16 @@ case "$target" in
+             # function thunks need to be generated for cross-DLL calls.
+             MOZ_FOLD_LIBS_FLAGS="-mnop-fun-dllimport"
+         else
+             # Silence problematic clang warnings
+             CXXFLAGS="$CXXFLAGS -Wno-incompatible-ms-struct"
+         fi
+     else
+         TARGET_COMPILER_ABI=msvc
+-        if test "$AS_BIN"; then
+-            AS="$(basename "$AS_BIN")"
+-        fi
+         AR='lib'
+         AR_FLAGS='-NOLOGO -OUT:$@'
+         AR_EXTRACT=
+         RANLIB='echo not_ranlib'
+         STRIP='echo not_strip'
+         PKG_SKIP_STRIP=1
+         WIN32_SUBSYSTEM_VERSION=6.01
+         WIN32_CONSOLE_EXE_LDFLAGS=-SUBSYSTEM:CONSOLE,$WIN32_SUBSYSTEM_VERSION
+@@ -4011,19 +4003,17 @@ dnl ====================================
+ dnl =
+ dnl = Maintainer debug option (no --enable equivalent)
+ dnl =
+ dnl ========================================================
+ 
+ AC_SUBST(AR)
+ AC_SUBST(AR_FLAGS)
+ AC_SUBST(AR_EXTRACT)
+-AC_SUBST(AS)
+ AC_SUBST_LIST(ASFLAGS)
+-AC_SUBST(AS_DASH_C_FLAG)
+ AC_SUBST(RC)
+ AC_SUBST(RCFLAGS)
+ AC_SUBST(WINDRES)
+ AC_SUBST(IMPLIB)
+ AC_SUBST(FILTER)
+ AC_SUBST(MOZ_AUTH_EXTENSION)
+ AC_SUBST(MOZ_PREF_EXTENSIONS)
+ AC_SUBST_LIST(MOZ_DEBUG_LDFLAGS)
+diff --git a/python/mozbuild/mozbuild/backend/tup.py b/python/mozbuild/mozbuild/backend/tup.py
+--- a/python/mozbuild/mozbuild/backend/tup.py
++++ b/python/mozbuild/mozbuild/backend/tup.py
+@@ -163,20 +163,17 @@ class BackendTupfile(object):
+             (sources['.s'], 'AS', 'ASFLAGS', as_dash_c, ''),
+             (sources['.cpp'], 'CXX', 'CXXFLAGS', '-c', ''),
+             (sources['.c'], 'CC', 'CFLAGS', '-c', ''),
+             (host_sources['.cpp'], 'HOST_CXX', 'HOST_CXXFLAGS', '-c', 'host_'),
+             (host_sources['.c'], 'HOST_CC', 'HOST_CFLAGS', '-c', 'host_'),
+         ]
+         for srcs, compiler, flags, dash_c, prefix in compilers:
+             for src in sorted(srcs):
+-                # AS can be set to $(CC), so we need to call expand_variables on
+-                # the compiler to get the real value.
+-                compiler_value = self.variables.get(compiler, self.environment.substs[compiler])
+-                cmd = [expand_variables(compiler_value, self.environment.substs)]
++                cmd = [self.variables.get(compiler, self.environment.substs[compiler])]
+                 cmd.extend(shell_quote(f) for f in self.local_flags[flags])
+                 cmd.extend(shell_quote(f) for f in self.per_source_flags[src])
+                 cmd.extend([dash_c, '%f', '-o', '%o'])
+                 self.rule(
+                     cmd=cmd,
+                     inputs=[src],
+                     extra_inputs=extra_inputs,
+                     outputs=[prefix + '%B.o'],

+ 130 - 0
rel-257/ian/patches/1397263-3-64a1.patch

@@ -0,0 +1,130 @@
+# HG changeset patch
+# User Ted Mielczarek <ted@mielczarek.org>
+# Date 1538612969 14400
+# Node ID b3ad0438392892aeab8c88826d347164640ba602
+# Parent  d6c38aa3ef4396c0c92f6a76157c34e83a4d7ee2
+Bug 1397263 - move MIDL_FLAGS to toolkit/moz.configure; r=glandium
+
+This is a straightforward port of MIDL_FLAGS from old-configure to
+moz.configure. The only behavioral change is that it removes support for
+prepending MIDL_FLAGS from the environment in configure, but I doubt anyone
+uses that.
+
+diff --git a/old-configure.in b/old-configure.in
+--- a/old-configure.in
++++ b/old-configure.in
+@@ -256,26 +256,16 @@ case "$target" in
+             if test "$_LD_MAJOR_VERSION" != "$_CC_SUITE"; then
+                 AC_MSG_ERROR([The linker major version, $_LD_FULL_VERSION,  does not match the compiler suite version, $_CC_SUITE.])
+             fi
+             ;;
+         esac
+ 
+         INCREMENTAL_LINKER=1
+ 
+-        # Set midl environment
+-        case "$target" in
+-        i*86-*)
+-            MIDL_FLAGS="${MIDL_FLAGS} -env win32"
+-            ;;
+-        x86_64-*)
+-            MIDL_FLAGS="${MIDL_FLAGS} -env x64"
+-            ;;
+-        esac
+-
+         unset _MSVC_VER_FILTER
+ 
+         WRAP_STL_INCLUDES=1
+         STL_FLAGS="-I${DIST}/stl_wrappers"
+         CFLAGS="$CFLAGS -D_HAS_EXCEPTIONS=0"
+         CXXFLAGS="$CXXFLAGS -D_HAS_EXCEPTIONS=0"
+     else
+         # Check w32api version
+@@ -308,27 +298,16 @@ case "$target" in
+                 "$_WINDRES_MINOR_VERSION" -lt "$WINDRES_MINOR_VERSION" -o \
+                 "$_WINDRES_MAJOR_VERSION" -eq "$WINDRES_MAJOR_VERSION" -a \
+                 "$_WINDRES_MINOR_VERSION" -eq "$WINDRES_MINOR_VERSION" -a \
+                 "$_WINDRES_RELEASE_VERSION" -lt "$WINDRES_RELEASE_VERSION"
+         then
+             AC_MSG_ERROR([windres version $WINDRES_VERSION or higher is required to build.])
+         fi
+ 
+-        if test -n "$MIDL"; then
+-            case "$target" in
+-            i*86-*)
+-                MIDL_FLAGS="$MIDL_FLAGS --win32 -m32"
+-                ;;
+-            x86_64-*)
+-                MIDL_FLAGS="$MIDL_FLAGS --win64 -m64"
+-                ;;
+-            esac
+-        fi
+-
+         # strsafe.h on mingw uses macros for function deprecation that pollutes namespace
+         # causing problems with local implementations with the same name.
+         AC_DEFINE(STRSAFE_NO_DEPRECATE)
+     fi # !GNU_CC
+ 
+     AC_DEFINE_UNQUOTED(WINVER,0x$WINVER)
+     AC_DEFINE_UNQUOTED(_WIN32_WINNT,0x$WINVER)
+     # Require OS features provided by IE 8.0 (Win7)
+@@ -345,17 +324,16 @@ if test -n "$_WIN32_MSVC"; then
+     # Since we're skipping compiler and library checks, hard-code
+     # some facts here.
+     AC_DEFINE(HAVE_IO_H)
+     AC_DEFINE(HAVE_ISATTY)
+ fi
+ 
+ fi # COMPILE_ENVIRONMENT
+ 
+-AC_SUBST(MIDL_FLAGS)
+ AC_SUBST(_MSC_VER)
+ 
+ AC_SUBST(GNU_AS)
+ AC_SUBST(GNU_CC)
+ AC_SUBST(GNU_CXX)
+ 
+ AC_SUBST_LIST(STL_FLAGS)
+ AC_SUBST(WRAP_STL_INCLUDES)
+diff --git a/toolkit/moz.configure b/toolkit/moz.configure
+--- a/toolkit/moz.configure
++++ b/toolkit/moz.configure
+@@ -1243,18 +1243,37 @@ def check_for_midl(target, compile_envir
+         return
+ 
+     if compile_environment:
+         return True
+ 
+ 
+ midl = check_prog('MIDL', midl_names, when=check_for_midl, allow_missing=True)
+ 
+-# Needed until we move MIDL_FLAGS and --disable-accessibility from old-configure
++
++@depends(c_compiler, target, when=depends(midl, target)(lambda m, t: m and t.kernel == 'WINNT'))
++def midl_flags(c_compiler, target):
++    if c_compiler and c_compiler.type in ('msvc', 'clang-cl'):
++        env = {
++            'x86': 'win32',
++            'x86_64': 'x64',
++            'aarch64': 'arm64',
++        }[target.cpu]
++        return ['-env', env]
++
++    # mingw
++    return {
++        'x86': ['--win32', '-m32'],
++        'x86_64': ['--win64', '-m64'],
++    }[target.cpu]
++
++
++# Needed until we move --disable-accessibility from old-configure
+ add_old_configure_assignment('MIDL', midl)
++set_config('MIDL_FLAGS', midl_flags)
+ 
+ # Addon signing
+ # ==============================================================
+ 
+ option('--with-unsigned-addon-scopes',
+        nargs='+', choices=('app', 'system'),
+        help='Addon scopes where signature is not required')
+ 

+ 139 - 0
rel-257/ian/patches/1397263-4-64a1.patch

@@ -0,0 +1,139 @@
+# HG changeset patch
+# User Ted Mielczarek <ted@mielczarek.org>
+# Date 1538612969 14400
+# Node ID 23f384237f7320a5f5ef99f19781feb0227faf7e
+# Parent  24bf8ec3d58af1350e3d2408834a1e5cd222067d
+Bug 1397263 - move GNU_AS checks to toolchain.configure; r=glandium
+
+The GNU_AS check in old-configure depended on running with the value
+of $AS before it gets reset to just be the C compiler, which breaks when
+we move setting AS into moz.configure.
+
+This patch moves the GNU_AS check to toolchain.configure and changes it
+so that it works when the assembler is the C compiler.  We do have to
+fix things slightly for clang, because the previous check was
+succeeding, but not because of clang: it was detecting the presence of
+"GNU" in the output for GNU ld/gold and a message about the GNU GPL.
+
+diff --git a/build/autoconf/toolchain.m4 b/build/autoconf/toolchain.m4
+--- a/build/autoconf/toolchain.m4
++++ b/build/autoconf/toolchain.m4
+@@ -9,30 +9,23 @@ dnl However, theses checks are not neces
+ dnl the corresponding variables already, so just skip those tests
+ dnl entirely.
+ define([AC_PROG_CPP],[])
+ define([AC_PROG_CXXCPP],[])
+ define([AC_HEADER_STDC], [])
+ 
+ AC_DEFUN([MOZ_TOOL_VARIABLES],
+ [
+-GNU_AS=
+-
+ GNU_CC=
+ GNU_CXX=
+ if test "$CC_TYPE" = "gcc"; then
+     GNU_CC=1
+     GNU_CXX=1
+ fi
+ 
+-if test "`echo | $AS -o conftest.out -v 2>&1 | grep -c GNU`" != "0"; then
+-    GNU_AS=1
+-fi
+-rm -f conftest.out
+-
+ CLANG_CC=
+ CLANG_CXX=
+ CLANG_CL=
+ if test "$CC_TYPE" = "clang"; then
+     GNU_CC=1
+     GNU_CXX=1
+     CLANG_CC=1
+     CLANG_CXX=1
+diff --git a/build/moz.configure/toolchain.configure b/build/moz.configure/toolchain.configure
+--- a/build/moz.configure/toolchain.configure
++++ b/build/moz.configure/toolchain.configure
+@@ -1631,16 +1631,42 @@ def as_with_flags(as_info, assembler, pr
+     assert as_info.type == 'gcc'
+ 
+     # Need to add compiler wrappers and flags as appropriate.
+     return c_compiler.wrapper + [assembler] + c_compiler.flags
+ 
+ 
+ add_old_configure_assignment('AS', as_with_flags)
+ 
++
++@depends(assembler, c_compiler, extra_toolchain_flags)
++@imports('subprocess')
++@imports(_from='os', _import='devnull')
++def gnu_as(assembler, c_compiler, toolchain_flags):
++    # clang uses a compatible GNU assembler.
++    if c_compiler.type == 'clang':
++        return True
++
++    if c_compiler.type == 'gcc':
++        cmd = [assembler] + c_compiler.flags
++        if toolchain_flags:
++            cmd += toolchain_flags
++        cmd += ['-Wa,--version', '-c', '-o', devnull, '-x', 'assembler', '-']
++        # We don't actually have to provide any input on stdin, `Popen.communicate` will
++        # close the stdin pipe.
++        # clang will error if it uses its integrated assembler for this target,
++        # so handle failures gracefully.
++        if 'GNU' in check_cmd_output(*cmd, stdin=subprocess.PIPE, onerror=lambda: '').decode('utf-8'):
++            return True
++
++
++set_config('GNU_AS', gnu_as)
++add_old_configure_assignment('GNU_AS', gnu_as)
++
++
+ @depends(as_info, target)
+ def as_dash_c_flag(as_info, target):
+     # armasm64 doesn't understand -c.
+     if as_info.type == 'masm' and target.cpu == 'aarch64':
+         return ''
+     else:
+         return '-c'
+ 
+diff --git a/js/src/old-configure.in b/js/src/old-configure.in
+--- a/js/src/old-configure.in
++++ b/js/src/old-configure.in
+@@ -296,17 +296,16 @@ if test -n "$SBCONF"; then
+     if test $_sb_version_major -eq 1 -a $_sb_version_minor -eq 0 -a $_sb_version_point -le 16; then
+         QEMU_CANT_RUN_JS_SHELL=1
+     fi
+ fi
+ AC_SUBST(QEMU_CANT_RUN_JS_SHELL)
+ 
+ AC_SUBST(_MSC_VER)
+ 
+-AC_SUBST(GNU_AS)
+ AC_SUBST(GNU_CC)
+ AC_SUBST(GNU_CXX)
+ 
+ dnl ========================================================
+ dnl Checks for programs.
+ dnl ========================================================
+ if test "$COMPILE_ENVIRONMENT"; then
+ 
+diff --git a/old-configure.in b/old-configure.in
+--- a/old-configure.in
++++ b/old-configure.in
+@@ -326,17 +326,16 @@ if test -n "$_WIN32_MSVC"; then
+     AC_DEFINE(HAVE_IO_H)
+     AC_DEFINE(HAVE_ISATTY)
+ fi
+ 
+ fi # COMPILE_ENVIRONMENT
+ 
+ AC_SUBST(_MSC_VER)
+ 
+-AC_SUBST(GNU_AS)
+ AC_SUBST(GNU_CC)
+ AC_SUBST(GNU_CXX)
+ 
+ AC_SUBST_LIST(STL_FLAGS)
+ AC_SUBST(WRAP_STL_INCLUDES)
+ 
+ dnl ========================================================
+ dnl Checks for programs.

+ 109 - 0
rel-257/ian/patches/1397263-5-64a1.patch

@@ -0,0 +1,109 @@
+# HG changeset patch
+# User Nathan Froyd <froydnj@mozilla.com>
+# Date 1538612969 14400
+# Node ID 237dbec378d81d707afbf97e1818fea97c972844
+# Parent  606ff2b449f30e8bdb869d0a65df8df1663afcfc
+Bug 1397263 - move ASOUTOPTION to moz.configure; r=mshal
+
+diff --git a/build/moz.configure/toolchain.configure b/build/moz.configure/toolchain.configure
+--- a/build/moz.configure/toolchain.configure
++++ b/build/moz.configure/toolchain.configure
+@@ -1668,16 +1668,28 @@ def as_dash_c_flag(as_info, target):
+     if as_info.type == 'masm' and target.cpu == 'aarch64':
+         return ''
+     else:
+         return '-c'
+ 
+ 
+ set_config('AS_DASH_C_FLAG', as_dash_c_flag)
+ 
++
++@depends(as_info, target)
++def as_outoption(as_info, target):
++    # The uses of ASOUTOPTION depend on the spacing for -o/-Fo.
++    if as_info.type == 'masm' and target.cpu != 'aarch64':
++        return '-Fo'
++
++    return '-o '
++
++
++set_config('ASOUTOPTION', as_outoption)
++
+ # clang plugin handling
+ # ==============================================================
+ 
+ js_option('--enable-clang-plugin', env='ENABLE_CLANG_PLUGIN',
+           help="Enable building with the mozilla clang plugin")
+ 
+ add_old_configure_assignment('ENABLE_CLANG_PLUGIN',
+                              depends_if('--enable-clang-plugin')(lambda _: True))
+diff --git a/config/rules.mk b/config/rules.mk
+--- a/config/rules.mk
++++ b/config/rules.mk
+@@ -378,22 +378,16 @@ IFLAGS2 = -m 755
+ endif
+ 
+ ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+ OUTOPTION = -Fo# eol
+ else
+ OUTOPTION = -o # eol
+ endif # WINNT && !GNU_CC
+ 
+-ifneq (,$(filter ml%,$(AS)))
+-ASOUTOPTION = -Fo# eol
+-else
+-ASOUTOPTION = -o # eol
+-endif
+-
+ ifeq (,$(CROSS_COMPILE))
+ HOST_OUTOPTION = $(OUTOPTION)
+ else
+ HOST_OUTOPTION = -o # eol
+ endif
+ ################################################################################
+ 
+ # Ensure the build config is up to date. This is done automatically when builds
+diff --git a/python/mozbuild/mozbuild/frontend/emitter.py b/python/mozbuild/mozbuild/frontend/emitter.py
+--- a/python/mozbuild/mozbuild/frontend/emitter.py
++++ b/python/mozbuild/mozbuild/frontend/emitter.py
+@@ -1294,16 +1294,17 @@ class TreeMetadataEmitter(LoggingMixin):
+                                         context.get('ASFLAGS'))
+ 
+         if context.get('USE_YASM') is True:
+             yasm = context.config.substs.get('YASM')
+             if not yasm:
+                 raise SandboxValidationError('yasm is not available', context)
+             passthru.variables['AS'] = yasm
+             passthru.variables['AS_DASH_C_FLAG'] = ''
++            passthru.variables['ASOUTOPTION'] = '-o '
+             computed_as_flags.resolve_flags('OS',
+                                             context.config.substs.get('YASM_ASFLAGS', []))
+ 
+ 
+         if passthru.variables:
+             yield passthru
+ 
+         if context.objdir in self._compile_dirs:
+diff --git a/python/mozbuild/mozbuild/test/frontend/test_emitter.py b/python/mozbuild/mozbuild/test/frontend/test_emitter.py
+--- a/python/mozbuild/mozbuild/test/frontend/test_emitter.py
++++ b/python/mozbuild/mozbuild/test/frontend/test_emitter.py
+@@ -444,17 +444,18 @@ class TestEmitterBasic(unittest.TestCase
+         self.assertIsInstance(asflags, ComputedFlags)
+ 
+         self.assertEqual(asflags.flags['OS'], reader.config.substs['YASM_ASFLAGS'])
+ 
+         maxDiff = self.maxDiff
+         self.maxDiff = None
+         self.assertEqual(passthru.variables,
+                          {'AS': 'yasm',
+-                          'AS_DASH_C_FLAG': ''})
++                          'AS_DASH_C_FLAG': '',
++                          'ASOUTOPTION': '-o '})
+         self.maxDiff = maxDiff
+ 
+ 
+     def test_generated_files(self):
+         reader = self.reader('generated-files')
+         objs = self.read_topsrcdir(reader)
+ 
+         self.assertEqual(len(objs), 3)

+ 157 - 0
rel-257/ian/patches/1397263-6-64a1.patch

@@ -0,0 +1,157 @@
+# HG changeset patch
+# User Nathan Froyd <froydnj@mozilla.com>
+# Date 1538612969 14400
+# Node ID d678adeaddcd50c3d49c6a4afe3395f1a10853e1
+# Parent  5125a4fecee091e008a8a404eebfdfc8bbb5af35
+Bug 1397263 - move --enable-accessibility to moz.configure; r=mshal
+
+diff --git a/build/moz.configure/old.configure b/build/moz.configure/old.configure
+--- a/build/moz.configure/old.configure
++++ b/build/moz.configure/old.configure
+@@ -164,17 +164,16 @@ def old_configure_options(*options):
+ 
+     return depends(prepare_configure, extra_old_configure_args, all_options,
+                    *options)
+ 
+ 
+ @old_configure_options(
+     '--cache-file',
+     '--datadir',
+-    '--enable-accessibility',
+     '--enable-alsa',
+     '--enable-bundled-fonts',
+     '--enable-content-sandbox',
+     '--enable-cookies',
+     '--enable-cpp-rtti',
+     '--enable-crashreporter',
+     '--enable-dbus',
+     '--enable-debug-js-modules',
+diff --git a/old-configure.in b/old-configure.in
+--- a/old-configure.in
++++ b/old-configure.in
+@@ -1895,17 +1895,16 @@ MOZ_SPELLCHECK=1
+ MOZ_TOOLKIT_SEARCH=1
+ MOZ_UNIVERSALCHARDET=1
+ MOZ_XUL=1
+ MOZ_ZIPWRITER=1
+ MOZ_NO_SMART_CARDS=
+ NECKO_COOKIES=1
+ MOZ_USE_NATIVE_POPUP_WINDOWS=
+ MOZ_EXCLUDE_HYPHENATION_DICTIONARIES=
+-ACCESSIBILITY=1
+ MOZ_CONTENT_SANDBOX=
+ MOZ_GMP_SANDBOX=
+ MOZ_SANDBOX=1
+ MOZ_BINARY_EXTENSIONS=
+ MOZ_DEVTOOLS=server
+ 
+ case "$target_os" in
+     mingw*)
+@@ -2274,37 +2273,16 @@ AC_SUBST(MOZ_ENABLE_DBUS)
+ 
+ dnl =========================================================
+ dnl = Whether to exclude hyphenations files in the build
+ dnl =========================================================
+ if test -n "$MOZ_EXCLUDE_HYPHENATION_DICTIONARIES"; then
+     AC_DEFINE(MOZ_EXCLUDE_HYPHENATION_DICTIONARIES)
+ fi
+ 
+-dnl ========================================================
+-dnl accessibility support on by default on all platforms
+-dnl ========================================================
+-MOZ_ARG_DISABLE_BOOL(accessibility,
+-[  --disable-accessibility Disable accessibility support],
+-    ACCESSIBILITY=,
+-    ACCESSIBILITY=1 )
+-if test "$ACCESSIBILITY"; then
+-    case "$target" in
+-    *-mingw*)
+-        if test -z "$MIDL"; then
+-            if test "$GCC" != "yes"; then
+-                AC_MSG_ERROR([MIDL could not be found. Building accessibility without MIDL is not supported.])
+-            else
+-                AC_MSG_ERROR([You have accessibility enabled, but widl could not be found. Add --disable-accessibility to your mozconfig or install widl. See https://developer.mozilla.org/en-US/docs/Cross_Compile_Mozilla_for_Mingw32 for details.])
+-            fi
+-        fi
+-    esac
+-    AC_DEFINE(ACCESSIBILITY)
+-fi
+-
+ AC_TRY_COMPILE([#include <linux/ethtool.h>],
+                [ struct ethtool_cmd cmd; cmd.speed_hi = 0; ],
+                MOZ_WEBRTC_HAVE_ETHTOOL_SPEED_HI=1)
+ 
+ AC_SUBST(MOZ_WEBRTC_HAVE_ETHTOOL_SPEED_HI)
+ 
+ if test -n "$MOZ_WEBRTC"; then
+     MOZ_RAW=1
+@@ -3995,17 +3973,16 @@ AC_SUBST(MOZ_AUTH_EXTENSION)
+ AC_SUBST(MOZ_PREF_EXTENSIONS)
+ AC_SUBST_LIST(MOZ_DEBUG_LDFLAGS)
+ AC_SUBST(WARNINGS_AS_ERRORS)
+ AC_SUBST_SET(MOZ_EXTENSIONS)
+ AC_SUBST(MOZ_TOOLKIT_SEARCH)
+ AC_SUBST(MOZ_FEEDS)
+ 
+ AC_SUBST(MOZ_UNIVERSALCHARDET)
+-AC_SUBST(ACCESSIBILITY)
+ AC_SUBST(MOZ_SPELLCHECK)
+ AC_SUBST(MOZ_ANDROID_ANR_REPORTER)
+ AC_SUBST(MOZ_CRASHREPORTER)
+ AC_SUBST(MOZ_CRASHREPORTER_INJECTOR)
+ AC_SUBST(MOZ_MAINTENANCE_SERVICE)
+ AC_SUBST(MOZ_STUB_INSTALLER)
+ AC_SUBST(MOZ_VERIFY_MAR_SIGNATURE)
+ AC_SUBST(MOZ_ENABLE_SIGNMAR)
+diff --git a/toolkit/moz.configure b/toolkit/moz.configure
+--- a/toolkit/moz.configure
++++ b/toolkit/moz.configure
+@@ -1261,20 +1261,46 @@ def midl_flags(c_compiler, target):
+ 
+     # mingw
+     return {
+         'x86': ['--win32', '-m32'],
+         'x86_64': ['--win64', '-m64'],
+     }[target.cpu]
+ 
+ 
+-# Needed until we move --disable-accessibility from old-configure
+-add_old_configure_assignment('MIDL', midl)
+ set_config('MIDL_FLAGS', midl_flags)
+ 
++# Accessibility
++# ==============================================================
++
++option('--disable-accessibility', help='Disable accessibility support')
++
++@depends('--disable-accessibility', check_for_midl, midl, c_compiler)
++def accessibility(value, check_for_midl, midl, c_compiler):
++    enabled = bool(value)
++
++    if not enabled:
++        return
++
++    if check_for_midl and not midl:
++        if c_compiler and c_compiler.type in ('gcc', 'clang'):
++            die('You have accessibility enabled, but widl could not be found. '
++                'Add --disable-accessibility to your mozconfig or install widl. '
++                'See https://developer.mozilla.org/en-US/docs/Cross_Compile_Mozilla_for_Mingw32 for details.')
++        else:
++            die('MIDL could not be found. '
++                'Building accessibility without MIDL is not supported.')
++
++    return enabled
++
++
++set_config('ACCESSIBILITY', accessibility)
++set_define('ACCESSIBILITY', accessibility)
++add_old_configure_assignment('ACCESSIBILITY', accessibility)
++
+ # Addon signing
+ # ==============================================================
+ 
+ option('--with-unsigned-addon-scopes',
+        nargs='+', choices=('app', 'system'),
+        help='Addon scopes where signature is not required')
+ 
+ @depends('--with-unsigned-addon-scopes')

+ 188 - 0
rel-257/ian/patches/1401776-62a1.patch

@@ -0,0 +1,188 @@
+# HG changeset patch
+# User Jed Davis <jld@mozilla.com>
+# Date 1525995392 21600
+# Node ID fcfbfc7d96d90fb5bbc3f03284a460a70e7674ac
+# Parent  7ea7dd821347952a96808a3b98e45aa08a420ccd
+Bug 1401776 - Raise fd limit to 4096 on Unix. r=glandium,mcmanus
+
+This is to accommodate non-networking fd usage (IPC transports, various
+databases, .xpi files, etc.), so it's separate from Necko's existing
+manipulation of the fd limit, which is tied into Necko's internal limits
+on how many sockets it will try to poll at once.
+
+Note that resource limits are inherited by child processes, so this needs
+to be done only in the parent.
+
+This patch also removes similar code used on Solaris and Mac OS X.  The
+Mac case (bug 1036682) refers to fd use by graphics textures, which
+shouldn't be consuming fds anymore (even transiently) as of bug 1161166.
+
+MozReview-Commit-ID: 2uodrkW5sUn
+
+diff --git a/gfx/thebes/gfxPlatformMac.cpp b/gfx/thebes/gfxPlatformMac.cpp
+--- a/gfx/thebes/gfxPlatformMac.cpp
++++ b/gfx/thebes/gfxPlatformMac.cpp
+@@ -73,29 +73,16 @@ gfxPlatformMac::gfxPlatformMac() {
+   DisableFontActivation();
+   mFontAntiAliasingThreshold = ReadAntiAliasingThreshold();
+ 
+   uint32_t canvasMask = BackendTypeBit(BackendType::SKIA);
+   uint32_t contentMask = BackendTypeBit(BackendType::SKIA);
+   InitBackendPrefs(canvasMask, BackendType::SKIA, contentMask,
+                    BackendType::SKIA);
+ 
+-  // XXX: Bug 1036682 - we run out of fds on Mac when using tiled layers because
+-  // with 256x256 tiles we can easily hit the soft limit of 800 when using
+-  // double buffered tiles in e10s, so let's bump the soft limit to the hard
+-  // limit for the OS up to a new cap of OPEN_MAX.
+-  struct rlimit limits;
+-  if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {
+-    limits.rlim_cur = std::min(rlim_t(OPEN_MAX), limits.rlim_max);
+-    if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {
+-      NS_WARNING(
+-          "Unable to bump RLIMIT_NOFILE to the maximum number on this OS");
+-    }
+-  }
+-
+   MacIOSurfaceLib::LoadLibrary();
+ }
+ 
+ gfxPlatformMac::~gfxPlatformMac() { gfxCoreTextShaper::Shutdown(); }
+ 
+ bool gfxPlatformMac::UsesTiling() const {
+   // The non-tiling ContentClient requires CrossProcessSemaphore which
+   // isn't implemented for OSX.
+diff --git a/toolkit/xre/nsAppRunner.cpp b/toolkit/xre/nsAppRunner.cpp
+--- a/toolkit/xre/nsAppRunner.cpp
++++ b/toolkit/xre/nsAppRunner.cpp
+@@ -148,19 +148,22 @@
+ #include "mozilla/Omnijar.h"
+ #include "mozilla/StartupTimeline.h"
+ #include "mozilla/LateWriteChecks.h"
+ 
+ #include <stdlib.h>
+ #include <locale.h>
+ 
+ #ifdef XP_UNIX
++#include <errno.h>
++#include <pwd.h>
++#include <string.h>
++#include <sys/resource.h>
+ #include <sys/stat.h>
+ #include <unistd.h>
+-#include <pwd.h>
+ #endif
+ 
+ #ifdef XP_WIN
+ #include <process.h>
+ #include <shlobj.h>
+ #include "mozilla/WinDllServices.h"
+ #include "nsThreadUtils.h"
+ #include <comdef.h>
+@@ -3050,16 +3053,43 @@ static bool CheckForUserMismatch() {
+     }
+   }
+   return false;
+ }
+ #else  // !XP_UNIX || ANDROID
+ static bool CheckForUserMismatch() { return false; }
+ #endif
+ 
++static void IncreaseDescriptorLimits() {
++#ifdef XP_UNIX
++  // Increase the fd limit to accomodate IPC resources like shared memory.
++  static const rlim_t kFDs = 4096;
++  struct rlimit rlim;
++
++  if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
++    Output(false, "getrlimit: %s\n", strerror(errno));
++    return;
++  }
++  // Don't decrease the limit if it's already high enough, but don't
++  // try to go over the hard limit.  (RLIM_INFINITY isn't required to
++  // be the numerically largest rlim_t, so don't assume that.)
++  if (rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur < kFDs &&
++      rlim.rlim_cur < rlim.rlim_max) {
++    if (rlim.rlim_max != RLIM_INFINITY && rlim.rlim_max < kFDs) {
++      rlim.rlim_cur = rlim.rlim_max;
++    } else {
++      rlim.rlim_cur = kFDs;
++    }
++    if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
++      Output(false, "setrlimit: %s\n", strerror(errno));
++    }
++  }
++#endif
++}
++
+ /*
+  * XRE_mainInit - Initial setup and command line parameter processing.
+  * Main() will exit early if either return value != 0 or if aExitFlag is
+  * true.
+  */
+ int XREMain::XRE_mainInit(bool* aExitFlag) {
+   if (!aExitFlag) return 1;
+   *aExitFlag = false;
+@@ -3117,16 +3147,18 @@ int XREMain::XRE_mainInit(bool* aExitFla
+ 
+   nsresult rv;
+   ArgResult ar;
+ 
+ #ifdef DEBUG
+   if (PR_GetEnv("XRE_MAIN_BREAK")) NS_BREAK();
+ #endif
+ 
++  IncreaseDescriptorLimits();
++
+ #ifdef USE_GLX_TEST
+   // bug 639842 - it's very important to fire this process BEFORE we set up
+   // error handling. indeed, this process is expected to be crashy, and we
+   // don't want the user to see its crashes. That's the whole reason for
+   // doing this in a separate process.
+   //
+   // This call will cause a fork and the fork will terminate itself separately
+   // from the usual shutdown sequence
+diff --git a/toolkit/xre/nsSigHandlers.cpp b/toolkit/xre/nsSigHandlers.cpp
+--- a/toolkit/xre/nsSigHandlers.cpp
++++ b/toolkit/xre/nsSigHandlers.cpp
+@@ -275,40 +275,16 @@ void InstallSignalHandlers(const char *a
+     m *= (1024 * 1024);
+     struct rlimit r;
+     r.rlim_cur = m;
+     r.rlim_max = m;
+     setrlimit(RLIMIT_AS, &r);
+   }
+ #endif
+ 
+-#if defined(SOLARIS)
+-#define NOFILES 512
+-
+-  // Boost Solaris file descriptors
+-  {
+-    struct rlimit rl;
+-
+-    if (getrlimit(RLIMIT_NOFILE, &rl) == 0)
+-
+-      if (rl.rlim_cur < NOFILES) {
+-        rl.rlim_cur = NOFILES;
+-
+-        if (setrlimit(RLIMIT_NOFILE, &rl) < 0) {
+-          perror("setrlimit(RLIMIT_NOFILE)");
+-          fprintf(stderr, "Cannot exceed hard limit for open files");
+-        }
+-#if defined(DEBUG)
+-        if (getrlimit(RLIMIT_NOFILE, &rl) == 0)
+-          printf("File descriptors set to %d\n", rl.rlim_cur);
+-#endif  // DEBUG
+-      }
+-  }
+-#endif  // SOLARIS
+-
+ #if defined(MOZ_WIDGET_GTK) && \
+     (GLIB_MAJOR_VERSION > 2 || \
+      (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION >= 6))
+   const char *assertString = PR_GetEnv("XPCOM_DEBUG_BREAK");
+   if (assertString &&
+       (!strcmp(assertString, "suspend") || !strcmp(assertString, "stack") ||
+        !strcmp(assertString, "abort") || !strcmp(assertString, "trap") ||
+        !strcmp(assertString, "break"))) {

+ 95 - 0
rel-257/ian/patches/1404666-1-66a1.patch

@@ -0,0 +1,95 @@
+# HG changeset patch
+# User Jonathan Kew <jkew@mozilla.com>
+# Date 1545133320 0
+#      Tue Dec 18 11:42:00 2018 +0000
+# Branch THUNDERBIRD_60_VERBRANCH
+# Node ID 64bba4f9928e6b0f0cded35016f671a32b812519
+# Parent  2e3a07dc4d270fde3c582dd181d4674705bfcba6
+Bug 1404666 - patch 1 - Accelerate OSPreferences::GetDateTimePattern by caching patterns found for particular style/locale combinations. r=gandalf a=jorgk
+
+diff --git a/intl/locale/OSPreferences.cpp b/intl/locale/OSPreferences.cpp
+--- a/intl/locale/OSPreferences.cpp
++++ b/intl/locale/OSPreferences.cpp
+@@ -372,16 +372,39 @@ OSPreferences::GetDateTimePattern(int32_
+ 
+   // If the user is asking for None on both, date and time style,
+   // let's exit early.
+   if (timeStyle == DateTimeFormatStyle::None &&
+       dateStyle == DateTimeFormatStyle::None) {
+     return NS_OK;
+   }
+ 
+-  if (!ReadDateTimePattern(dateStyle, timeStyle, aLocale, aRetVal)) {
+-    if (!GetDateTimePatternForStyle(dateStyle, timeStyle, aLocale, aRetVal)) {
++  // Create a cache key from the locale + style options
++  nsAutoCString key(aLocale);
++  key.Append(':');
++  key.AppendInt(aDateFormatStyle);
++  key.Append(':');
++  key.AppendInt(aTimeFormatStyle);
++
++  nsString pattern;
++  if (mPatternCache.Get(key, &pattern)) {
++    aRetVal = pattern;
++    return NS_OK;
++  }
++
++  if (!ReadDateTimePattern(dateStyle, timeStyle, aLocale, pattern)) {
++    if (!GetDateTimePatternForStyle(dateStyle, timeStyle, aLocale, pattern)) {
+       return NS_ERROR_FAILURE;
+     }
+   }
+ 
++  if (mPatternCache.Count() == kMaxCachedPatterns) {
++    // Don't allow unlimited cache growth; just throw it away in the case of
++    // pathological behavior where a page keeps requesting different formats
++    // and locales.
++    NS_WARNING("flushing DateTimePattern cache");
++    mPatternCache.Clear();
++  }
++  mPatternCache.Put(key, pattern);
++
++  aRetVal = pattern;
+   return NS_OK;
+ }
+diff --git a/intl/locale/OSPreferences.h b/intl/locale/OSPreferences.h
+--- a/intl/locale/OSPreferences.h
++++ b/intl/locale/OSPreferences.h
+@@ -2,16 +2,17 @@
+ /* This Source Code Form is subject to the terms of the Mozilla Public
+  * 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/. */
+ 
+ #ifndef mozilla_intl_IntlOSPreferences_h__
+ #define mozilla_intl_IntlOSPreferences_h__
+ 
+ #include "mozilla/StaticPtr.h"
++#include "nsDataHashtable.h"
+ #include "nsString.h"
+ #include "nsTArray.h"
+ #include "unicode/uloc.h"
+ 
+ #include "mozIOSPreferences.h"
+ 
+ namespace mozilla {
+ namespace intl {
+@@ -140,16 +141,19 @@ class OSPreferences : public mozIOSPrefe
+    * hooks into OS events.
+    */
+   void Refresh();
+ 
+  protected:
+   nsTArray<nsCString> mSystemLocales;
+   nsTArray<nsCString> mRegionalPrefsLocales;
+ 
++  const size_t kMaxCachedPatterns = 15;
++  nsDataHashtable<nsCStringHashKey, nsString> mPatternCache;
++
+  private:
+   virtual ~OSPreferences();
+ 
+   static StaticRefPtr<OSPreferences> sInstance;
+ 
+   static bool CanonicalizeLanguageTag(nsCString& aLoc);
+ 
+   /**

+ 421 - 0
rel-257/ian/patches/1404666-2-66a1.patch

@@ -0,0 +1,421 @@
+# HG changeset patch
+# User Jonathan Kew <jkew@mozilla.com>
+# Date 1545133324 0
+#      Tue Dec 18 11:42:04 2018 +0000
+# Branch THUNDERBIRD_60_VERBRANCH
+# Node ID aafc47a21cd3190e7d22521e409aa3cbaceb9861
+# Parent  da664f2ee88b420bc9a91ea4634031527464884c
+Bug 1404666 - patch 2 - Accelerate DateTimeFormat::FormatUDateTime by caching ICU UDateFormat objects instead of creating them afresh every time. r=gandalf a=jorgk DONTBUILD
+
+diff --git a/intl/locale/DateTimeFormat.cpp b/intl/locale/DateTimeFormat.cpp
+--- a/intl/locale/DateTimeFormat.cpp
++++ b/intl/locale/DateTimeFormat.cpp
+@@ -11,16 +11,17 @@
+ #include "OSPreferences.h"
+ #include "mozIOSPreferences.h"
+ #include "unicode/udatpg.h"
+ 
+ namespace mozilla {
+ using namespace mozilla::intl;
+ 
+ nsCString* DateTimeFormat::mLocale = nullptr;
++nsDataHashtable<nsCStringHashKey, UDateFormat*>* DateTimeFormat::mFormatCache;
+ 
+ /*static*/ nsresult DateTimeFormat::Initialize() {
+   if (mLocale) {
+     return NS_OK;
+   }
+ 
+   mLocale = new nsCString();
+   AutoTArray<nsCString, 10> regionalPrefsLocales;
+@@ -69,152 +70,180 @@ nsCString* DateTimeFormat::mLocale = nul
+ 
+   // set up locale data
+   rv = Initialize();
+ 
+   if (NS_FAILED(rv)) {
+     return rv;
+   }
+ 
+-  // Get the date style for the formatter.
+-  nsAutoString skeletonDate;
+-  nsAutoString patternDate;
+-  bool haveSkeleton = true;
+-  switch (aDateFormatSelector) {
+-    case kDateFormatLong:
+-      rv = OSPreferences::GetInstance()->GetDateTimePattern(
+-          mozIOSPreferences::dateTimeFormatStyleLong,
+-          mozIOSPreferences::dateTimeFormatStyleNone,
+-          nsDependentCString(mLocale->get()), patternDate);
+-      NS_ENSURE_SUCCESS(rv, rv);
+-      haveSkeleton = false;
+-      break;
+-    case kDateFormatShort:
+-      rv = OSPreferences::GetInstance()->GetDateTimePattern(
+-          mozIOSPreferences::dateTimeFormatStyleShort,
+-          mozIOSPreferences::dateTimeFormatStyleNone,
+-          nsDependentCString(mLocale->get()), patternDate);
+-      NS_ENSURE_SUCCESS(rv, rv);
+-      haveSkeleton = false;
+-      break;
+-    case kDateFormatYearMonth:
+-      skeletonDate.AssignLiteral("yyyyMM");
+-      break;
+-    case kDateFormatYearMonthLong:
+-      skeletonDate.AssignLiteral("yyyyMMMM");
+-      break;
+-    case kDateFormatMonthLong:
+-      skeletonDate.AssignLiteral("MMMM");
+-      break;
+-    case kDateFormatWeekday:
+-      skeletonDate.AssignLiteral("EEE");
+-      break;
+-    case kDateFormatNone:
+-      haveSkeleton = false;
+-      break;
+-    default:
+-      NS_ERROR("Unknown nsDateFormatSelector");
+-      return NS_ERROR_ILLEGAL_VALUE;
++  UErrorCode status = U_ZERO_ERROR;
++
++  nsAutoCString key;
++  key.AppendInt((int)aDateFormatSelector);
++  key.Append(':');
++  key.AppendInt((int)aTimeFormatSelector);
++  if (aTimeParameters) {
++    key.Append(':');
++    key.AppendInt(aTimeParameters->tp_gmt_offset);
++    key.Append(':');
++    key.AppendInt(aTimeParameters->tp_dst_offset);
++  }
++
++  if (mFormatCache && mFormatCache->Count() == kMaxCachedFormats) {
++    // Don't allow a pathological page to extend the cache unreasonably.
++    NS_WARNING("flushing UDateFormat cache");
++    DeleteCache();
++  }
++  if (!mFormatCache) {
++    mFormatCache =
++        new nsDataHashtable<nsCStringHashKey, UDateFormat*>(kMaxCachedFormats);
+   }
+ 
+-  UErrorCode status = U_ZERO_ERROR;
+-  if (haveSkeleton) {
+-    // Get pattern for skeleton.
+-    UDateTimePatternGenerator* patternGenerator =
+-        udatpg_open(mLocale->get(), &status);
+-    if (U_SUCCESS(status)) {
+-      int32_t patternLength;
+-      patternDate.SetLength(DATETIME_FORMAT_INITIAL_LEN);
+-      patternLength = udatpg_getBestPattern(
+-          patternGenerator,
+-          reinterpret_cast<const UChar*>(skeletonDate.BeginReading()),
+-          skeletonDate.Length(),
+-          reinterpret_cast<UChar*>(patternDate.BeginWriting()),
+-          DATETIME_FORMAT_INITIAL_LEN, &status);
+-      patternDate.SetLength(patternLength);
++  UDateFormat*& dateTimeFormat = mFormatCache->GetOrInsert(key);
++
++  if (!dateTimeFormat) {
++    // We didn't have a cached formatter for this key, so create one.
+ 
+-      if (status == U_BUFFER_OVERFLOW_ERROR) {
+-        status = U_ZERO_ERROR;
+-        udatpg_getBestPattern(
++    // Get the date style for the formatter.
++    nsAutoString skeletonDate;
++    nsAutoString patternDate;
++    bool haveSkeleton = true;
++    switch (aDateFormatSelector) {
++      case kDateFormatLong:
++        rv = OSPreferences::GetInstance()->GetDateTimePattern(
++            mozIOSPreferences::dateTimeFormatStyleLong,
++            mozIOSPreferences::dateTimeFormatStyleNone,
++            nsDependentCString(mLocale->get()), patternDate);
++        NS_ENSURE_SUCCESS(rv, rv);
++        haveSkeleton = false;
++        break;
++      case kDateFormatShort:
++        rv = OSPreferences::GetInstance()->GetDateTimePattern(
++            mozIOSPreferences::dateTimeFormatStyleShort,
++            mozIOSPreferences::dateTimeFormatStyleNone,
++            nsDependentCString(mLocale->get()), patternDate);
++        NS_ENSURE_SUCCESS(rv, rv);
++        haveSkeleton = false;
++        break;
++      case kDateFormatYearMonth:
++        skeletonDate.AssignLiteral("yyyyMM");
++        break;
++      case kDateFormatYearMonthLong:
++        skeletonDate.AssignLiteral("yyyyMMMM");
++        break;
++      case kDateFormatMonthLong:
++        skeletonDate.AssignLiteral("MMMM");
++        break;
++      case kDateFormatWeekday:
++        skeletonDate.AssignLiteral("EEE");
++        break;
++      case kDateFormatNone:
++        haveSkeleton = false;
++        break;
++      default:
++        NS_ERROR("Unknown nsDateFormatSelector");
++        return NS_ERROR_ILLEGAL_VALUE;
++    }
++
++    if (haveSkeleton) {
++      // Get pattern for skeleton.
++      UDateTimePatternGenerator* patternGenerator =
++          udatpg_open(mLocale->get(), &status);
++      if (U_SUCCESS(status)) {
++        int32_t patternLength;
++        patternDate.SetLength(DATETIME_FORMAT_INITIAL_LEN);
++        patternLength = udatpg_getBestPattern(
+             patternGenerator,
+             reinterpret_cast<const UChar*>(skeletonDate.BeginReading()),
+             skeletonDate.Length(),
+-            reinterpret_cast<UChar*>(patternDate.BeginWriting()), patternLength,
+-            &status);
++            reinterpret_cast<UChar*>(patternDate.BeginWriting()),
++            DATETIME_FORMAT_INITIAL_LEN, &status);
++        patternDate.SetLength(patternLength);
++
++        if (status == U_BUFFER_OVERFLOW_ERROR) {
++          status = U_ZERO_ERROR;
++          udatpg_getBestPattern(
++              patternGenerator,
++              reinterpret_cast<const UChar*>(skeletonDate.BeginReading()),
++              skeletonDate.Length(),
++              reinterpret_cast<UChar*>(patternDate.BeginWriting()),
++              patternLength, &status);
++        }
++      }
++      udatpg_close(patternGenerator);
++    }
++
++    // Get the time style for the formatter.
++    nsAutoString patternTime;
++    switch (aTimeFormatSelector) {
++      case kTimeFormatSeconds:
++        rv = OSPreferences::GetInstance()->GetDateTimePattern(
++            mozIOSPreferences::dateTimeFormatStyleNone,
++            mozIOSPreferences::dateTimeFormatStyleLong,
++            nsDependentCString(mLocale->get()), patternTime);
++        NS_ENSURE_SUCCESS(rv, rv);
++        break;
++      case kTimeFormatNoSeconds:
++        rv = OSPreferences::GetInstance()->GetDateTimePattern(
++            mozIOSPreferences::dateTimeFormatStyleNone,
++            mozIOSPreferences::dateTimeFormatStyleShort,
++            nsDependentCString(mLocale->get()), patternTime);
++        NS_ENSURE_SUCCESS(rv, rv);
++        break;
++      case kTimeFormatNone:
++        break;
++      default:
++        NS_ERROR("Unknown nsTimeFormatSelector");
++        return NS_ERROR_ILLEGAL_VALUE;
++    }
++
++    nsAutoString pattern;
++    if (patternTime.Length() == 0) {
++      pattern.Assign(patternDate);
++    } else if (patternDate.Length() == 0) {
++      pattern.Assign(patternTime);
++    } else {
++      OSPreferences::GetDateTimeConnectorPattern(
++          nsDependentCString(mLocale->get()), pattern);
++      int32_t index = pattern.Find("{1}");
++      if (index != kNotFound) pattern.Replace(index, 3, patternDate);
++      index = pattern.Find("{0}");
++      if (index != kNotFound) pattern.Replace(index, 3, patternTime);
++    }
++
++    // Generate date/time string.
++    nsAutoString timeZoneID(u"GMT");
++    if (aTimeParameters) {
++      int32_t totalOffsetMinutes =
++          (aTimeParameters->tp_gmt_offset + aTimeParameters->tp_dst_offset) /
++          60;
++      if (totalOffsetMinutes != 0) {
++        char sign = totalOffsetMinutes < 0 ? '-' : '+';
++        int32_t hours = abs(totalOffsetMinutes) / 60;
++        int32_t minutes = abs(totalOffsetMinutes) % 60;
++        timeZoneID.AppendPrintf("%c%02d:%02d", sign, hours, minutes);
+       }
+     }
+-    udatpg_close(patternGenerator);
+-  }
+ 
+-  // Get the time style for the formatter.
+-  nsAutoString patternTime;
+-  switch (aTimeFormatSelector) {
+-    case kTimeFormatSeconds:
+-      rv = OSPreferences::GetInstance()->GetDateTimePattern(
+-          mozIOSPreferences::dateTimeFormatStyleNone,
+-          mozIOSPreferences::dateTimeFormatStyleLong,
+-          nsDependentCString(mLocale->get()), patternTime);
+-      NS_ENSURE_SUCCESS(rv, rv);
+-      break;
+-    case kTimeFormatNoSeconds:
+-      rv = OSPreferences::GetInstance()->GetDateTimePattern(
+-          mozIOSPreferences::dateTimeFormatStyleNone,
+-          mozIOSPreferences::dateTimeFormatStyleShort,
+-          nsDependentCString(mLocale->get()), patternTime);
+-      NS_ENSURE_SUCCESS(rv, rv);
+-      break;
+-    case kTimeFormatNone:
+-      break;
+-    default:
+-      NS_ERROR("Unknown nsTimeFormatSelector");
+-      return NS_ERROR_ILLEGAL_VALUE;
+-  }
+-
+-  nsAutoString pattern;
+-  if (patternTime.Length() == 0) {
+-    pattern.Assign(patternDate);
+-  } else if (patternDate.Length() == 0) {
+-    pattern.Assign(patternTime);
+-  } else {
+-    OSPreferences::GetDateTimeConnectorPattern(
+-        nsDependentCString(mLocale->get()), pattern);
+-    int32_t index = pattern.Find("{1}");
+-    if (index != kNotFound) pattern.Replace(index, 3, patternDate);
+-    index = pattern.Find("{0}");
+-    if (index != kNotFound) pattern.Replace(index, 3, patternTime);
+-  }
+-
+-  // Generate date/time string.
+-  nsAutoString timeZoneID(u"GMT");
+-  if (aTimeParameters) {
+-    int32_t totalOffsetMinutes =
+-        (aTimeParameters->tp_gmt_offset + aTimeParameters->tp_dst_offset) / 60;
+-    if (totalOffsetMinutes != 0) {
+-      char sign = totalOffsetMinutes < 0 ? '-' : '+';
+-      int32_t hours = abs(totalOffsetMinutes) / 60;
+-      int32_t minutes = abs(totalOffsetMinutes) % 60;
+-      timeZoneID.AppendPrintf("%c%02d:%02d", sign, hours, minutes);
++    if (aTimeParameters) {
++      dateTimeFormat =
++          udat_open(UDAT_PATTERN, UDAT_PATTERN, mLocale->get(),
++                    reinterpret_cast<const UChar*>(timeZoneID.BeginReading()),
++                    timeZoneID.Length(),
++                    reinterpret_cast<const UChar*>(pattern.BeginReading()),
++                    pattern.Length(), &status);
++    } else {
++      dateTimeFormat =
++          udat_open(UDAT_PATTERN, UDAT_PATTERN, mLocale->get(), nullptr, -1,
++                    reinterpret_cast<const UChar*>(pattern.BeginReading()),
++                    pattern.Length(), &status);
+     }
+   }
+ 
+-  UDateFormat* dateTimeFormat;
+-  if (aTimeParameters) {
+-    dateTimeFormat =
+-        udat_open(UDAT_PATTERN, UDAT_PATTERN, mLocale->get(),
+-                  reinterpret_cast<const UChar*>(timeZoneID.BeginReading()),
+-                  timeZoneID.Length(),
+-                  reinterpret_cast<const UChar*>(pattern.BeginReading()),
+-                  pattern.Length(), &status);
+-  } else {
+-    dateTimeFormat =
+-        udat_open(UDAT_PATTERN, UDAT_PATTERN, mLocale->get(), nullptr, -1,
+-                  reinterpret_cast<const UChar*>(pattern.BeginReading()),
+-                  pattern.Length(), &status);
+-  }
+-
+   if (U_SUCCESS(status) && dateTimeFormat) {
+     aStringOut.SetLength(DATETIME_FORMAT_INITIAL_LEN);
+     dateTimeLen =
+         udat_format(dateTimeFormat, aUDateTime,
+                     reinterpret_cast<UChar*>(aStringOut.BeginWriting()),
+                     DATETIME_FORMAT_INITIAL_LEN, nullptr, &status);
+     aStringOut.SetLength(dateTimeLen);
+ 
+@@ -225,22 +254,29 @@ nsCString* DateTimeFormat::mLocale = nul
+                   dateTimeLen, nullptr, &status);
+     }
+   }
+ 
+   if (U_FAILURE(status)) {
+     rv = NS_ERROR_FAILURE;
+   }
+ 
+-  if (dateTimeFormat) {
+-    udat_close(dateTimeFormat);
+-  }
+-
+   return rv;
+ }
+ 
++/*static*/ void DateTimeFormat::DeleteCache() {
++  if (mFormatCache) {
++    for (auto i = mFormatCache->Iter(); !i.Done(); i.Next()) {
++      udat_close(i.Data());
++    }
++    delete mFormatCache;
++    mFormatCache = nullptr;
++  }
++}
++
+ /*static*/ void DateTimeFormat::Shutdown() {
++  DeleteCache();
+   if (mLocale) {
+     delete mLocale;
+   }
+ }
+ 
+ }  // namespace mozilla
+diff --git a/intl/locale/DateTimeFormat.h b/intl/locale/DateTimeFormat.h
+--- a/intl/locale/DateTimeFormat.h
++++ b/intl/locale/DateTimeFormat.h
+@@ -4,16 +4,17 @@
+  * 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/. */
+ 
+ #ifndef mozilla_DateTimeFormat_h
+ #define mozilla_DateTimeFormat_h
+ 
+ #include <time.h>
+ #include "gtest/MozGtestFriend.h"
++#include "nsDataHashtable.h"
+ #include "nsString.h"
+ #include "prtime.h"
+ #include "unicode/udat.h"
+ 
+ namespace mozilla {
+ 
+ enum nsDateFormatSelector : long {
+   // Do not change the order of the values below (see bug 1225696).
+@@ -50,27 +51,30 @@ class DateTimeFormat {
+       const PRExplodedTime* aExplodedTime, nsAString& aStringOut);
+ 
+   static void Shutdown();
+ 
+  private:
+   DateTimeFormat() = delete;
+ 
+   static nsresult Initialize();
++  static void DeleteCache();
++  static const size_t kMaxCachedFormats = 15;
+ 
+   FRIEND_TEST(DateTimeFormat, FormatPRExplodedTime);
+   FRIEND_TEST(DateTimeFormat, DateFormatSelectors);
+   FRIEND_TEST(DateTimeFormat, FormatPRExplodedTimeForeign);
+   FRIEND_TEST(DateTimeFormat, DateFormatSelectorsForeign);
+ 
+   // performs a locale sensitive date formatting operation on the UDate
+   // parameter
+   static nsresult FormatUDateTime(
+       const nsDateFormatSelector aDateFormatSelector,
+       const nsTimeFormatSelector aTimeFormatSelector, const UDate aUDateTime,
+       const PRTimeParameters* aTimeParameters, nsAString& aStringOut);
+ 
+   static nsCString* mLocale;
++  static nsDataHashtable<nsCStringHashKey, UDateFormat*>* mFormatCache;
+ };
+ 
+ }  // namespace mozilla
+ 
+ #endif /* mozilla_DateTimeFormat_h */

+ 108 - 0
rel-257/ian/patches/1411589-1-61a1.patch

@@ -0,0 +1,108 @@
+# HG changeset patch
+# User Jan Horak <jhorak@redhat.com>
+# Date 1520527199 -3600
+# Node ID e2d6c52a232e4d3a4d80719b97d53c42bfc09d64
+# Parent  085cf5f3a13927d47e0c7eb3d56f9aa4ad73eedc
+Bug 1411589 - Export ShouldUseFlatpakPortal(); r=stransky
+We need to detect the flatpak environment on multiple places.
+Making the ShouldUseFlatpakPortal() exported to the nsIGIOService
+allows us to reuse it.
+
+MozReview-Commit-ID: 41NJyR3fqZQ
+
+diff --git a/toolkit/system/gnome/nsGIOService.cpp b/toolkit/system/gnome/nsGIOService.cpp
+--- a/toolkit/system/gnome/nsGIOService.cpp
++++ b/toolkit/system/gnome/nsGIOService.cpp
+@@ -33,17 +33,17 @@ static bool GetShouldUseFlatpakPortal() 
+     shouldUsePortal = true;
+   } else {
+     shouldUsePortal = (g_getenv("GTK_USE_PORTAL") != nullptr);
+   }
+   g_free(path);
+   return shouldUsePortal;
+ }
+ 
+-static bool ShouldUseFlatpakPortal() {
++static bool ShouldUseFlatpakPortalImpl() {
+   static bool sShouldUseFlatpakPortal = GetShouldUseFlatpakPortal();
+   return sShouldUseFlatpakPortal;
+ }
+ 
+ class nsFlatpakHandlerApp : public nsIHandlerApp {
+  public:
+   NS_DECL_ISUPPORTS
+   NS_DECL_NSIHANDLERAPP
+@@ -414,17 +414,17 @@ nsGIOService::GetMimeTypeFromExtension(c
+ NS_IMETHODIMP
+ nsGIOService::GetAppForURIScheme(const nsACString& aURIScheme,
+                                  nsIHandlerApp** aApp) {
+   *aApp = nullptr;
+ 
+   // Application in flatpak sandbox does not have access to the list
+   // of installed applications on the system. We use generic
+   // nsFlatpakHandlerApp which forwards launch call to the system.
+-  if (ShouldUseFlatpakPortal()) {
++  if (ShouldUseFlatpakPortalImpl()) {
+     nsFlatpakHandlerApp* mozApp = new nsFlatpakHandlerApp();
+     NS_ADDREF(*aApp = mozApp);
+     return NS_OK;
+   }
+ 
+   GAppInfo* app_info = g_app_info_get_default_for_uri_scheme(
+       PromiseFlatCString(aURIScheme).get());
+   if (app_info) {
+@@ -472,17 +472,17 @@ nsGIOService::GetAppsForURIScheme(const 
+ 
+ NS_IMETHODIMP
+ nsGIOService::GetAppForMimeType(const nsACString& aMimeType,
+                                 nsIHandlerApp** aApp) {
+   *aApp = nullptr;
+ 
+   // Flatpak does not reveal installed application to the sandbox,
+   // we need to create generic system handler.
+-  if (ShouldUseFlatpakPortal()) {
++  if (ShouldUseFlatpakPortalImpl()) {
+     nsFlatpakHandlerApp* mozApp = new nsFlatpakHandlerApp();
+     NS_ADDREF(*aApp = mozApp);
+     return NS_OK;
+   }
+ 
+   char* content_type =
+       g_content_type_from_mime_type(PromiseFlatCString(aMimeType).get());
+   if (!content_type) return NS_ERROR_FAILURE;
+@@ -698,8 +698,14 @@ nsGIOService::CreateAppFromCommand(nsACS
+   }
+   g_free(executableWithFullPath);
+ 
+   nsGIOMimeApp* mozApp = new nsGIOMimeApp(app_info);
+   NS_ENSURE_TRUE(mozApp, NS_ERROR_OUT_OF_MEMORY);
+   NS_ADDREF(*appInfo = mozApp);
+   return NS_OK;
+ }
++
++NS_IMETHODIMP
++nsGIOService::ShouldUseFlatpakPortal(bool* aRes) {
++  *aRes = ShouldUseFlatpakPortalImpl();
++  return NS_OK;
++}
+diff --git a/xpcom/system/nsIGIOService.idl b/xpcom/system/nsIGIOService.idl
+--- a/xpcom/system/nsIGIOService.idl
++++ b/xpcom/system/nsIGIOService.idl
+@@ -76,13 +76,17 @@ interface nsIGIOService : nsISupports
+   /*** Misc. methods ***/
+ 
+   /* Open the given URI in the default application */
+   void               showURI(in nsIURI uri);
+   [noscript] void    showURIForInput(in ACString uri);
+ 
+   /* Open path in file manager using org.freedesktop.FileManager1 interface */
+   [noscript] void    orgFreedesktopFileManager1ShowItems(in ACString path);
++
++  /* Check if we're in flatpak runtime or using GTK portals has been enforced */
++  [noscript] bool    shouldUseFlatpakPortal();
++
+ };
+ 
+ %{C++
+ #define NS_GIOSERVICE_CONTRACTID "@mozilla.org/gio-service;1"
+ %}

+ 531 - 0
rel-257/ian/patches/1411589-2-61a1.patch

@@ -0,0 +1,531 @@
+# HG changeset patch
+# User Jan Horak <jhorak@redhat.com>
+# Date 1522939475 -7200
+# Node ID c470cb1ec203f838faabf078fc8c2e16fafecc1d
+# Parent  5072999a9c14e05f970e92938821e3a61a8b186c
+Bug 1411589 - Implement printing support for the flatpak portal, r=stransky
+
+In the flatpak environment the applications do not have access to the printers.
+They need to use printing portal implemented by DBUS interface. The patch
+implements support for printing portal by introducing nsFlatpakPrintPortal class.
+1. it request print portal to show the print dialog
+2. waits until print dialog is finished
+3. setup observer for 'print-to-file-finished' topic
+4. pass file descriptor of the printed file to the portal when the observer is notified
+
+MozReview-Commit-ID: 3nZtYx7KzK6
+
+diff --git a/widget/gtk/nsPrintDialogGTK.cpp b/widget/gtk/nsPrintDialogGTK.cpp
+--- a/widget/gtk/nsPrintDialogGTK.cpp
++++ b/widget/gtk/nsPrintDialogGTK.cpp
+@@ -19,17 +19,30 @@
+ #include "nsIFile.h"
+ #include "nsIStringBundle.h"
+ #include "nsIPrintSettingsService.h"
+ #include "nsIDOMWindow.h"
+ #include "nsPIDOMWindow.h"
+ #include "nsIBaseWindow.h"
+ #include "nsIDocShellTreeItem.h"
+ #include "nsIDocShell.h"
++#include "nsIGIOService.h"
+ #include "WidgetUtils.h"
++#include "nsIObserverService.h"
++
++// for gdk_x11_window_get_xid
++#include <gdk/gdkx.h>
++#include <sys/types.h>
++#include <sys/stat.h>
++#include <fcntl.h>
++#include <gio/gunixfdlist.h>
++
++// for dlsym
++#include <dlfcn.h>
++#include "MainThreadUtils.h"
+ 
+ using namespace mozilla;
+ using namespace mozilla::widget;
+ 
+ static const char header_footer_tags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"};
+ 
+ #define CUSTOM_VALUE_INDEX gint(ArrayLength(header_footer_tags))
+ 
+@@ -544,23 +557,479 @@ NS_IMPL_ISUPPORTS(nsPrintDialogServiceGT
+ 
+ nsPrintDialogServiceGTK::nsPrintDialogServiceGTK() {}
+ 
+ nsPrintDialogServiceGTK::~nsPrintDialogServiceGTK() {}
+ 
+ NS_IMETHODIMP
+ nsPrintDialogServiceGTK::Init() { return NS_OK; }
+ 
++// Used to obtain window handle. The portal use this handle
++// to ensure that print dialog is modal.
++typedef void (*WindowHandleExported)(GtkWindow* window, const char* handle,
++                                     gpointer user_data);
++
++typedef void (*GtkWindowHandleExported)(GtkWindow* window, const char* handle,
++                                        gpointer user_data);
++#ifdef MOZ_WAYLAND
++typedef struct {
++  GtkWindow *window;
++  WindowHandleExported callback;
++  gpointer user_data;
++} WaylandWindowHandleExportedData;
++
++static void wayland_window_handle_exported(GdkWindow* window,
++                                           const char* wayland_handle_str,
++                                           gpointer user_data) {
++  WaylandWindowHandleExportedData *data =
++      static_cast<WaylandWindowHandleExportedData*>(user_data);
++  char* handle_str;
++
++  handle_str = g_strdup_printf("wayland:%s", wayland_handle_str);
++  data->callback(data->window, handle_str, data->user_data);
++  g_free(handle_str);
++}
++#endif
++
++// Get window handle for the portal, taken from gtk/gtkwindow.c
++// (currently not exported)
++static gboolean window_export_handle(GtkWindow* window,
++                                     GtkWindowHandleExported callback,
++                                     gpointer user_data) {
++  if (GDK_IS_X11_DISPLAY(gtk_widget_get_display(GTK_WIDGET(window)))) {
++    GdkWindow* gdk_window = gtk_widget_get_window(GTK_WIDGET(window));
++    char* handle_str;
++    guint32 xid = (guint32) gdk_x11_window_get_xid(gdk_window);
++
++    handle_str = g_strdup_printf("x11:%x", xid);
++    callback(window, handle_str, user_data);
++    g_free(handle_str);
++    return true;
++  }
++#ifdef MOZ_WAYLAND
++  else {
++    GdkWindow* gdk_window = gtk_widget_get_window(GTK_WIDGET(window));
++    WaylandWindowHandleExportedData* data;
++
++    data = g_new0(WaylandWindowHandleExportedData, 1);
++    data->window = window;
++    data->callback = callback;
++    data->user_data = user_data;
++
++    static auto s_gdk_wayland_window_export_handle =
++        reinterpret_cast<gboolean (*)(GdkWindow*, GdkWaylandWindowExported,
++                                      gpointer, GDestroyNotify)>(
++            dlsym(RTLD_DEFAULT, "gdk_wayland_window_export_handle"));
++    if (!s_gdk_wayland_window_export_handle ||
++        !s_gdk_wayland_window_export_handle(
++            gdk_window, wayland_window_handle_exported, data, g_free)) {
++      g_free(data);
++      return false;
++    } else  {
++      return true;
++    }
++  }
++#endif
++
++  g_warning("Couldn't export handle, unsupported windowing system");
++
++  return false;
++}
++/**
++ * Communication class with the GTK print portal handler
++ *
++ * To print document from flatpak we need to use print portal because
++ * printers are not directly accessible in the sandboxed environment.
++ *
++ * At first we request portal to show the print dialog to let user choose
++ * printer settings. We use DBUS interface for that (PreparePrint method).
++ *
++ * Next we force application to print to temporary file and after the writing
++ * to the file is finished we pass its file descriptor to the portal.
++ * Portal will pass duplicate of the file descriptor to the printer which
++ * user selected before (by DBUS Print method).
++ *
++ * Since DBUS communication is done async while nsPrintDialogServiceGTK::Show
++ * is expecting sync execution, we need to create a new GMainLoop during the
++ * print portal dialog is running. The loop is stopped after the dialog
++ * is closed.
++ */
++class nsFlatpakPrintPortal: public nsIObserver {
++  NS_DECL_ISUPPORTS
++  NS_DECL_NSIOBSERVER
++ public:
++  explicit nsFlatpakPrintPortal(nsPrintSettingsGTK* aPrintSettings);
++  nsresult PreparePrintRequest(GtkWindow* aWindow);
++  static void OnWindowExportHandleDone(GtkWindow* aWindow,
++                                       const char* aWindowHandleStr,
++                                       gpointer aUserData);
++  void PreparePrint(GtkWindow* aWindow, const char* aWindowHandleStr);
++  static void OnPreparePrintResponse(GDBusConnection* connection,
++                                     const char* sender_name,
++                                     const char* object_path,
++                                     const char* interface_name,
++                                     const char* signal_name,
++                                     GVariant* parameters,
++                                     gpointer data);
++   GtkPrintOperationResult GetResult();
++  private:
++   virtual ~nsFlatpakPrintPortal();
++   void FinishPrintDialog(GVariant* parameters);
++   nsCOMPtr<nsPrintSettingsGTK> mPrintAndPageSettings;
++   GDBusProxy* mProxy;
++   guint32 mToken;
++   GMainLoop* mLoop;
++   GtkPrintOperationResult mResult;
++   guint mResponseSignalId;
++   GtkWindow* mParentWindow;
++};
++
++NS_IMPL_ISUPPORTS(nsFlatpakPrintPortal, nsIObserver)
++
++nsFlatpakPrintPortal::nsFlatpakPrintPortal(nsPrintSettingsGTK* aPrintSettings)
++    : mPrintAndPageSettings(aPrintSettings),
++      mProxy(nullptr),
++      mLoop(nullptr),
++      mParentWindow(nullptr) {}
++
++/**
++ * Creates GDBusProxy, query for window handle and create a new GMainLoop.
++ *
++ * The GMainLoop is to be run from GetResult() and be quitted during
++ * FinishPrintDialog.
++ *
++ * @param aWindow toplevel application window which is used as parent of print
++ *                dialog
++ */
++nsresult nsFlatpakPrintPortal::PreparePrintRequest(GtkWindow* aWindow) {
++  NS_PRECONDITION(aWindow, "aWindow must not be null");
++  NS_PRECONDITION(mPrintAndPageSettings, "mPrintAndPageSettings must not be null");
++
++  GError* error = nullptr;
++  mProxy = g_dbus_proxy_new_for_bus_sync(
++      G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, nullptr,
++      "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop",
++      "org.freedesktop.portal.Print", nullptr, &error);
++  if (mProxy == nullptr) {
++    NS_WARNING(
++        nsPrintfCString("Unable to create dbus proxy: %s", error->message)
++            .get());
++    g_error_free(error);
++    return NS_ERROR_FAILURE;
++  }
++
++  // The window handler is returned async, we will continue by PreparePrint
++  // method when it is returned.
++  if (!window_export_handle(
++          aWindow, &nsFlatpakPrintPortal::OnWindowExportHandleDone, this)) {
++    NS_WARNING("Unable to get window handle for creating modal print dialog.");
++    return NS_ERROR_FAILURE;
++  }
++
++  mLoop = g_main_loop_new(NULL, FALSE);
++  return NS_OK;
++}
++
++void nsFlatpakPrintPortal::OnWindowExportHandleDone(
++    GtkWindow* aWindow, const char* aWindowHandleStr, gpointer aUserData) {
++  nsFlatpakPrintPortal* printPortal =
++      static_cast<nsFlatpakPrintPortal*>(aUserData);
++  printPortal->PreparePrint(aWindow, aWindowHandleStr);
++}
++
++/**
++ * Ask print portal to show the print dialog.
++ *
++ * Print and page settings and window handle are passed to the portal to prefill
++ * last used settings.
++ */
++void nsFlatpakPrintPortal::PreparePrint(GtkWindow* aWindow,
++                                        const char* aWindowHandleStr) {
++  GtkPrintSettings* gtkSettings = mPrintAndPageSettings->GetGtkPrintSettings();
++  GtkPageSetup* pageSetup = mPrintAndPageSettings->GetGtkPageSetup();
++
++  // We need to remember GtkWindow to unexport window handle after it is
++  // no longer needed by the portal dialog (apply only on non-X11 sessions).
++  if (!GDK_IS_X11_DISPLAY(gdk_display_get_default())) {
++    mParentWindow = aWindow;
++  }
++
++  GVariantBuilder opt_builder;
++  g_variant_builder_init(&opt_builder, G_VARIANT_TYPE_VARDICT);
++  char* token = g_strdup_printf("mozilla%d", g_random_int_range(0, G_MAXINT));
++  g_variant_builder_add(&opt_builder, "{sv}", "handle_token",
++                        g_variant_new_string(token));
++  g_free(token);
++  GVariant* options = g_variant_builder_end(&opt_builder);
++  static auto s_gtk_print_settings_to_gvariant =
++      reinterpret_cast<GVariant* (*)(GtkPrintSettings*)>(
++          dlsym(RTLD_DEFAULT, "gtk_print_settings_to_gvariant"));
++  static auto s_gtk_page_setup_to_gvariant =
++      reinterpret_cast<GVariant* (*)(GtkPageSetup *)>(
++          dlsym(RTLD_DEFAULT, "gtk_page_setup_to_gvariant"));
++  if (!s_gtk_print_settings_to_gvariant || !s_gtk_page_setup_to_gvariant) {
++    mResult = GTK_PRINT_OPERATION_RESULT_ERROR;
++    FinishPrintDialog(nullptr);
++    return;
++  }
++
++  // Get translated window title
++  nsCOMPtr<nsIStringBundleService> bundleSvc =
++       do_GetService(NS_STRINGBUNDLE_CONTRACTID);
++  nsCOMPtr<nsIStringBundle> printBundle;
++  bundleSvc->CreateBundle("chrome://global/locale/printdialog.properties",
++                          getter_AddRefs(printBundle));
++  nsAutoString intlPrintTitle;
++  printBundle->GetStringFromName("printTitleGTK", intlPrintTitle);
++
++  GError* error = nullptr;
++  GVariant *ret = g_dbus_proxy_call_sync(
++      mProxy, "PreparePrint",
++      g_variant_new(
++          "(ss@a{sv}@a{sv}@a{sv})", aWindowHandleStr,
++          NS_ConvertUTF16toUTF8(intlPrintTitle).get(),  // Title of the window
++          s_gtk_print_settings_to_gvariant(gtkSettings),
++          s_gtk_page_setup_to_gvariant(pageSetup), options),
++      G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
++  if (ret == nullptr) {
++    NS_WARNING(
++        nsPrintfCString("Unable to call dbus proxy: %s", error->message).get());
++    g_error_free(error);
++    mResult = GTK_PRINT_OPERATION_RESULT_ERROR;
++    FinishPrintDialog(nullptr);
++    return;
++  }
++
++  const char* handle = nullptr;
++  g_variant_get(ret, "(&o)", &handle);
++  if (strcmp(aWindowHandleStr, handle) != 0) {
++    aWindowHandleStr = g_strdup(handle);
++    g_dbus_connection_signal_unsubscribe(
++        g_dbus_proxy_get_connection(G_DBUS_PROXY(mProxy)), mResponseSignalId);
++  }
++  mResponseSignalId = g_dbus_connection_signal_subscribe(
++      g_dbus_proxy_get_connection(G_DBUS_PROXY(mProxy)),
++      "org.freedesktop.portal.Desktop", "org.freedesktop.portal.Request",
++      "Response", aWindowHandleStr, NULL, G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE,
++      &nsFlatpakPrintPortal::OnPreparePrintResponse, this, NULL);
++}
++
++void nsFlatpakPrintPortal::OnPreparePrintResponse(
++    GDBusConnection* connection, const char* sender_name,
++    const char* object_path, const char* interface_name,
++    const char* signal_name, GVariant* parameters, gpointer data) {
++  nsFlatpakPrintPortal* printPortal = static_cast<nsFlatpakPrintPortal*>(data);
++  printPortal->FinishPrintDialog(parameters);
++}
++
++/**
++ * When the dialog is accepted, read print and page settings and token.
++ *
++ * Token is later used for printing portal as print operation identifier.
++ * Print and page settings are modified in-place and stored to
++ * mPrintAndPageSettings.
++ */
++void nsFlatpakPrintPortal::FinishPrintDialog(GVariant* parameters) {
++  // This ends GetResult() method
++  if (mLoop) {
++    g_main_loop_quit(mLoop);
++    mLoop = nullptr;
++  }
++
++  if (!parameters) {
++    // mResult should be already defined
++    return;
++  }
++
++  guint32 response;
++  GVariant* options;
++
++  g_variant_get(parameters, "(u@a{sv})", &response, &options);
++  mResult = GTK_PRINT_OPERATION_RESULT_CANCEL;
++  if (response == 0) {
++    GVariant* v;
++
++    char* filename;
++    char* uri;
++    v = g_variant_lookup_value(options, "settings", G_VARIANT_TYPE_VARDICT);
++    static auto s_gtk_print_settings_new_from_gvariant =
++        reinterpret_cast<GtkPrintSettings* (*)(GVariant*)>(
++            dlsym(RTLD_DEFAULT, "gtk_print_settings_new_from_gvariant"));
++
++    GtkPrintSettings* printSettings = s_gtk_print_settings_new_from_gvariant(v);
++    g_variant_unref(v);
++
++    v = g_variant_lookup_value(options, "page-setup", G_VARIANT_TYPE_VARDICT);
++    static auto s_gtk_page_setup_new_from_gvariant =
++        reinterpret_cast<GtkPageSetup* (*)(GVariant*)>(
++            dlsym(RTLD_DEFAULT, "gtk_page_setup_new_from_gvariant"));
++    GtkPageSetup* pageSetup = s_gtk_page_setup_new_from_gvariant(v);
++    g_variant_unref(v);
++
++    g_variant_lookup(options, "token", "u", &mToken);
++
++    // Force printing to file because only filedescriptor of the file
++    // can be passed to portal
++    int fd = g_file_open_tmp("gtkprintXXXXXX", &filename, NULL);
++    uri = g_filename_to_uri(filename, NULL, NULL);
++    gtk_print_settings_set(printSettings, GTK_PRINT_SETTINGS_OUTPUT_URI, uri);
++    g_free(uri);
++    close(fd);
++
++    // Save native settings in the session object
++    mPrintAndPageSettings->SetGtkPrintSettings(printSettings);
++    mPrintAndPageSettings->SetGtkPageSetup(pageSetup);
++
++    // Portal consumes PDF file
++    mPrintAndPageSettings->SetOutputFormat(nsIPrintSettings::kOutputFormatPDF);
++
++    // We need to set to print to file
++    mPrintAndPageSettings->SetPrintToFile(true);
++
++    mResult = GTK_PRINT_OPERATION_RESULT_APPLY;
++  }
++}
++
++/**
++ * Get result of the print dialog.
++ *
++ * This call blocks until FinishPrintDialog is called.
++ *
++ */
++GtkPrintOperationResult
++nsFlatpakPrintPortal::GetResult() {
++  // If the mLoop has not been initialized we haven't go thru PreparePrint
++  // method
++  if (!NS_IsMainThread() || !mLoop) {
++    return GTK_PRINT_OPERATION_RESULT_ERROR;
++  }
++  // Calling g_main_loop_run stops current code until g_main_loop_quit is called
++  g_main_loop_run(mLoop);
++
++  // Free resources we've allocated in order to show print dialog.
++#ifdef MOZ_WAYLAND
++  if (mParentWindow) {
++    GdkWindow *gdk_window = gtk_widget_get_window(GTK_WIDGET(mParentWindow));
++    static auto s_gdk_wayland_window_unexport_handle =
++        reinterpret_cast<void (*)(GdkWindow*)>(
++            dlsym(RTLD_DEFAULT, "gdk_wayland_window_unexport_handle"));
++    if (s_gdk_wayland_window_unexport_handle) {
++      s_gdk_wayland_window_unexport_handle(gdk_window);
++    }
++  }
++#endif
++  return mResult;
++}
++
++/**
++ * Send file descriptor of the file which contains document to the portal to
++ * finish the print operation.
++ */
++NS_IMETHODIMP
++nsFlatpakPrintPortal::Observe(nsISupports* aObject, const char* aTopic,
++                              const char16_t* aData) {
++  // Check that written file match to the stored filename in case multiple
++  // print operations are in progress.
++  nsAutoString filenameStr;
++  mPrintAndPageSettings->GetToFileName(filenameStr);
++  if (!nsDependentString(aData).Equals(filenameStr)) {
++    // Different file is finished, not for this instance
++    return NS_OK;
++  }
++  int fd, idx;
++  fd = open(NS_ConvertUTF16toUTF8(filenameStr).get(), O_RDONLY|O_CLOEXEC);
++  static auto s_g_unix_fd_list_new =
++      reinterpret_cast<GUnixFDList* (*)(void)>(
++          dlsym(RTLD_DEFAULT, "g_unix_fd_list_new"));
++  NS_ASSERTION(s_g_unix_fd_list_new,
++               "Cannot find g_unix_fd_list_new function.");
++
++  GUnixFDList* fd_list = s_g_unix_fd_list_new();
++  static auto s_g_unix_fd_list_append =
++      reinterpret_cast<gint (*)(GUnixFDList*, gint, GError**)>(
++          dlsym(RTLD_DEFAULT, "g_unix_fd_list_append"));
++  idx = s_g_unix_fd_list_append(fd_list, fd, NULL);
++  close(fd);
++
++  GVariantBuilder opt_builder;
++  g_variant_builder_init(&opt_builder, G_VARIANT_TYPE_VARDICT);
++  g_variant_builder_add(&opt_builder, "{sv}",  "token",
++                        g_variant_new_uint32(mToken));
++  g_dbus_proxy_call_with_unix_fd_list(
++      mProxy, "Print",
++      g_variant_new("(ssh@a{sv})", "", /* window */
++                     "Print",          /* title */
++                     idx, g_variant_builder_end(&opt_builder)),
++      G_DBUS_CALL_FLAGS_NONE, -1, fd_list, NULL,
++      NULL,      // TODO portal result cb function
++      nullptr);  // data
++  g_object_unref(fd_list);
++
++  nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
++  // Let the nsFlatpakPrintPortal instance die
++  os->RemoveObserver(this, "print-to-file-finished");
++  return NS_OK;
++}
++
++nsFlatpakPrintPortal::~nsFlatpakPrintPortal() {
++  if (mProxy)
++    g_object_unref(mProxy);
++  if (mLoop) g_main_loop_quit(mLoop);
++}
++
+ NS_IMETHODIMP
+ nsPrintDialogServiceGTK::Show(nsPIDOMWindowOuter* aParent,
+                               nsIPrintSettings* aSettings,
+                               nsIWebBrowserPrint* aWebBrowserPrint) {
+   NS_PRECONDITION(aParent, "aParent must not be null");
+   NS_PRECONDITION(aSettings, "aSettings must not be null");
+ 
++  // Check for the flatpak portal first
++  nsCOMPtr<nsIGIOService> giovfs = do_GetService(NS_GIOSERVICE_CONTRACTID);
++  bool shouldUsePortal;
++  giovfs->ShouldUseFlatpakPortal(&shouldUsePortal);
++  if (shouldUsePortal && gtk_check_version(3, 22, 0) == nullptr) {
++    nsCOMPtr<nsIWidget> widget = WidgetUtils::DOMWindowToWidget(aParent);
++    NS_ASSERTION(widget, "Need a widget for dialog to be modal.");
++    GtkWindow* gtkParent = get_gtk_window_for_nsiwidget(widget);
++    NS_ASSERTION(gtkParent, "Need a GTK window for dialog to be modal.");
++
++    nsCOMPtr<nsPrintSettingsGTK> printSettingsGTK(do_QueryInterface(aSettings));
++    RefPtr<nsFlatpakPrintPortal> fpPrintPortal =
++        new nsFlatpakPrintPortal(printSettingsGTK);
++
++    nsresult rv = fpPrintPortal->PreparePrintRequest(gtkParent);
++    NS_ENSURE_SUCCESS(rv, rv);
++
++    // This blocks until nsFlatpakPrintPortal::FinishPrintDialog is called
++    GtkPrintOperationResult printDialogResult = fpPrintPortal->GetResult();
++
++    rv = NS_OK;
++    switch (printDialogResult) {
++      case GTK_PRINT_OPERATION_RESULT_APPLY: {
++        nsCOMPtr<nsIObserver> observer = do_QueryInterface(fpPrintPortal);
++        nsCOMPtr<nsIObserverService> os =
++            mozilla::services::GetObserverService();
++        NS_ENSURE_STATE(os);
++        // Observer waits until notified that the file with the content
++        // to print has been written.
++        rv = os->AddObserver(observer, "print-to-file-finished", false);
++        NS_ENSURE_SUCCESS(rv, rv);
++        break;
++      }
++      case GTK_PRINT_OPERATION_RESULT_CANCEL:
++        rv = NS_ERROR_ABORT;
++        break;
++      default:
++        NS_WARNING("Unexpected response");
++        rv = NS_ERROR_ABORT;
++    }
++    return rv;
++  }
++
+   nsPrintDialogWidgetGTK printDialog(aParent, aSettings);
+   nsresult rv = printDialog.ImportSettings(aSettings);
+ 
+   NS_ENSURE_SUCCESS(rv, rv);
+ 
+   const gint response = printDialog.Run();
+ 
+   // Handle the result

+ 69 - 0
rel-257/ian/patches/1411589-3-61a1.patch

@@ -0,0 +1,69 @@
+# HG changeset patch
+# User Jan Horak <jhorak@redhat.com>
+# Date 1523874531 -7200
+# Node ID a6bd62970a9fb094f223d99fbdf3dac25ec2f42d
+# Parent  0329e06e07894182d3cf86f870e454a2e538db7d
+Bug 1411589 - Notify flatpak print portal that print to file has finished, r=stransky
+
+The GTK print portal is notified by the observer service with 'print-to-file-finished'
+topic. The print filename is used as an identifier of the target in case multiple
+printing jobs are in progress.
+
+MozReview-Commit-ID: 1BZKDcK5De3
+
+diff --git a/widget/gtk/nsDeviceContextSpecG.cpp b/widget/gtk/nsDeviceContextSpecG.cpp
+--- a/widget/gtk/nsDeviceContextSpecG.cpp
++++ b/widget/gtk/nsDeviceContextSpecG.cpp
+@@ -28,16 +28,19 @@
+ #include "nsThreadUtils.h"
+ 
+ #include "mozilla/Preferences.h"
+ 
+ #include <unistd.h>
+ #include <sys/types.h>
+ #include <sys/stat.h>
+ 
++// To check if we need to use flatpak portal for printing
++#include "nsIGIOService.h"
++
+ using namespace mozilla;
+ 
+ using mozilla::gfx::IntSize;
+ using mozilla::gfx::PrintTarget;
+ using mozilla::gfx::PrintTargetPDF;
+ using mozilla::gfx::PrintTargetPS;
+ 
+ static LazyLogModule sDeviceContextSpecGTKLog("DeviceContextSpecGTK");
+@@ -342,16 +345,32 @@ NS_IMETHODIMP nsDeviceContextSpecGTK::En
+ 
+     // This is the standard way to get the UNIX umask. Ugh.
+     mode_t mask = umask(0);
+     umask(mask);
+     // If you're not familiar with umasks, they contain the bits of what NOT to
+     // set in the permissions (thats because files and directories have
+     // different numbers of bits for their permissions)
+     destFile->SetPermissions(0666 & ~(mask));
++
++    // Notify flatpak printing portal that file is completely written
++    nsCOMPtr<nsIGIOService> giovfs = do_GetService(NS_GIOSERVICE_CONTRACTID);
++    bool shouldUsePortal;
++    if (giovfs) {
++      giovfs->ShouldUseFlatpakPortal(&shouldUsePortal);
++      if (shouldUsePortal) {
++        // Use the name of the file for printing to match with
++        // nsFlatpakPrintPortal
++        nsCOMPtr<nsIObserverService> os =
++            mozilla::services::GetObserverService();
++        // Pass filename to be sure that observer process the right data
++        os->NotifyObservers(nullptr, "print-to-file-finished",
++                            targetPath.get());
++      }
++    }
+   }
+   return NS_OK;
+ }
+ 
+ //  Printer Enumerator
+ nsPrinterEnumeratorGTK::nsPrinterEnumeratorGTK() {}
+ 
+ NS_IMPL_ISUPPORTS(nsPrinterEnumeratorGTK, nsIPrinterEnumerator)

+ 179 - 0
rel-257/ian/patches/1418629-68a1.patch

@@ -0,0 +1,179 @@
+# HG changeset patch
+# User Makoto Kato <m_kato@ga2.so-net.ne.jp>
+# Date 1557308165 0
+# Node ID 5822c9d23ff717f637b5cd9c2c24a8e2d223fcb8
+# Parent  c68cb2a8cdd17d72bd37a0e1499f26f78ca00700
+Bug 1418629 - Single quotation mark shouldn't always separator. r=Ehsan
+
+This seems to be regression by bug 1362858.
+
+Actually, single quotation mark is always separator for spellchecker after
+landing bug 1462858. When user tries to input "doesn't",  "'" becomes separator
+for spellchecker. Then "doesn" will be misspell word.
+
+So we shouldn't mark single quotation mark as separator if user is inputting
+word.
+
+Differential Revision: https://phabricator.services.mozilla.com/D29153
+
+diff --git a/editor/spellchecker/tests/mochitest.ini b/editor/spellchecker/tests/mochitest.ini
+--- a/editor/spellchecker/tests/mochitest.ini
++++ b/editor/spellchecker/tests/mochitest.ini
+@@ -7,20 +7,22 @@ support-files =
+   bug1204147_subframe.html
+   bug1204147_subframe2.html
+   en-GB/en_GB.dic
+   en-GB/en_GB.aff
+   en-AU/en_AU.dic
+   en-AU/en_AU.aff
+   de-DE/de_DE.dic
+   de-DE/de_DE.aff
++  !/editor/libeditor/tests/spellcheck.js
+ 
+ [test_async_UpdateCurrentDictionary.html]
+ [test_bug678842.html]
+ [test_bug697981.html]
+ [test_bug717433.html]
+ [test_bug1200533.html]
+ [test_bug1204147.html]
+ [test_bug1205983.html]
+ [test_bug1209414.html]
+ [test_bug1219928.html]
+ skip-if = e10s
+ [test_bug1365383.html]
++[test_bug1418629.html]
+diff --git a/editor/spellchecker/tests/test_bug1418629.html b/editor/spellchecker/tests/test_bug1418629.html
+new file mode 100644
+--- /dev/null
++++ b/editor/spellchecker/tests/test_bug1418629.html
+@@ -0,0 +1,96 @@
++<!DOCTYPE html>
++<html>
++<head>
++  <title>Mozilla bug 1418629</title>
++  <link rel=stylesheet href="/tests/SimpleTest/test.css">
++  <script src="/tests/SimpleTest/EventUtils.js"></script>
++  <script src="/tests/SimpleTest/SimpleTest.js"></script>
++  <script src="/tests/SimpleTest/AddTask.js"></script>
++  <script src="/tests/editor/libeditor/tests/spellcheck.js"></script>
++</head>
++<body>
++<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1418629">Mozilla Bug 1418629</a>
++<p id="display"></p>
++<div id="content" style="display: none;">
++
++</div>
++
++<input id="input1" autofocus spellcheck="true">
++
++<script>
++const {onSpellCheck} = SpecialPowers.Cu.import("resource://testing-common/AsyncSpellCheckTestHelper.jsm", {});
++
++SimpleTest.waitForExplicitFinish();
++
++add_task(async function() {
++  await new Promise((resolve) => {
++    SimpleTest.waitForFocus(() => {
++      SimpleTest.executeSoon(resolve);
++    }, window);
++  });
++
++  let misspeltWords = [];
++  let input = document.getElementById("input1");
++
++  input.focus();
++  input.value = "";
++  synthesizeKey("d");
++  synthesizeKey("o");
++  synthesizeKey("e");
++  synthesizeKey("s");
++
++  await new Promise((resolve) => { onSpellCheck(input, resolve); });
++  // isSpellingCheckOk is defined in spellcheck.js
++  // eslint-disable-next-line no-undef
++  ok(isSpellingCheckOk(SpecialPowers.wrap(input).editor, misspeltWords),
++     "no misspelt words");
++
++  synthesizeKey("n");
++  synthesizeKey("\'");
++  is(input.value, "doesn\'", "");
++
++  await new Promise((resolve) => { onSpellCheck(input, resolve); });
++  // isSpellingCheckOk is defined in spellcheck.js
++  // eslint-disable-next-line no-undef
++  ok(isSpellingCheckOk(SpecialPowers.wrap(input).editor, misspeltWords),
++     "don't run spellchecker during inputting word");
++
++  synthesizeKey(" ");
++  is(input.value, "doesn\' ", "");
++
++  await new Promise((resolve) => { onSpellCheck(input, resolve); });
++  misspeltWords.push("doesn\'");
++  // isSpellingCheckOk is defined in spellcheck.js
++  // eslint-disable-next-line no-undef
++  ok(isSpellingCheckOk(SpecialPowers.wrap(input).editor, misspeltWords),
++     "should run spellchecker");
++});
++
++async function test_with_twice_characters(ch) {
++  let misspeltWords = [];
++  let input = document.getElementById("input1");
++
++  input.focus();
++  input.value = "";
++  synthesizeKey("d");
++  synthesizeKey("o");
++  synthesizeKey("e");
++  synthesizeKey("s");
++  synthesizeKey("n");
++  synthesizeKey(ch);
++  synthesizeKey(ch);
++  is(input.value, "doesn" + ch + ch, "");
++
++  await new Promise((resolve) => { onSpellCheck(input, resolve); });
++  misspeltWords.push("doesn");
++  // isSpellingCheckOk is defined in spellcheck.js
++  // eslint-disable-next-line no-undef
++  ok(isSpellingCheckOk(SpecialPowers.wrap(input).editor, misspeltWords),
++     "should run spellchecker");
++}
++
++add_task(test_with_twice_characters.bind(null, "\'"));
++add_task(test_with_twice_characters.bind(null, String.fromCharCode(0x2019)));
++</script>
++</body>
++</html>
+diff --git a/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp b/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
+--- a/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
++++ b/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
+@@ -385,18 +385,29 @@ CharClass WordSplitState::ClassifyCharac
+     if (aIndex == 0) return CHAR_CLASS_SEPARATOR;
+     if (ClassifyCharacter(aIndex - 1, false) != CHAR_CLASS_WORD)
+       return CHAR_CLASS_SEPARATOR;
+     // If the previous charatcer is a word-char, make sure that it's not a
+     // special dot character.
+     if (mDOMWordText[aIndex - 1] == '.') return CHAR_CLASS_SEPARATOR;
+ 
+     // now we know left char is a word-char, check the right-hand character
+-    if (aIndex == int32_t(mDOMWordText.Length()) - 1)
++    if (aIndex == int32_t(mDOMWordText.Length() - 1)) {
++      if (mDOMWordText[aIndex] == '\'' || mDOMWordText[aIndex] == 0x2019) {
++        nsUGenCategory prevCategory =
++            mozilla::unicode::GetGenCategory(mDOMWordText[aIndex - 1]);
++        if (prevCategory == nsUGenCategory::kLetter ||
++            prevCategory == nsUGenCategory::kNumber) {
++          // If single quotation mark is last, we don't return separator yet.
++          return CHAR_CLASS_WORD;
++        }
++      }
+       return CHAR_CLASS_SEPARATOR;
++    }
++
+     if (ClassifyCharacter(aIndex + 1, false) != CHAR_CLASS_WORD)
+       return CHAR_CLASS_SEPARATOR;
+     // If the next charatcer is a word-char, make sure that it's not a
+     // special dot character.
+     if (mDOMWordText[aIndex + 1] == '.') return CHAR_CLASS_SEPARATOR;
+ 
+     // char on either side is a word, this counts as a word
+     return CHAR_CLASS_WORD;

+ 45 - 0
rel-257/ian/patches/1418629-BACKOUT-1362858-1-60.patch

@@ -0,0 +1,45 @@
+# HG changeset patch
+# User Jorg K <jorgk@jorgk.com>
+# Date 1537205939 -7200
+#      Mon Sep 17 19:38:59 2018 +0200
+# Branch THUNDERBIRD_60_VERBRANCH
+# Node ID 78c54e4a83e8807cdeaa96e22648d381eb51c8da
+# Parent  aeb1b54a1cf0370303dba7f320eb5eb017f1bc9c
+Backed out part of changeset eaf99ba3813a (bug 1362858, part 1, for causing bug 1418629) to build Thunderbird 60.2. a=jorgk DONTBUILD
+
+diff --git a/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp b/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
+--- a/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
++++ b/extensions/spellcheck/src/mozInlineSpellWordUtil.cpp
+@@ -580,29 +580,21 @@ static inline bool IsBRElement(nsINode* 
+  */
+ static bool TextNodeContainsDOMWordSeparator(nsINode* aNode,
+                                              int32_t aBeforeOffset,
+                                              int32_t* aSeparatorOffset) {
+   // aNode is actually an nsIContent, since it's eTEXT
+   nsIContent* content = static_cast<nsIContent*>(aNode);
+   const nsTextFragment* textFragment = content->GetText();
+   NS_ASSERTION(textFragment, "Where is our text?");
+-  nsString text;
+-  int32_t end = std::min(aBeforeOffset, int32_t(textFragment->GetLength()));
+-  bool ok = textFragment->AppendTo(text, 0, end, mozilla::fallible);
+-  if (!ok) return false;
+-
+-  WordSplitState state(nullptr, text, 0, end);
+-  for (int32_t i = end - 1; i >= 0; --i) {
+-    if (IsDOMWordSeparator(textFragment->CharAt(i)) ||
+-        state.ClassifyCharacter(i, true) == CHAR_CLASS_SEPARATOR) {
++  for (int32_t i = std::min(aBeforeOffset, int32_t(textFragment->GetLength())) - 1; i >= 0; --i) {
++    if (IsDOMWordSeparator(textFragment->CharAt(i))) {
+       // Be greedy, find as many separators as we can
+       for (int32_t j = i - 1; j >= 0; --j) {
+-        if (IsDOMWordSeparator(textFragment->CharAt(j)) ||
+-            state.ClassifyCharacter(j, true) == CHAR_CLASS_SEPARATOR) {
++        if (IsDOMWordSeparator(textFragment->CharAt(j))) {
+           i = j;
+         } else {
+           break;
+         }
+       }
+       *aSeparatorOffset = i;
+       return true;
+     }

+ 563 - 0
rel-257/ian/patches/1418749-61a1.patch

@@ -0,0 +1,563 @@
+# HG changeset patch
+# User Michael Webster <miketwebster@gmail.com>
+# Date 1520527380 -7200
+# Node ID 45c0904bee03657a4a68e69521f9aadc4ca06f33
+# Parent  bcbe17a5fc1672257d9664baeb736defabf6208e
+Bug 1418749 - Add a TaskbarProgress implementation for gtk3/x11.  r=paolo,karlt
+This adds support for download progress reporting via the XApp
+method currently used in the Cinnamon desktop, by establishing a new
+X11 window property to be supported/read by the window manager.
+
+See https://github.com/linuxmint/xapps/blob/master/libxapp/xapp-gtk-window.c,
+as well as https://github.com/linuxmint/muffin/commit/39045da0ea06f
+for more details.
+
+The property-setting code lives in nsWindow - it's a small and stable
+enough chunk that it made more sense to do this than actually depend on
+another external library.  As nsWindow is already using x11 calls, this
+seemed the safest place for it, without affecting the build.
+
+The TaskbarProgress instance is initialized via the DownloadsTaskbar
+js module, and is handed a pointer to the current main window to call
+SetProgress on.  Most of the javascript side of this is in line with
+how the other platforms are handled.
+
+Without a supporting window manager/desktop environment (currently just
+Cinnamon/Muffin 3.6,) the simplest way to observe working behavior is
+by calling 'xprop -spy' on the browser window being testing and watching
+for updates during a download.
+
+diff --git a/browser/components/downloads/DownloadsTaskbar.jsm b/browser/components/downloads/DownloadsTaskbar.jsm
+--- a/browser/components/downloads/DownloadsTaskbar.jsm
++++ b/browser/components/downloads/DownloadsTaskbar.jsm
+@@ -35,16 +35,22 @@ XPCOMUtils.defineLazyGetter(this, "gWinT
+ });
+ 
+ XPCOMUtils.defineLazyGetter(this, "gMacTaskbarProgress", function() {
+   return ("@mozilla.org/widget/macdocksupport;1" in Cc) &&
+          Cc["@mozilla.org/widget/macdocksupport;1"]
+            .getService(Ci.nsITaskbarProgress);
+ });
+ 
++XPCOMUtils.defineLazyGetter(this, "gGtkTaskbarProgress", function() {
++  return ("@mozilla.org/widget/taskbarprogress/gtk;1" in Cc) &&
++         Cc["@mozilla.org/widget/taskbarprogress/gtk;1"]
++           .getService(Ci.nsIGtkTaskbarProgress);
++});
++
+ // DownloadsTaskbar
+ 
+ /**
+  * Handles the download progress indicator in the taskbar.
+  */
+ var DownloadsTaskbar = {
+   /**
+    * Underlying DownloadSummary providing the aggregate download information, or
+@@ -84,16 +90,20 @@ var DownloadsTaskbar = {
+         Services.obs.addObserver(() => {
+           this._taskbarProgress = null;
+           gMacTaskbarProgress = null;
+         }, "quit-application-granted");
+       } else if (gWinTaskbar) {
+         // On Windows, the indicator is currently hidden because we have no
+         // previous browser window, thus we should attach the indicator now.
+         this._attachIndicator(aBrowserWindow);
++      } else if (gGtkTaskbarProgress) {
++        this._taskbarProgress = gGtkTaskbarProgress;
++
++        this._attachGtkTaskbarProgress(aBrowserWindow);
+       } else {
+         // The taskbar indicator is not available on this platform.
+         return;
+       }
+     }
+ 
+     // Ensure that the DownloadSummary object will be created asynchronously.
+     if (!this._summary) {
+@@ -138,16 +148,45 @@ var DownloadsTaskbar = {
+         // The last browser window has been closed.  We remove the reference to
+         // the taskbar progress object so that the indicator will be registered
+         // again on the next browser window that is opened.
+         this._taskbarProgress = null;
+       }
+     });
+   },
+ 
++  /**
++   * In gtk3, the window itself implements the progress interface.
++   */
++  _attachGtkTaskbarProgress(aWindow) {
++    // Set the current window.
++    this._taskbarProgress.setPrimaryWindow(aWindow);
++
++    // If the DownloadSummary object has already been created, we should update
++    // the state of the new indicator, otherwise it will be updated as soon as
++    // the DownloadSummary view is registered.
++    if (this._summary) {
++      this.onSummaryChanged();
++    }
++
++    aWindow.addEventListener("unload", () => {
++      // Locate another browser window, excluding the one being closed.
++      let browserWindow = RecentWindow.getMostRecentBrowserWindow();
++      if (browserWindow) {
++        // Move the progress indicator to the other browser window.
++        this._attachGtkTaskbarProgress(browserWindow);
++      } else {
++        // The last browser window has been closed.  We remove the reference to
++        // the taskbar progress object so that the indicator will be registered
++        // again on the next browser window that is opened.
++        this._taskbarProgress = null;
++      }
++    });
++  },
++
+   // DownloadSummary view
+ 
+   onSummaryChanged() {
+     // If the last browser window has been closed, we have no indicator any more.
+     if (!this._taskbarProgress) {
+       return;
+     }
+ 
+diff --git a/widget/gtk/TaskbarProgress.cpp b/widget/gtk/TaskbarProgress.cpp
+new file mode 100644
+--- /dev/null
++++ b/widget/gtk/TaskbarProgress.cpp
+@@ -0,0 +1,111 @@
++/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
++/* vim: set ts=8 sts=2 et sw=2 tw=80: */
++/* This Source Code Form is subject to the terms of the Mozilla Public
++ * License, v. 2.0. If a copy of the MPL was not distributed with this
++ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
++
++#include "mozilla/Logging.h"
++
++#include "TaskbarProgress.h"
++#include "nsWindow.h"
++#include "WidgetUtils.h"
++#include "nsPIDOMWindow.h"
++
++using mozilla::LogLevel;
++static mozilla::LazyLogModule gGtkTaskbarProgressLog("nsIGtkTaskbarProgress");
++
++/******************************************************************************
++ * TaskbarProgress
++ ******************************************************************************/
++
++NS_IMPL_ISUPPORTS(TaskbarProgress, nsIGtkTaskbarProgress, nsITaskbarProgress)
++
++TaskbarProgress::TaskbarProgress()
++    : mPrimaryWindow(nullptr)
++{
++  MOZ_LOG(gGtkTaskbarProgressLog, LogLevel::Info,
++          ("%p TaskbarProgress()", this));
++}
++
++TaskbarProgress::~TaskbarProgress()
++{
++  MOZ_LOG(gGtkTaskbarProgressLog, LogLevel::Info,
++          ("%p ~TaskbarProgress()", this));
++}
++
++NS_IMETHODIMP
++TaskbarProgress::SetProgressState(nsTaskbarProgressState aState,
++                                  uint64_t               aCurrentValue,
++                                  uint64_t               aMaxValue)
++{
++#ifdef MOZ_X11
++  NS_ENSURE_ARG_RANGE(aState, 0, STATE_PAUSED);
++
++  if (aState == STATE_NO_PROGRESS || aState == STATE_INDETERMINATE) {
++    NS_ENSURE_TRUE(aCurrentValue == 0, NS_ERROR_INVALID_ARG);
++    NS_ENSURE_TRUE(aMaxValue == 0, NS_ERROR_INVALID_ARG);
++  }
++
++  NS_ENSURE_TRUE((aCurrentValue <= aMaxValue), NS_ERROR_ILLEGAL_VALUE);
++
++  // See TaskbarProgress::SetPrimaryWindow: if we're running in headless
++  // mode, mPrimaryWindow will be null.
++  if (!mPrimaryWindow) {
++    return NS_OK;
++  }
++
++  gulong progress;
++
++  if (aMaxValue == 0) {
++    progress = 0;
++  } else {
++    // Rounding down to ensure we don't set to 'full' until the operation
++    // is completely finished.
++    progress = (gulong) (((double)aCurrentValue / aMaxValue) * 100.0);
++  }
++
++  // Check if the resultant value is the same as the previous call, and
++  // ignore this update if it is.
++
++  if (progress == mCurrentProgress) {
++    return NS_OK;
++  }
++
++  mCurrentProgress = progress;
++
++  MOZ_LOG(gGtkTaskbarProgressLog, LogLevel::Debug,
++          ("GtkTaskbarProgress::SetProgressState progress: %lu", progress));
++
++  mPrimaryWindow->SetProgress(progress);
++#endif
++
++  return NS_OK;
++}
++
++NS_IMETHODIMP
++TaskbarProgress::SetPrimaryWindow(mozIDOMWindowProxy* aWindow)
++{
++  NS_ENSURE_TRUE(aWindow != nullptr, NS_ERROR_ILLEGAL_VALUE);
++
++  auto* parent = nsPIDOMWindowOuter::From(aWindow);
++  RefPtr<nsIWidget> widget = mozilla::widget::WidgetUtils::DOMWindowToWidget(parent);
++
++  // Only nsWindows have a native window, HeadlessWidgets do not.  Stop here if the
++  // window does not have one.
++  if (!widget->GetNativeData(NS_NATIVE_WINDOW)) {
++    return NS_OK;
++  }
++
++  mPrimaryWindow = static_cast<nsWindow*>(widget.get());
++
++  // Clear our current progress.  We get a forced update from the DownloadsTaskbar
++  // after returning from this function - zeroing out our progress will make sure the
++  // new window gets the property set on it immediately, rather than waiting for the
++  // progress value to change (which could be a while depending on size.)
++  mCurrentProgress = 0;
++
++  MOZ_LOG(gGtkTaskbarProgressLog, LogLevel::Debug,
++          ("GtkTaskbarProgress::SetPrimaryWindow window: %p", mPrimaryWindow.get()));
++
++  return NS_OK;
++}
+diff --git a/widget/gtk/TaskbarProgress.h b/widget/gtk/TaskbarProgress.h
+new file mode 100644
+--- /dev/null
++++ b/widget/gtk/TaskbarProgress.h
+@@ -0,0 +1,34 @@
++/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
++/* vim:expandtab:shiftwidth=4:tabstop=4:
++ */
++/* This Source Code Form is subject to the terms of the Mozilla Public
++ * 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/. */
++
++#ifndef TaskbarProgress_h_
++#define TaskbarProgress_h_
++
++#include "nsIGtkTaskbarProgress.h"
++
++class nsWindow;
++
++class TaskbarProgress final : public nsIGtkTaskbarProgress
++{
++public:
++  NS_DECL_ISUPPORTS
++  NS_DECL_NSIGTKTASKBARPROGRESS
++  NS_DECL_NSITASKBARPROGRESS
++
++  TaskbarProgress();
++
++protected:
++  ~TaskbarProgress();
++
++  // We track the progress value so we can avoid updating the X window property
++  // unnecessarily.
++  unsigned long mCurrentProgress;
++
++  RefPtr<nsWindow> mPrimaryWindow;
++};
++
++#endif // #ifndef TaskbarProgress_h_
+diff --git a/widget/gtk/moz.build b/widget/gtk/moz.build
+--- a/widget/gtk/moz.build
++++ b/widget/gtk/moz.build
+@@ -43,16 +43,17 @@ UNIFIED_SOURCES += [
+     'nsGtkKeyUtils.cpp',
+     'nsImageToPixbuf.cpp',
+     'nsLookAndFeel.cpp',
+     'nsNativeThemeGTK.cpp',
+     'nsSound.cpp',
+     'nsToolkit.cpp',
+     'nsWidgetFactory.cpp',
+     'ScreenHelperGTK.cpp',
++    'TaskbarProgress.cpp',
+     'WakeLockListener.cpp',
+     'WidgetTraceEvent.cpp',
+     'WidgetUtilsGtk.cpp',
+ ]
+ 
+ SOURCES += [
+     'nsWindow.cpp', # conflicts with X11 headers
+ ]
+diff --git a/widget/gtk/nsWidgetFactory.cpp b/widget/gtk/nsWidgetFactory.cpp
+--- a/widget/gtk/nsWidgetFactory.cpp
++++ b/widget/gtk/nsWidgetFactory.cpp
+@@ -22,16 +22,17 @@
+ #ifdef MOZ_X11
+ #include "nsClipboardHelper.h"
+ #include "nsClipboard.h"
+ #include "nsDragService.h"
+ #endif
+ #ifdef MOZ_WIDGET_GTK
+ #include "nsApplicationChooser.h"
+ #endif
++#include "TaskbarProgress.h"
+ #include "nsColorPicker.h"
+ #include "nsFilePicker.h"
+ #include "nsSound.h"
+ #include "nsBidiKeyboard.h"
+ #include "nsGTKToolkit.h"
+ #include "WakeLockListener.h"
+ 
+ #ifdef NS_PRINTING
+@@ -70,16 +71,17 @@ NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR
+ NS_GENERIC_FACTORY_CONSTRUCTOR(nsClipboardHelper)
+ NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsDragService,
+                                          nsDragService::GetInstance)
+ #endif
+ NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsISound, nsSound::GetInstance)
+ NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(ScreenManager,
+                                          ScreenManager::GetAddRefedSingleton)
+ NS_GENERIC_FACTORY_CONSTRUCTOR(nsImageToPixbuf)
++NS_GENERIC_FACTORY_CONSTRUCTOR(TaskbarProgress)
+ 
+ // from nsWindow.cpp
+ extern bool gDisableNativeTheme;
+ 
+ static nsresult nsNativeThemeGTKConstructor(nsISupports *aOuter, REFNSIID aIID,
+                                             void **aResult) {
+   nsresult rv;
+   nsCOMPtr<nsITheme> inst;
+@@ -190,16 +192,17 @@ static nsresult nsClipboardConstructor(n
+ NS_DEFINE_NAMED_CID(NS_WINDOW_CID);
+ NS_DEFINE_NAMED_CID(NS_CHILD_CID);
+ NS_DEFINE_NAMED_CID(NS_APPSHELL_CID);
+ NS_DEFINE_NAMED_CID(NS_COLORPICKER_CID);
+ NS_DEFINE_NAMED_CID(NS_FILEPICKER_CID);
+ #ifdef MOZ_WIDGET_GTK
+ NS_DEFINE_NAMED_CID(NS_APPLICATIONCHOOSER_CID);
+ #endif
++NS_DEFINE_NAMED_CID(NS_GTK_TASKBARPROGRESS_CID);
+ NS_DEFINE_NAMED_CID(NS_SOUND_CID);
+ NS_DEFINE_NAMED_CID(NS_TRANSFERABLE_CID);
+ #ifdef MOZ_X11
+ NS_DEFINE_NAMED_CID(NS_CLIPBOARD_CID);
+ NS_DEFINE_NAMED_CID(NS_CLIPBOARDHELPER_CID);
+ NS_DEFINE_NAMED_CID(NS_DRAGSERVICE_CID);
+ #endif
+ NS_DEFINE_NAMED_CID(NS_HTMLFORMATCONVERTER_CID);
+@@ -227,16 +230,17 @@ static const mozilla::Module::CIDEntry k
+     {&kNS_COLORPICKER_CID, false, nullptr, nsColorPickerConstructor,
+      Module::MAIN_PROCESS_ONLY},
+     {&kNS_FILEPICKER_CID, false, nullptr, nsFilePickerConstructor,
+      Module::MAIN_PROCESS_ONLY},
+ #ifdef MOZ_WIDGET_GTK
+     {&kNS_APPLICATIONCHOOSER_CID, false, nullptr,
+      nsApplicationChooserConstructor, Module::MAIN_PROCESS_ONLY},
+ #endif
++    {&kNS_GTK_TASKBARPROGRESS_CID, false, nullptr, TaskbarProgressConstructor},
+     {&kNS_SOUND_CID, false, nullptr, nsISoundConstructor,
+      Module::MAIN_PROCESS_ONLY},
+     {&kNS_TRANSFERABLE_CID, false, nullptr, nsTransferableConstructor},
+ #ifdef MOZ_X11
+     {&kNS_CLIPBOARD_CID, false, nullptr, nsClipboardConstructor,
+      Module::MAIN_PROCESS_ONLY},
+     {&kNS_CLIPBOARDHELPER_CID, false, nullptr, nsClipboardHelperConstructor},
+     {&kNS_DRAGSERVICE_CID, false, nullptr, nsDragServiceConstructor,
+@@ -274,16 +278,17 @@ static const mozilla::Module::ContractID
+     {"@mozilla.org/colorpicker;1", &kNS_COLORPICKER_CID,
+      Module::MAIN_PROCESS_ONLY},
+     {"@mozilla.org/filepicker;1", &kNS_FILEPICKER_CID,
+      Module::MAIN_PROCESS_ONLY},
+ #ifdef MOZ_WIDGET_GTK
+     {"@mozilla.org/applicationchooser;1", &kNS_APPLICATIONCHOOSER_CID,
+      Module::MAIN_PROCESS_ONLY},
+ #endif
++    {"@mozilla.org/widget/taskbarprogress/gtk;1", &kNS_GTK_TASKBARPROGRESS_CID},
+     {"@mozilla.org/sound;1", &kNS_SOUND_CID, Module::MAIN_PROCESS_ONLY},
+     {"@mozilla.org/widget/transferable;1", &kNS_TRANSFERABLE_CID},
+ #ifdef MOZ_X11
+     {"@mozilla.org/widget/clipboard;1", &kNS_CLIPBOARD_CID,
+      Module::MAIN_PROCESS_ONLY},
+     {"@mozilla.org/widget/clipboardhelper;1", &kNS_CLIPBOARDHELPER_CID},
+     {"@mozilla.org/widget/dragservice;1", &kNS_DRAGSERVICE_CID,
+      Module::MAIN_PROCESS_ONLY},
+diff --git a/widget/gtk/nsWindow.cpp b/widget/gtk/nsWindow.cpp
+--- a/widget/gtk/nsWindow.cpp
++++ b/widget/gtk/nsWindow.cpp
+@@ -6384,8 +6384,70 @@ wl_surface *nsWindow::GetWaylandSurface(
+     return moz_container_get_wl_surface(MOZ_CONTAINER(mContainer));
+ 
+   NS_WARNING(
+       "nsWindow::GetWaylandSurfaces(): We don't have any mContainer for "
+       "drawing!");
+   return nullptr;
+ }
+ #endif
++
++#ifdef MOZ_X11
++/* XApp progress support currently works by setting a property
++ * on a window with this Atom name.  A supporting window manager
++ * will notice this and pass it along to whatever handling has
++ * been implemented on that end (e.g. passing it on to a taskbar
++ * widget.)  There is no issue if WM support is lacking, this is
++ * simply ignored in that case.
++ *
++ * See https://github.com/linuxmint/xapps/blob/master/libxapp/xapp-gtk-window.c
++ * for further details.
++ */
++
++#define PROGRESS_HINT  "_NET_WM_XAPP_PROGRESS"
++
++static void
++set_window_hint_cardinal (Window       xid,
++                          const gchar *atom_name,
++                          gulong       cardinal)
++{
++  GdkDisplay *display;
++
++  display = gdk_display_get_default ();
++
++  if (cardinal > 0)
++  {
++    XChangeProperty (GDK_DISPLAY_XDISPLAY (display),
++                     xid,
++                     gdk_x11_get_xatom_by_name_for_display (display, atom_name),
++                     XA_CARDINAL, 32,
++                     PropModeReplace,
++                     (guchar *) &cardinal, 1);
++  }
++  else
++  {
++    XDeleteProperty (GDK_DISPLAY_XDISPLAY (display),
++                     xid,
++                     gdk_x11_get_xatom_by_name_for_display (display, atom_name));
++  }
++}
++#endif // MOZ_X11
++
++void
++nsWindow::SetProgress(unsigned long progressPercent)
++{
++#ifdef MOZ_X11
++
++  if (!mIsX11Display) {
++    return;
++  }
++
++  if (!mShell) {
++    return;
++  }
++
++  progressPercent = CLAMP(progressPercent, 0, 100);
++
++  set_window_hint_cardinal(GDK_WINDOW_XID(gtk_widget_get_window(mShell)),
++                           PROGRESS_HINT,
++                           progressPercent);
++#endif // MOZ_X11
++}
+diff --git a/widget/gtk/nsWindow.h b/widget/gtk/nsWindow.h
+--- a/widget/gtk/nsWindow.h
++++ b/widget/gtk/nsWindow.h
+@@ -211,16 +211,18 @@ class nsWindow final : public nsBaseWidg
+ 
+   virtual already_AddRefed<mozilla::gfx::DrawTarget> StartRemoteDrawingInRegion(
+       LayoutDeviceIntRegion& aInvalidRegion,
+       mozilla::layers::BufferMode* aBufferMode) override;
+   virtual void EndRemoteDrawingInRegion(
+       mozilla::gfx::DrawTarget* aDrawTarget,
+       LayoutDeviceIntRegion& aInvalidRegion) override;
+ 
++   void SetProgress(unsigned long progressPercent);
++
+  private:
+   void UpdateAlpha(mozilla::gfx::SourceSurface* aSourceSurface,
+                    nsIntRect aBoundsRect);
+ 
+   void NativeMove();
+   void NativeResize();
+   void NativeMoveResize();
+ 
+diff --git a/widget/moz.build b/widget/moz.build
+--- a/widget/moz.build
++++ b/widget/moz.build
+@@ -79,16 +79,21 @@ DIRS += ['headless']
+ # source tree.
+ #
+ if 'gtk' in CONFIG['MOZ_WIDGET_TOOLKIT']:
+     DIRS += ['gtk']
+ 
+     if CONFIG['MOZ_X11']:
+         DIRS += ['gtkxtbin']
+ 
++    XPIDL_SOURCES += [
++        'nsIGtkTaskbarProgress.idl',
++        'nsITaskbarProgress.idl',
++    ]
++
+ XPIDL_SOURCES += [
+     'nsIAppShell.idl',
+     'nsIBaseWindow.idl',
+     'nsIBidiKeyboard.idl',
+     'nsIClipboard.idl',
+     'nsIClipboardDragDropHookList.idl',
+     'nsIClipboardDragDropHooks.idl',
+     'nsIClipboardHelper.idl',
+diff --git a/widget/nsIGtkTaskbarProgress.idl b/widget/nsIGtkTaskbarProgress.idl
+new file mode 100644
+--- /dev/null
++++ b/widget/nsIGtkTaskbarProgress.idl
+@@ -0,0 +1,22 @@
++/* This Source Code Form is subject to the terms of the Mozilla Public
++ * 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/. */
++
++#include "nsITaskbarProgress.idl"
++
++interface mozIDOMWindowProxy;
++
++/**
++ * Allow the TaskbarProgress instance to set a new target window.
++ */
++
++[scriptable, uuid(39f6fc5a-2386-4bc6-941c-d7479253bc3f)]
++interface nsIGtkTaskbarProgress : nsITaskbarProgress
++{
++  /**
++   * Sets the window that is considered primary for purposes of
++   * setting the XApp progress property.
++   */
++
++  void setPrimaryWindow(in mozIDOMWindowProxy aWindow);
++};
+diff --git a/widget/nsWidgetsCID.h b/widget/nsWidgetsCID.h
+--- a/widget/nsWidgetsCID.h
++++ b/widget/nsWidgetsCID.h
+@@ -264,16 +264,20 @@
+ // {e9096367-ddd9-45e4-b762-49c0c18b7119}
+ #define NS_MACWEBAPPUTILS_CID                        \
+   {                                                  \
+     0xe9096367, 0xddd9, 0x45e4, {                    \
+       0xb7, 0x62, 0x49, 0xc0, 0xc1, 0x8b, 0x71, 0x19 \
+     }                                                \
+   }
+ 
++// {a9339876-0027-430f-b953-84c9c11c2da3}
++#define NS_GTK_TASKBARPROGRESS_CID \
++{ 0xa9339876, 0x0027, 0x430f, { 0xb9, 0x53, 0x84, 0xc9, 0xc1, 0x1c, 0x2d, 0xa3 } }
++
+ //-----------------------------------------------------------
+ // Printing
+ //-----------------------------------------------------------
+ #define NS_DEVICE_CONTEXT_SPEC_CID                   \
+   {                                                  \
+     0xd3f69889, 0xe13a, 0x4321, {                    \
+       0x98, 0x0c, 0xa3, 0x93, 0x32, 0xe2, 0x1f, 0x34 \
+     }                                                \

+ 331 - 0
rel-257/ian/patches/1419892-61a1.patch

@@ -0,0 +1,331 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1522103391 25200
+# Node ID 25bffacec2573375a58f67d11c4516b607f9bfbf
+# Parent  19fc460c37a235747f57ae6228d8cb20bb7b60bd
+Bug 1419892 - Link programs and libraries in the tup backend. r=mshal
+
+MozReview-Commit-ID: 26Yb0QdCn5H
+
+diff --git a/python/mozbuild/mozbuild/backend/tup.py b/python/mozbuild/mozbuild/backend/tup.py
+--- a/python/mozbuild/mozbuild/backend/tup.py
++++ b/python/mozbuild/mozbuild/backend/tup.py
+@@ -29,17 +29,21 @@ from ..frontend.data import (
+     FinalTargetPreprocessedFiles,
+     GeneratedFile,
+     GeneratedSources,
+     HostDefines,
+     HostSources,
+     JARManifest,
+     ObjdirFiles,
+     PerSourceFlag,
++    Program,
++    HostProgram,
++    SharedLibrary,
+     Sources,
++    StaticLibrary,
+     VariablePassthru,
+ )
+ from ..util import (
+     FileAvoidWrite,
+     expand_variables,
+ )
+ from ..frontend.context import (
+     AbsolutePath,
+@@ -57,21 +61,25 @@ class BackendTupfile(object):
+         self.relobjdir = mozpath.relpath(objdir, topobjdir)
+         self.environment = environment
+         self.name = mozpath.join(objdir, 'Tupfile')
+         self.rules_included = False
+         self.shell_exported = False
+         self.defines = []
+         self.host_defines = []
+         self.delayed_generated_files = []
++        self.delayed_installed_files = []
+         self.per_source_flags = defaultdict(list)
+         self.local_flags = defaultdict(list)
+         self.sources = defaultdict(list)
+         self.host_sources = defaultdict(list)
+         self.variables = {}
++        self.static_lib = None
++        self.shared_lib = None
++        self.program = None
+ 
+         self.fh = FileAvoidWrite(self.name, capture_diff=True)
+         self.fh.write('# THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT EDIT.\n')
+         self.fh.write('\n')
+ 
+     def write(self, buf):
+         self.fh.write(buf)
+ 
+@@ -188,16 +196,28 @@ class TupOnly(CommonBackend, PartialBack
+         # will be built before any rules that list this as an input.
+         self._installed_idls = '$(MOZ_OBJ_ROOT)/<installed-idls>'
+         self._installed_files = '$(MOZ_OBJ_ROOT)/<installed-files>'
+         # The preprocessor including source-repo.h and buildid.h creates
+         # dependencies that aren't specified by moz.build and cause errors
+         # in Tup. Express these as a group dependency.
+         self._early_generated_files = '$(MOZ_OBJ_ROOT)/<early-generated-files>'
+ 
++        # application.ini.h is a special case since we need to process
++        # the FINAL_TARGET_PP_FILES for application.ini before running
++        # the GENERATED_FILES script, and tup doesn't handle the rules
++        # out of order. Similarly, dependentlibs.list uses libxul as
++        # an input, so must be written after the rule for libxul.
++        self._delayed_files = (
++            'application.ini.h',
++            'dependentlibs.list',
++            'dependentlibs.list.gtest'
++        )
++
++
+     def _get_backend_file(self, relobjdir):
+         objdir = mozpath.normpath(mozpath.join(self.environment.topobjdir, relobjdir))
+         if objdir not in self._backend_files:
+             self._backend_files[objdir] = \
+                     BackendTupfile(objdir, self.environment,
+                                    self.environment.topsrcdir, self.environment.topobjdir)
+         return self._backend_files[objdir]
+ 
+@@ -207,16 +227,139 @@ class TupOnly(CommonBackend, PartialBack
+     def _py_action(self, action):
+         cmd = [
+             '$(PYTHON)',
+             '-m',
+             'mozbuild.action.%s' % action,
+         ]
+         return cmd
+ 
++    def _lib_paths(self, objdir, libs):
++        return [mozpath.relpath(mozpath.join(l.objdir, l.import_name), objdir)
++                for l in libs]
++
++    def _gen_shared_library(self, backend_file):
++        if backend_file.shared_lib.name == 'libxul.so':
++            # This will fail to link currently due to missing rust symbols.
++            return
++
++        if backend_file.shared_lib.cxx_link:
++            mkshlib = (
++                [backend_file.environment.substs['CXX']] +
++                backend_file.local_flags['CXX_LDFLAGS']
++            )
++        else:
++            mkshlib = (
++                [backend_file.environment.substs['CC']] +
++                backend_file.local_flags['C_LDFLAGS']
++            )
++
++        mkshlib += (
++            backend_file.environment.substs['DSO_PIC_CFLAGS'] +
++            [backend_file.environment.substs['DSO_LDOPTS']] +
++            ['-Wl,-h,%s' % backend_file.shared_lib.soname] +
++            ['-o', backend_file.shared_lib.lib_name]
++        )
++
++        objs, _, shared_libs, os_libs, static_libs = self._expand_libs(backend_file.shared_lib)
++        static_libs = self._lib_paths(backend_file.objdir, static_libs)
++        shared_libs = self._lib_paths(backend_file.objdir, shared_libs)
++
++        list_file_name = '%s.list' % backend_file.shared_lib.name.replace('.', '_')
++        list_file = self._make_list_file(backend_file.objdir, objs, list_file_name)
++
++        inputs = objs + static_libs + shared_libs
++        if any(i.endswith('libxul.so') for i in inputs):
++            # Don't attempt to link anything that depends on libxul.
++            return
++
++        symbols_file = []
++        if backend_file.shared_lib.symbols_file:
++            inputs.append(backend_file.shared_lib.symbols_file)
++            # TODO: Assumes GNU LD
++            symbols_file = ['-Wl,--version-script,%s' % backend_file.shared_lib.symbols_file]
++
++        cmd = (
++            mkshlib +
++            [list_file] +
++            backend_file.local_flags['LDFLAGS'] +
++            static_libs +
++            shared_libs +
++            symbols_file +
++            [backend_file.environment.substs['OS_LIBS']] +
++            os_libs
++        )
++        backend_file.rule(
++            cmd=cmd,
++            inputs=inputs,
++            outputs=[backend_file.shared_lib.lib_name],
++            display='LINK %o'
++        )
++
++
++    def _gen_program(self, backend_file):
++        cc_or_cxx = 'CXX' if backend_file.program.cxx_link else 'CC'
++        objs, _, shared_libs, os_libs, static_libs = self._expand_libs(backend_file.program)
++        static_libs = self._lib_paths(backend_file.objdir, static_libs)
++        shared_libs = self._lib_paths(backend_file.objdir, shared_libs)
++
++        inputs = objs + static_libs + shared_libs
++        if any(i.endswith('libxul.so') for i in inputs):
++            # Don't attempt to link anything that depends on libxul.
++            return
++
++        list_file_name = '%s.list' % backend_file.program.name.replace('.', '_')
++        list_file = self._make_list_file(backend_file.objdir, objs, list_file_name)
++
++        outputs = [mozpath.relpath(backend_file.program.output_path.full_path,
++                                   backend_file.objdir)]
++        cmd = (
++            [backend_file.environment.substs[cc_or_cxx], '-o', '%o'] +
++            backend_file.local_flags['CXX_LDFLAGS'] +
++            [list_file] +
++            backend_file.local_flags['LDFLAGS'] +
++            static_libs +
++            [backend_file.environment.substs['MOZ_PROGRAM_LDFLAGS']] +
++            shared_libs +
++            [backend_file.environment.substs['OS_LIBS']] +
++            os_libs
++        )
++        backend_file.rule(
++            cmd=cmd,
++            inputs=inputs,
++            outputs=outputs,
++            display='LINK %o'
++        )
++
++
++    def _gen_static_library(self, backend_file):
++        ar = [
++            backend_file.environment.substs['AR'],
++            backend_file.environment.substs['AR_FLAGS'].replace('$@', '%o')
++        ]
++
++        objs, _, shared_libs, _, static_libs = self._expand_libs(backend_file.static_lib)
++        static_libs = self._lib_paths(backend_file.objdir, static_libs)
++        shared_libs = self._lib_paths(backend_file.objdir, shared_libs)
++
++        inputs = objs + static_libs
++
++        cmd = (
++            ar +
++            inputs
++        )
++
++        backend_file.rule(
++            cmd=cmd,
++            inputs=inputs,
++            outputs=[backend_file.static_lib.name],
++            display='AR %o'
++        )
++
++
+     def consume_object(self, obj):
+         """Write out build files necessary to build with tup."""
+ 
+         if not isinstance(obj, ContextDerived):
+             return False
+ 
+         consumed = CommonBackend.consume_object(self, obj)
+         if consumed:
+@@ -229,21 +372,17 @@ class TupOnly(CommonBackend, PartialBack
+ 
+             if self.environment.is_artifact_build:
+                 skip_files = self._compile_env_gen_files
+ 
+             for f in obj.outputs:
+                 if any(mozpath.match(f, p) for p in skip_files):
+                     return False
+ 
+-            if 'application.ini.h' in obj.outputs:
+-                # application.ini.h is a special case since we need to process
+-                # the FINAL_TARGET_PP_FILES for application.ini before running
+-                # the GENERATED_FILES script, and tup doesn't handle the rules
+-                # out of order.
++            if any([f in obj.outputs for f in self._delayed_files]):
+                 backend_file.delayed_generated_files.append(obj)
+             else:
+                 self._process_generated_file(backend_file, obj)
+         elif (isinstance(obj, ChromeManifestEntry) and
+               obj.install_target.startswith('dist/bin')):
+             top_level = mozpath.join(obj.install_target, 'chrome.manifest')
+             if obj.path != top_level:
+                 entry = 'manifest %s' % mozpath.relpath(obj.path,
+@@ -265,16 +404,24 @@ class TupOnly(CommonBackend, PartialBack
+         elif isinstance(obj, ComputedFlags):
+             self._process_computed_flags(obj, backend_file)
+         elif isinstance(obj, (Sources, GeneratedSources)):
+             backend_file.sources[obj.canonical_suffix].extend(obj.files)
+         elif isinstance(obj, HostSources):
+             backend_file.host_sources[obj.canonical_suffix].extend(obj.files)
+         elif isinstance(obj, VariablePassthru):
+             backend_file.variables = obj.variables
++        elif isinstance(obj, StaticLibrary):
++            backend_file.static_lib = obj
++        elif isinstance(obj, SharedLibrary):
++            backend_file.shared_lib = obj
++        elif isinstance(obj, HostProgram):
++            pass
++        elif isinstance(obj, Program):
++            backend_file.program = obj
+ 
+         # The top-level Makefile.in still contains our driver target and some
+         # things related to artifact builds, so as a special case ensure the
+         # make backend generates a Makefile there.
+         if obj.objdir == self.environment.topobjdir:
+             return False
+ 
+         return True
+@@ -285,19 +432,28 @@ class TupOnly(CommonBackend, PartialBack
+         # The approach here is similar to fastermake.py, but we
+         # simply write out the resulting files here.
+         for target, entries in self._manifest_entries.iteritems():
+             with self._write_file(mozpath.join(self.environment.topobjdir,
+                                                target)) as fh:
+                 fh.write(''.join('%s\n' % e for e in sorted(entries)))
+ 
+         for objdir, backend_file in sorted(self._backend_files.items()):
++            backend_file.gen_sources_rules([self._installed_files])
++            for condition, gen_method in ((backend_file.shared_lib, self._gen_shared_library),
++                                          (backend_file.static_lib and backend_file.static_lib.no_expand_lib,
++                                           self._gen_static_library),
++                                          (backend_file.program, self._gen_program)):
++                if condition:
++                    backend_file.export_shell()
++                    gen_method(backend_file)
+             for obj in backend_file.delayed_generated_files:
+                 self._process_generated_file(backend_file, obj)
+-            backend_file.gen_sources_rules([self._installed_files])
++            for path, output in backend_file.delayed_installed_files:
++                backend_file.symlink_rule(path, output=output)
+             with self._write_file(fh=backend_file):
+                 pass
+ 
+         with self._write_file(mozpath.join(self.environment.topobjdir, 'Tuprules.tup')) as fh:
+             acdefines_flags = ' '.join(['-D%s=%s' % (name, shell_quote(value))
+                 for (name, value) in sorted(self.environment.acdefines.iteritems())])
+             # TODO: AB_CD only exists in Makefiles at the moment.
+             acdefines_flags += ' -DAB_CD=en-US'
+@@ -431,18 +587,21 @@ class TupOnly(CommonBackend, PartialBack
+                     # We're not generating files in these directories yet, so
+                     # don't attempt to install files generated from them.
+                     if f.context.relobjdir not in ('layout/style/test',
+                                                    'toolkit/library',
+                                                    'js/src/shell'):
+                         output = mozpath.join('$(MOZ_OBJ_ROOT)', target, path,
+                                               f.target_basename)
+                         gen_backend_file = self._get_backend_file(f.context.relobjdir)
+-                        gen_backend_file.symlink_rule(f.full_path, output=output,
+-                                                      output_group=self._installed_files)
++                        if f.target_basename in self._delayed_files:
++                            gen_backend_file.delayed_installed_files.append((f.full_path, output))
++                        else:
++                            gen_backend_file.symlink_rule(f.full_path, output=output,
++                                                          output_group=self._installed_files)
+ 
+     def _process_final_target_pp_files(self, obj, backend_file):
+         for i, (path, files) in enumerate(obj.files.walk()):
+             for f in files:
+                 self._preprocess(backend_file, f.full_path,
+                                  destdir=mozpath.join(self.environment.topobjdir, obj.install_target, path))
+ 
+     def _process_computed_flags(self, obj, backend_file):

+ 42 - 0
rel-257/ian/patches/1421501-6only-63a1.patch

@@ -0,0 +1,42 @@
+# HG changeset patch
+# User Robert Helmer <rhelmer@mozilla.com>
+# Date 1533828948 25200
+#      Thu Aug 09 08:35:48 2018 -0700
+# Node ID 5599309f2879ce75d53d5723c7ab818771902b73
+# Parent  bedda35e49dde37706e20b4e34eeefb82ef4dbc1
+Bug 1421501 - export NSS [Init,Shutdown]Context symbols r=fkiefer
+
+MozReview-Commit-ID: Kmhn1dBSYUD
+
+diff --git a/security/nss.symbols b/security/nss.symbols
+--- a/security/nss.symbols
++++ b/security/nss.symbols
+@@ -255,26 +255,28 @@ NSS_Get_SEC_OctetStringTemplate
+ NSS_Get_SEC_OctetStringTemplate_Util
+ NSS_Get_SECOID_AlgorithmIDTemplate
+ NSS_Get_SECOID_AlgorithmIDTemplate_Util
+ NSS_Get_SEC_SignedCertificateTemplate
+ NSS_Get_SEC_UTF8StringTemplate
+ NSS_Get_SEC_UTF8StringTemplate_Util
+ NSS_GetVersion
+ NSS_Init
++NSS_InitContext
+ NSS_Initialize
+ NSS_InitWithMerge
+ NSS_IsInitialized
+ NSS_OptionGet
+ NSS_OptionSet
+ NSS_NoDB_Init
+ NSS_SecureMemcmp
+ NSS_SetAlgorithmPolicy
+ NSS_SetDomesticPolicy
+ NSS_Shutdown
++NSS_ShutdownContext
+ NSSSMIME_GetVersion
+ NSS_SMIMESignerInfo_SaveSMIMEProfile
+ NSS_SMIMEUtil_FindBulkAlgForRecipients
+ NSSSSL_GetVersion
+ #ifdef XP_WIN
+ _NSSUTIL_Access
+ #endif
+ NSSUTIL_ArgDecodeNumber

+ 74 - 0
rel-257/ian/patches/1422368-61a1.patch

@@ -0,0 +1,74 @@
+# HG changeset patch
+# User David Major <dmajor@mozilla.com>
+# Date 1522845696 14400
+# Node ID 8a463b11e2411cf11ce3113c00a3ef63f844f2d8
+# Parent  f242fa9cd57f62cf097ce6c9401994eba62c025f
+Bug 1422368: Use intrinsics-based YUV functions from Win64 under Win32 clang-cl. r=jrmuizel
+
+diff --git a/gfx/ycbcr/convert.patch b/gfx/ycbcr/convert.patch
+--- a/gfx/ycbcr/convert.patch
++++ b/gfx/ycbcr/convert.patch
+@@ -343,17 +343,17 @@ diff --git a/gfx/ycbcr/yuv_convert.cpp b
+ -    } else {
+ -      if (filter & FILTER_BILINEAR_H) {
+ +    } else if (filter & FILTER_BILINEAR_H) {
+          LinearScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
+                                   dest_pixel, width, source_dx);
+      } else {
+  // Specialized scalers and rotation.
+ -#if USE_MMX && defined(_MSC_VER)
+-+#if defined(MOZILLA_MAY_SUPPORT_SSE) && defined(_MSC_VER) && defined(_M_IX86)
+++#if defined(MOZILLA_MAY_SUPPORT_SSE) && defined(_MSC_VER) && defined(_M_IX86) && !defined(__clang__)
+ +      if(mozilla::supports_sse()) {
+          if (width == (source_width * 2)) {
+ -          DoubleYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
+ -                              dest_pixel, width);
+ +          DoubleYUVToRGB32Row_SSE(y_ptr, u_ptr, v_ptr,
+ +                                  dest_pixel, width);
+          } else if ((source_dx & kFractionMask) == 0) {
+            // Scaling by integer scale factor. ie half.
+diff --git a/gfx/ycbcr/moz.build b/gfx/ycbcr/moz.build
+--- a/gfx/ycbcr/moz.build
++++ b/gfx/ycbcr/moz.build
+@@ -29,17 +29,17 @@ if CONFIG['INTEL_ARCHITECTURE']:
+             SOURCES += [
+                 'yuv_convert_mmx.cpp',
+             ]
+     else:
+         SOURCES += ['yuv_convert_mmx.cpp']
+         SOURCES['yuv_convert_mmx.cpp'].flags += CONFIG['MMX_FLAGS']
+ 
+ if CONFIG['CC_TYPE'] in ('msvc', 'clang-cl'):
+-    if CONFIG['OS_TEST'] == 'x86_64':
++    if CONFIG['OS_TEST'] == 'x86_64' or CONFIG['CC_TYPE'] == 'clang-cl':
+         SOURCES += [
+             'yuv_row_win64.cpp',
+         ]
+     else:
+         SOURCES += [
+             'yuv_row_win.cpp',
+         ]
+ elif CONFIG['OS_ARCH'] in ('Linux', 'SunOS', 'Darwin', 'DragonFly',
+diff --git a/gfx/ycbcr/yuv_convert.cpp b/gfx/ycbcr/yuv_convert.cpp
+--- a/gfx/ycbcr/yuv_convert.cpp
++++ b/gfx/ycbcr/yuv_convert.cpp
+@@ -482,17 +482,17 @@ void ScaleYCbCrToRGB32_deprecated(const 
+     if (source_dx == kFractionMax) {  // Not scaled
+       FastConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
+                                dest_pixel, width);
+     } else if (filter & FILTER_BILINEAR_H) {
+         LinearScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
+                                  dest_pixel, width, source_dx);
+     } else {
+ // Specialized scalers and rotation.
+-#if defined(MOZILLA_MAY_SUPPORT_SSE) && defined(_MSC_VER) && defined(_M_IX86)
++#if defined(MOZILLA_MAY_SUPPORT_SSE) && defined(_MSC_VER) && defined(_M_IX86) && !defined(__clang__)
+       if(mozilla::supports_sse()) {
+         if (width == (source_width * 2)) {
+           DoubleYUVToRGB32Row_SSE(y_ptr, u_ptr, v_ptr,
+                                   dest_pixel, width);
+         } else if ((source_dx & kFractionMask) == 0) {
+           // Scaling by integer scale factor. ie half.
+           ConvertYUVToRGB32Row_SSE(y_ptr, u_ptr, v_ptr,
+                                    dest_pixel, width,
+

+ 46 - 0
rel-257/ian/patches/1423895-62a1.patch

@@ -0,0 +1,46 @@
+# HG changeset patch
+# User Emilio Cobos Alvarez <emilio@crisal.io>
+# Date 1528923668 25200
+#      Wed Jun 13 14:01:08 2018 -0700
+# Branch THUNDERBIRD_60_VERBRANCH
+# Node ID 0c42de7c105b1f4fa427a3cb99541e543d5dd4b1
+# Parent  4bcb64fd8fa1aae1bdb7a2a019a283eacb7af4ca
+Bug 1423895: Don't use the XUL stylesheet cache if the parsing mode doesn't match. r=bz a=jorgk
+
+Enigmail is loading a XUL document sheet that is @import-ed in another chrome://
+sheet.
+
+Servo keys stuff off the origin of the sheet, which we derive from the parsing
+mode (see mode_to_origin in glue.rs).
+
+MozReview-Commit-ID: LQqKmxToBKC
+
+diff --git a/layout/style/Loader.cpp b/layout/style/Loader.cpp
+--- a/layout/style/Loader.cpp
++++ b/layout/style/Loader.cpp
+@@ -935,20 +935,23 @@ nsresult Loader::CreateSheet(nsIURI* aUR
+       // This sheet came from the XUL cache or our per-document hashtable; it
+       // better be a complete sheet.
+       NS_ASSERTION(sheet->IsComplete(),
+                    "Sheet thinks it's not complete while we think it is");
+ 
+       // Make sure it hasn't been forced to have a unique inner;
+       // that is an indication that its rules have been exposed to
+       // CSSOM and so we can't use it.
+-      if (sheet->HasForcedUniqueInner()) {
++      //
++      // Similarly, if the sheet doesn't have the right parsing mode just bail.
++      if (sheet->HasForcedUniqueInner() ||
++          sheet->ParsingMode() != aParsingMode) {
+         LOG(
+             ("  Not cloning completed sheet %p because it has a "
+-             "forced unique inner",
++             "forced unique inner or the wrong parsing mode",
+              sheet.get()));
+         sheet = nullptr;
+         fromCompleteSheets = false;
+       }
+     }
+ 
+     // Then loading sheets
+     if (!sheet && !aSyncLoad) {

+ 102 - 0
rel-257/ian/patches/1424281-1-61a1.patch

@@ -0,0 +1,102 @@
+# HG changeset patch
+# User David Major <dmajor@mozilla.com>
+# Date 1520349334 18000
+# Node ID 1187ae9020bef4e101696883feb3b41ffb8724db
+# Parent  fbdee2935a9f0a949f48bf2a704a0dab3c811512
+Bug 1424281 - De-optimize some functions to work around crashes during compilation. r=froydnj
+
+diff --git a/layout/generic/nsContainerFrame.cpp b/layout/generic/nsContainerFrame.cpp
+--- a/layout/generic/nsContainerFrame.cpp
++++ b/layout/generic/nsContainerFrame.cpp
+@@ -970,16 +970,24 @@ void nsContainerFrame::PositionChildView
+  *
+  * Flags:
+  * NS_FRAME_NO_MOVE_FRAME - don't move the frame. aX and aY are ignored in this
+  *    case. Also implies NS_FRAME_NO_MOVE_VIEW
+  * NS_FRAME_NO_MOVE_VIEW - don't position the frame's view. Set this if you
+  *    don't want to automatically sync the frame and view
+  * NS_FRAME_NO_SIZE_VIEW - don't size the frame's view
+  */
++
++/**
++ * De-optimize function to work around a VC2017 15.5+ compiler bug:
++ * https://bugzil.la/1424281#c12
++ */
++#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_AMD64)
++#pragma optimize("g", off)
++#endif
+ void nsContainerFrame::FinishReflowChild(
+     nsIFrame* aKidFrame, nsPresContext* aPresContext,
+     const ReflowOutput& aDesiredSize, const ReflowInput* aReflowInput,
+     const WritingMode& aWM, const LogicalPoint& aPos,
+     const nsSize& aContainerSize, uint32_t aFlags) {
+   if (aWM.IsVerticalRL() || (!aWM.IsVertical() && !aWM.IsBidiLTR())) {
+     NS_ASSERTION(aContainerSize.width != NS_UNCONSTRAINEDSIZE,
+                  "FinishReflowChild with unconstrained container width!");
+@@ -1011,16 +1019,19 @@ void nsContainerFrame::FinishReflowChild
+       // If the frame has moved, then we need to make sure any child views are
+       // correctly positioned
+       PositionChildViews(aKidFrame);
+     }
+   }
+ 
+   aKidFrame->DidReflow(aPresContext, aReflowInput);
+ }
++#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_AMD64)
++#pragma optimize("", on)
++#endif
+ 
+ // XXX temporary: hold on to a copy of the old physical version of
+ //    FinishReflowChild so that we can convert callers incrementally.
+ void nsContainerFrame::FinishReflowChild(nsIFrame* aKidFrame,
+                                          nsPresContext* aPresContext,
+                                          const ReflowOutput& aDesiredSize,
+                                          const ReflowInput* aReflowInput,
+                                          nscoord aX, nscoord aY,
+diff --git a/third_party/aom/av1/encoder/x86/hybrid_fwd_txfm_avx2.c b/third_party/aom/av1/encoder/x86/hybrid_fwd_txfm_avx2.c
+--- a/third_party/aom/av1/encoder/x86/hybrid_fwd_txfm_avx2.c
++++ b/third_party/aom/av1/encoder/x86/hybrid_fwd_txfm_avx2.c
+@@ -166,16 +166,21 @@ static void right_shift_16x16(__m256i *i
+   in[10] = _mm256_srai_epi16(in[10], 2);
+   in[11] = _mm256_srai_epi16(in[11], 2);
+   in[12] = _mm256_srai_epi16(in[12], 2);
+   in[13] = _mm256_srai_epi16(in[13], 2);
+   in[14] = _mm256_srai_epi16(in[14], 2);
+   in[15] = _mm256_srai_epi16(in[15], 2);
+ }
+ 
++// Work around bugs in Visual Studio 2017 15.6 profile-guided optimization.
++#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_IX86)
++#pragma optimize("g", off)
++#endif
++
+ static void fdct16_avx2(__m256i *in) {
+   // sequence: cospi_L_H = pairs(L, H) and L first
+   const __m256i cospi_p16_m16 = pair256_set_epi16(cospi_16_64, -cospi_16_64);
+   const __m256i cospi_p16_p16 = pair256_set_epi16(cospi_16_64, cospi_16_64);
+   const __m256i cospi_p24_p08 = pair256_set_epi16(cospi_24_64, cospi_8_64);
+   const __m256i cospi_m08_p24 = pair256_set_epi16(-cospi_8_64, cospi_24_64);
+   const __m256i cospi_m24_m08 = pair256_set_epi16(-cospi_24_64, -cospi_8_64);
+ 
+@@ -355,16 +360,21 @@ static void fdct16_avx2(__m256i *in) {
+   in[11] = butter_fly(&x0, &x1, &cospi_m10_p22);
+ 
+   x0 = _mm256_unpacklo_epi16(u3, u4);
+   x1 = _mm256_unpackhi_epi16(u3, u4);
+   in[13] = butter_fly(&x0, &x1, &cospi_p06_p26);
+   in[3] = butter_fly(&x0, &x1, &cospi_m26_p06);
+ }
+ 
++// Work around bugs in Visual Studio 2017 15.6 profile-guided optimization.
++#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_IX86)
++#pragma optimize("", on)
++#endif
++
+ void fadst16_avx2(__m256i *in) {
+   const __m256i cospi_p01_p31 = pair256_set_epi16(cospi_1_64, cospi_31_64);
+   const __m256i cospi_p31_m01 = pair256_set_epi16(cospi_31_64, -cospi_1_64);
+   const __m256i cospi_p05_p27 = pair256_set_epi16(cospi_5_64, cospi_27_64);
+   const __m256i cospi_p27_m05 = pair256_set_epi16(cospi_27_64, -cospi_5_64);
+   const __m256i cospi_p09_p23 = pair256_set_epi16(cospi_9_64, cospi_23_64);
+   const __m256i cospi_p23_m09 = pair256_set_epi16(cospi_23_64, -cospi_9_64);
+   const __m256i cospi_p13_p19 = pair256_set_epi16(cospi_13_64, cospi_19_64);

+ 304 - 0
rel-257/ian/patches/1424281-2-61a1.patch

@@ -0,0 +1,304 @@
+# HG changeset patch
+# User Ryan VanderMeulen <ryanvm@gmail.com>
+# Date 1520897084 14400
+# Node ID 87b446c458d34e890ca43f6c181e3681eec0a4ab
+# Parent  1ce242f2869d95725df227b435c69c59f1e13528
+Bug 1424281 - Use Visual Studio 2017 15.6.0 for Windows builds. r=froydnj
+
+diff --git a/browser/config/tooltool-manifests/win32/releng.manifest b/browser/config/tooltool-manifests/win32/releng.manifest
+--- a/browser/config/tooltool-manifests/win32/releng.manifest
++++ b/browser/config/tooltool-manifests/win32/releng.manifest
+@@ -1,21 +1,21 @@
+ [
+   {
+     "size": 266240,
+     "digest": "bb345b0e700ffab4d09436981f14b5de84da55a3f18a7f09ebc4364a4488acdeab8d46f447b12ac70f2da1444a68b8ce8b8675f0dae2ccf845e966d1df0f0869",
+     "algorithm": "sha512",
+     "filename": "mozmake.exe"
+   },
+   {
+-    "version": "Visual Studio 2017 15.4.2 / SDK 10.0.15063.0",
+-    "digest": "18700889e6b5e81613b9cf57ce4e0d46a6ee45bb4c5c33bae2604a5275326128775b8a032a1eb178c5db973746d565340c4e36d98375789e1d5bd836ab16ba58",
+-    "size": 303146863,
++    "version": "Visual Studio 2017 15.6.0 / SDK 10.0.15063.0",
++    "digest": "f99285fa6328da3c21839adabe6fc4dd1a792bcb6048a491ba7617a8ce3d0e21f8d18e9de03b65c90ce5bf37073637ba7c1497fb21ce920b6794d2c9819b4f9e",
++    "size": 309779153,
+     "algorithm": "sha512",
+-    "filename": "vs2017_15.4.2.zip",
++    "filename": "vs2017_15.6.0.zip",
+     "unpack": true
+   },
+   {
+     "version": "makecab rev d2bc6797648b7a834782714a55d339d2fd4e58c8",
+     "algorithm": "sha512",
+     "visibility": "public",
+     "filename": "makecab.tar.bz2",
+     "unpack": true,
+diff --git a/browser/config/tooltool-manifests/win64/releng.manifest b/browser/config/tooltool-manifests/win64/releng.manifest
+--- a/browser/config/tooltool-manifests/win64/releng.manifest
++++ b/browser/config/tooltool-manifests/win64/releng.manifest
+@@ -1,21 +1,21 @@
+ [
+   {
+     "size": 266240,
+     "digest": "bb345b0e700ffab4d09436981f14b5de84da55a3f18a7f09ebc4364a4488acdeab8d46f447b12ac70f2da1444a68b8ce8b8675f0dae2ccf845e966d1df0f0869",
+     "algorithm": "sha512",
+     "filename": "mozmake.exe"
+   },
+   {
+-    "version": "Visual Studio 2017 15.4.2 / SDK 10.0.15063.0",
+-    "digest": "18700889e6b5e81613b9cf57ce4e0d46a6ee45bb4c5c33bae2604a5275326128775b8a032a1eb178c5db973746d565340c4e36d98375789e1d5bd836ab16ba58",
+-    "size": 303146863,
++    "version": "Visual Studio 2017 15.6.0 / SDK 10.0.15063.0",
++    "digest": "f99285fa6328da3c21839adabe6fc4dd1a792bcb6048a491ba7617a8ce3d0e21f8d18e9de03b65c90ce5bf37073637ba7c1497fb21ce920b6794d2c9819b4f9e",
++    "size": 309779153,
+     "algorithm": "sha512",
+-    "filename": "vs2017_15.4.2.zip",
++    "filename": "vs2017_15.6.0.zip",
+     "unpack": true
+   },
+   {
+     "version": "makecab rev d2bc6797648b7a834782714a55d339d2fd4e58c8",
+     "algorithm": "sha512",
+     "visibility": "public",
+     "filename": "makecab.tar.bz2",
+     "unpack": true,
+diff --git a/build/build-clang/build-clang.py b/build/build-clang/build-clang.py
+--- a/build/build-clang/build-clang.py
++++ b/build/build-clang/build-clang.py
+@@ -523,17 +523,17 @@ if __name__ == "__main__":
+             os.environ['LD_LIBRARY_PATH'] = '%s/lib64/' % gcc_dir
+     elif is_windows():
+         extra_cflags = []
+         extra_cxxflags = []
+         # clang-cl would like to figure out what it's supposed to be emulating
+         # by looking at an MSVC install, but we don't really have that here.
+         # Force things on.
+         extra_cflags2 = []
+-        extra_cxxflags2 = ['-fms-compatibility-version=19.11.25547', '-Xclang', '-std=c++14']
++        extra_cxxflags2 = ['-fms-compatibility-version=19.13.26128', '-Xclang', '-std=c++14']
+         extra_asmflags = []
+         extra_ldflags = []
+ 
+     if osx_cross_compile:
+         # undo the damage done in the is_linux() block above, and also simulate
+         # the is_darwin() block above.
+         extra_cflags = []
+         extra_cxxflags = ["-stdlib=libc++"]
+diff --git a/build/docs/toolchains.rst b/build/docs/toolchains.rst
+--- a/build/docs/toolchains.rst
++++ b/build/docs/toolchains.rst
+@@ -31,32 +31,32 @@ publicly. However, the same tool can be 
+ Configuring Your System
+ -----------------------
+ 
+ It is **highly** recommended to perform this process on a fresh installation
+ of Windows 7 or 10 (such as in a VM). Installing all updates through
+ Windows Update is not only acceptable - it is encouraged. Although it
+ shouldn't matter.
+ 
+-Next, install Visual Studio 2015 Community. The download link can be
+-found at https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx.
++Next, install Visual Studio 2017 Community. The download link can be found
++at https://www.visualstudio.com/vs/community/.
+ Be sure to follow these install instructions:
+ 
+ 1. Choose a ``Custom`` installation and click ``Next``
+ 2. Select ``Programming Languages`` -> ``Visual C++`` (make sure all sub items are
+    selected)
+ 3. Under ``Windows and Web Development`` uncheck everything except
+    ``Universal Windows App Development Tools`` and the items under it
+    (should be ``Tools (1.3.1)...`` and the ``Windows 10 SDK``).
+ 
+-Once Visual Studio 2015 Community has been installed, from a checkout
++Once Visual Studio 2017 Community has been installed, from a checkout
+ of mozilla-central, run something like the following to produce a ZIP
+ archive::
+ 
+-   $ ./mach python build/windows_toolchain.py create-zip vs2017_15.4.2
++   $ ./mach python build/windows_toolchain.py create-zip vs2017_15.6.0
+ 
+ The produced archive will be the argument to ``create-zip`` + ``.zip``.
+ 
+ Firefox for Android with Gradle
+ ===============================
+ 
+ To build Firefox for Android with Gradle in automation, archives
+ containing both the Gradle executable and a Maven repository
+diff --git a/build/moz.configure/toolchain.configure b/build/moz.configure/toolchain.configure
+--- a/build/moz.configure/toolchain.configure
++++ b/build/moz.configure/toolchain.configure
+@@ -502,21 +502,22 @@ def check_compiler(compiler, language, t
+             append_flag('-std=c++14')
+         # GCC 4.9 indicates that it implements draft C++14 features
+         # instead of the full language.
+         elif info.type == 'gcc' and \
+                 info.language_version not in (draft_cxx14_version,
+                                               cxx14_version):
+             append_flag('-std=gnu++14')
+ 
+-    # We force clang-cl to emulate Visual C++ 2017 version 15.4
+-    if info.type == 'clang-cl' and info.version != '19.11.25547':
++    # We force clang-cl to emulate Visual C++ 2017 version 15.6.0
++    msvc_version = '19.13.26128'
++    if info.type == 'clang-cl' and info.version != msvc_version:
+         # This flag is a direct clang-cl flag that doesn't need -Xclang,
+         # add it directly.
+-        flags.append('-fms-compatibility-version=19.11.25547')
++        flags.append('-fms-compatibility-version=%s' % msvc_version)
+ 
+     # Check compiler target
+     # --------------------------------------------------------------------
+     if not info.cpu or info.cpu != target.cpu:
+         if info.type == 'clang':
+             append_flag('--target=%s' % target.toolchain)
+         elif info.type == 'clang-cl':
+             # Ideally this would share the 'clang' branch above, but on Windows
+diff --git a/build/win32/mozconfig.vs2017 b/build/win32/mozconfig.vs2017
+--- a/build/win32/mozconfig.vs2017
++++ b/build/win32/mozconfig.vs2017
+@@ -1,11 +1,11 @@
+ if [ -z "${VSPATH}" ]; then
+     TOOLTOOL_DIR=${TOOLTOOL_DIR:-$topsrcdir}
+-    VSPATH="$(cd ${TOOLTOOL_DIR} && pwd)/vs2017_15.4.2"
++    VSPATH="$(cd ${TOOLTOOL_DIR} && pwd)/vs2017_15.6.0"
+ fi
+ 
+ if [ -d "${VSPATH}" ]; then
+     VSWINPATH="$(cd ${VSPATH} && pwd -W)"
+ 
+     export WINDOWSSDKDIR="${VSWINPATH}/SDK"
+     export WIN32_REDIST_DIR="${VSPATH}/VC/redist/x86/Microsoft.VC141.CRT"
+     export WIN_UCRT_REDIST_DIR="${VSPATH}/SDK/Redist/ucrt/DLLs/x86"
+diff --git a/build/win64/mozconfig.vs2017 b/build/win64/mozconfig.vs2017
+--- a/build/win64/mozconfig.vs2017
++++ b/build/win64/mozconfig.vs2017
+@@ -1,11 +1,11 @@
+ if [ -z "${VSPATH}" ]; then
+     TOOLTOOL_DIR=${TOOLTOOL_DIR:-$topsrcdir}
+-    VSPATH="$(cd ${TOOLTOOL_DIR} && pwd)/vs2017_15.4.2"
++    VSPATH="$(cd ${TOOLTOOL_DIR} && pwd)/vs2017_15.6.0"
+ fi
+ 
+ if [ -d "${VSPATH}" ]; then
+     VSWINPATH="$(cd ${VSPATH} && pwd -W)"
+ 
+     export WINDOWSSDKDIR="${VSWINPATH}/SDK"
+     export WIN32_REDIST_DIR=${VSPATH}/VC/redist/x64/Microsoft.VC141.CRT
+     export WIN_UCRT_REDIST_DIR="${VSPATH}/SDK/Redist/ucrt/DLLs/x64"
+diff --git a/build/windows_toolchain.py b/build/windows_toolchain.py
+--- a/build/windows_toolchain.py
++++ b/build/windows_toolchain.py
+@@ -47,17 +47,17 @@ PATTERNS = [
+                 'pattern': 'lib/**',
+                 'ignore': (
+                     'lib/arm/**',
+                 ),
+             },
+         ],
+     },
+     {
+-        'srcdir': '%(vs_path)s/VC/Tools/MSVC/14.11.25503',
++        'srcdir': '%(vs_path)s/VC/Tools/MSVC/14.13.26128',
+         'dstdir': 'VC',
+         'files': [
+             # ATL is needed by Breakpad.
+             {
+                 'pattern': 'atlmfc/include/**',
+             },
+             {
+                 'pattern': 'atlmfc/lib/x86/atls.*',
+@@ -81,17 +81,17 @@ PATTERNS = [
+                     'lib/onecore/**',
+                     'lib/x64/store/**',
+                     'lib/x86/store/**',
+                 ),
+             },
+         ],
+     },
+     {
+-        'srcdir': '%(vs_path)s/VC/Redist/MSVC/14.11.25325',
++        'srcdir': '%(vs_path)s/VC/Redist/MSVC/14.13.26020',
+         'dstdir': 'VC/redist',
+         'files': [
+             {
+                 'pattern': 'x64/Microsoft.VC141.CRT/**',
+             },
+             {
+                 'pattern': 'x86/Microsoft.VC141.CRT/**',
+             },
+diff --git a/js/src/devtools/automation/winbuildenv.sh b/js/src/devtools/automation/winbuildenv.sh
+--- a/js/src/devtools/automation/winbuildenv.sh
++++ b/js/src/devtools/automation/winbuildenv.sh
+@@ -5,17 +5,17 @@ mk_add_options() {
+   echo "$@"
+ }
+ 
+ topsrcdir="$SOURCE"
+ 
+ # Tooltool installs in parent of topsrcdir for spidermonkey builds.
+ # Resolve that path since the mozconfigs assume tooltool installs in
+ # topsrcdir.
+-export VSPATH="$(cd ${topsrcdir}/.. && pwd)/vs2017_15.4.2"
++export VSPATH="$(cd ${topsrcdir}/.. && pwd)/vs2017_15.6.0"
+ 
+ # When running on a developer machine, several variables will already
+ # have the right settings and we will need to keep them since the
+ # Windows mozconfigs overwrite them.
+ echo "export ORIGINAL_INCLUDE=$INCLUDE"
+ echo "export ORIGINAL_LIB=$LIB"
+ echo "export ORIGINAL_LIBPATH=$LIBPATH"
+ 
+diff --git a/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py b/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
+--- a/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
++++ b/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
+@@ -251,17 +251,17 @@ VS_PLATFORM_X86_64 = {
+ # Note: In reality, the -std=gnu* options are only supported when preceded by
+ # -Xclang.
+ CLANG_CL_3_9 = (CLANG_BASE('3.9.0') + VS('18.00.00000') + DEFAULT_C11 +
+                 SUPPORTS_GNU99 + SUPPORTS_GNUXX11 + SUPPORTS_CXX14) + {
+     '*.cpp': {
+         '__STDC_VERSION__': False,
+         '__cplusplus': '201103L',
+     },
+-    '-fms-compatibility-version=19.11.25547': VS('19.11.25547')[None],
++    '-fms-compatibility-version=19.13.26128': VS('19.13.26128')[None],
+ }
+ 
+ CLANG_CL_PLATFORM_X86 = FakeCompiler(VS_PLATFORM_X86, GCC_PLATFORM_X86[None])
+ CLANG_CL_PLATFORM_X86_64 = FakeCompiler(VS_PLATFORM_X86_64, GCC_PLATFORM_X86_64[None])
+ 
+ LIBRARY_NAME_INFOS = {
+     'linux-gnu': {
+         'DLL_PREFIX': 'lib',
+@@ -894,26 +894,26 @@ class WindowsToolchainTest(BaseToolchain
+         flags=[],
+         version='19.00.24213',
+         type='msvc',
+         compiler='/usr/bin/cl',
+         language='C++',
+     )
+     CLANG_CL_3_9_RESULT = CompilerResult(
+         flags=['-Xclang', '-std=gnu99',
+-               '-fms-compatibility-version=19.11.25547'],
+-        version='19.11.25547',
++               '-fms-compatibility-version=19.13.26128'],
++        version='19.13.26128',
+         type='clang-cl',
+         compiler='/usr/bin/clang-cl',
+         language='C',
+     )
+     CLANGXX_CL_3_9_RESULT = CompilerResult(
+         flags=['-Xclang', '-std=c++14',
+-               '-fms-compatibility-version=19.11.25547'],
+-        version='19.11.25547',
++               '-fms-compatibility-version=19.13.26128'],
++        version='19.13.26128',
+         type='clang-cl',
+         compiler='/usr/bin/clang-cl',
+         language='C++',
+     )
+     CLANG_3_3_RESULT = LinuxToolchainTest.CLANG_3_3_RESULT
+     CLANGXX_3_3_RESULT = LinuxToolchainTest.CLANGXX_3_3_RESULT
+     CLANG_3_6_RESULT = LinuxToolchainTest.CLANG_3_6_RESULT
+     CLANGXX_3_6_RESULT = LinuxToolchainTest.CLANGXX_3_6_RESULT

+ 275 - 0
rel-257/ian/patches/1424281-3-61a1.patch

@@ -0,0 +1,275 @@
+# HG changeset patch
+# User Ryan VanderMeulen <ryanvm@gmail.com>
+# Date 1520897084 14400
+# Node ID a7ab282e1d4a1aa1726017a05e04102c7adc9e33
+# Parent  90e86627fa01e2b0ce0a103c0fde9209c8583014
+Bug 1424281 - Require Visual Studio 2017 15.6.0 and Win SDK 10.0.15063.0 to build on Windows. r=froydnj
+
+diff --git a/build/moz.configure/toolchain.configure b/build/moz.configure/toolchain.configure
+--- a/build/moz.configure/toolchain.configure
++++ b/build/moz.configure/toolchain.configure
+@@ -915,35 +915,25 @@ def compiler(language, host_or_target, c
+ 
+         # If you want to bump the version check here search for
+         # cxx_alignof above, and see the associated comment.
+         if info.type == 'clang' and not info.version:
+             raise FatalCheckError(
+                 'Only clang/llvm 3.6 or newer is supported.')
+ 
+         if info.type == 'msvc':
+-            # 19.00 is VS2015.
+-            # 19.10+ is VS2017+.
+-            if info.version < '19.00.24213':
++            if info.version < '19.13.26128':
+                 raise FatalCheckError(
+                     'This version (%s) of the MSVC compiler is not '
+                     'supported.\n'
+-                    'You must install Visual C++ 2015 Update 3 or newer in '
++                    'You must install Visual C++ 2017 Update 6 or newer in '
+                     'order to build.\n'
+                     'See https://developer.mozilla.org/en/'
+                     'Windows_Build_Prerequisites' % info.version)
+ 
+-            if info.version >= '19.10' and info.version < '19.11.25506':
+-                raise FatalCheckError(
+-                    'This version (%s) of the MSVC compiler is not supported.\n'
+-                    'You must install Visual C++ 2017 15.3 or newer in order '
+-                    'to build.\n'
+-                    'See https://developer.mozilla.org/en/'
+-                    'Windows_Build_Prerequisites' % info.version)
+-
+         if info.flags:
+             raise FatalCheckError(
+                 'Unknown compiler or compiler not supported.')
+ 
+         return namespace(
+             wrapper=wrapper,
+             compiler=compiler,
+             flags=flags,
+diff --git a/build/moz.configure/windows.configure b/build/moz.configure/windows.configure
+--- a/build/moz.configure/windows.configure
++++ b/build/moz.configure/windows.configure
+@@ -223,17 +223,17 @@ def valid_ucrt_sdk_dir(windows_sdk_dir, 
+                 'CRT.' % windows_sdk_dir_env)
+ 
+     valid_sdks = sorted(sdks, key=lambda x: sdks[x][0], reverse=True)
+     if not valid_sdks:
+         raise FatalCheckError('Cannot find the Universal CRT SDK. '
+                               'Please install it.')
+ 
+     version, sdk = sdks[valid_sdks[0]]
+-    minimum_ucrt_version = Version('10.0.14393.0')
++    minimum_ucrt_version = Version('10.0.15063.0')
+     if version < minimum_ucrt_version:
+         raise FatalCheckError('Latest Universal CRT SDK version found %s'
+                               ' and minimum required is %s. This or a later'
+                               ' version can be installed using the Visual'
+                               ' Studio installer.'
+                               % (version, minimum_ucrt_version))
+ 
+     broken_ucrt_version = Version('10.0.16299.0')
+diff --git a/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py b/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
+--- a/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
++++ b/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
+@@ -231,16 +231,18 @@ def VS(version):
+ 
+ 
+ VS_2013u2 = VS('18.00.30501')
+ VS_2013u3 = VS('18.00.30723')
+ VS_2015 = VS('19.00.23026')
+ VS_2015u1 = VS('19.00.23506')
+ VS_2015u2 = VS('19.00.23918')
+ VS_2015u3 = VS('19.00.24213')
++VS_2017u4 = VS('19.11.25547')
++VS_2017u6 = VS('19.13.26128')
+ 
+ VS_PLATFORM_X86 = {
+     '_M_IX86': 600,
+     '_WIN32': 1,
+ }
+ 
+ VS_PLATFORM_X86_64 = {
+     '_M_X64': 100,
+@@ -842,17 +844,19 @@ class WindowsToolchainTest(BaseToolchain
+     # For the purpose of this test, it doesn't matter that the paths are not
+     # real Windows paths.
+     PATHS = {
+         '/opt/VS_2013u2/bin/cl': VS_2013u2 + VS_PLATFORM_X86,
+         '/opt/VS_2013u3/bin/cl': VS_2013u3 + VS_PLATFORM_X86,
+         '/opt/VS_2015/bin/cl': VS_2015 + VS_PLATFORM_X86,
+         '/opt/VS_2015u1/bin/cl': VS_2015u1 + VS_PLATFORM_X86,
+         '/opt/VS_2015u2/bin/cl': VS_2015u2 + VS_PLATFORM_X86,
+-        '/usr/bin/cl': VS_2015u3 + VS_PLATFORM_X86,
++        '/opt/VS_2015u3/bin/cl': VS_2015u3 + VS_PLATFORM_X86,
++        '/opt/VS_2017u4/bin/cl': VS_2017u4 + VS_PLATFORM_X86,
++        '/usr/bin/cl': VS_2017u6 + VS_PLATFORM_X86,
+         '/usr/bin/clang-cl': CLANG_CL_3_9 + CLANG_CL_PLATFORM_X86,
+         '/usr/bin/gcc': GCC_4_9 + GCC_PLATFORM_X86_WIN,
+         '/usr/bin/g++': GXX_4_9 + GCC_PLATFORM_X86_WIN,
+         '/usr/bin/gcc-4.7': GCC_4_7 + GCC_PLATFORM_X86_WIN,
+         '/usr/bin/g++-4.7': GXX_4_7 + GCC_PLATFORM_X86_WIN,
+         '/usr/bin/gcc-5': GCC_5 + GCC_PLATFORM_X86_WIN,
+         '/usr/bin/g++-5': GXX_5 + GCC_PLATFORM_X86_WIN,
+         '/usr/bin/clang': CLANG_3_6 + CLANG_PLATFORM_X86_WIN,
+@@ -860,44 +864,52 @@ class WindowsToolchainTest(BaseToolchain
+         '/usr/bin/clang-3.6': CLANG_3_6 + CLANG_PLATFORM_X86_WIN,
+         '/usr/bin/clang++-3.6': CLANGXX_3_6 + CLANG_PLATFORM_X86_WIN,
+         '/usr/bin/clang-3.3': CLANG_3_3 + CLANG_PLATFORM_X86_WIN,
+         '/usr/bin/clang++-3.3': CLANGXX_3_3 + CLANG_PLATFORM_X86_WIN,
+     }
+ 
+     VS_2013u2_RESULT = (
+         'This version (18.00.30501) of the MSVC compiler is not supported.\n'
+-        'You must install Visual C++ 2015 Update 3 or newer in order to build.\n'
++        'You must install Visual C++ 2017 Update 6 or newer in order to build.\n'
+         'See https://developer.mozilla.org/en/Windows_Build_Prerequisites')
+     VS_2013u3_RESULT = (
+         'This version (18.00.30723) of the MSVC compiler is not supported.\n'
+-        'You must install Visual C++ 2015 Update 3 or newer in order to build.\n'
++        'You must install Visual C++ 2017 Update 6 or newer in order to build.\n'
+         'See https://developer.mozilla.org/en/Windows_Build_Prerequisites')
+     VS_2015_RESULT = (
+         'This version (19.00.23026) of the MSVC compiler is not supported.\n'
+-        'You must install Visual C++ 2015 Update 3 or newer in order to build.\n'
++        'You must install Visual C++ 2017 Update 6 or newer in order to build.\n'
+         'See https://developer.mozilla.org/en/Windows_Build_Prerequisites')
+     VS_2015u1_RESULT = (
+         'This version (19.00.23506) of the MSVC compiler is not supported.\n'
+-        'You must install Visual C++ 2015 Update 3 or newer in order to build.\n'
++        'You must install Visual C++ 2017 Update 6 or newer in order to build.\n'
+         'See https://developer.mozilla.org/en/Windows_Build_Prerequisites')
+     VS_2015u2_RESULT = (
+         'This version (19.00.23918) of the MSVC compiler is not supported.\n'
+-        'You must install Visual C++ 2015 Update 3 or newer in order to build.\n'
++        'You must install Visual C++ 2017 Update 6 or newer in order to build.\n'
++        'See https://developer.mozilla.org/en/Windows_Build_Prerequisites')
++    VS_2015u3_RESULT = (
++        'This version (19.00.24213) of the MSVC compiler is not supported.\n'
++        'You must install Visual C++ 2017 Update 6 or newer in order to build.\n'
+         'See https://developer.mozilla.org/en/Windows_Build_Prerequisites')
+-    VS_2015u3_RESULT = CompilerResult(
++    VS_2017u4_RESULT = (
++        'This version (19.11.25547) of the MSVC compiler is not supported.\n'
++        'You must install Visual C++ 2017 Update 6 or newer in order to build.\n'
++        'See https://developer.mozilla.org/en/Windows_Build_Prerequisites')
++    VS_2017u6_RESULT = CompilerResult(
+         flags=[],
+-        version='19.00.24213',
++        version='19.13.26128',
+         type='msvc',
+         compiler='/usr/bin/cl',
+         language='C',
+     )
+-    VSXX_2015u3_RESULT = CompilerResult(
++    VSXX_2017u6_RESULT = CompilerResult(
+         flags=[],
+-        version='19.00.24213',
++        version='19.13.26128',
+         type='msvc',
+         compiler='/usr/bin/cl',
+         language='C++',
+     )
+     CLANG_CL_3_9_RESULT = CompilerResult(
+         flags=['-Xclang', '-std=gnu99',
+                '-fms-compatibility-version=19.13.26128'],
+         version='19.13.26128',
+@@ -930,25 +942,37 @@ class WindowsToolchainTest(BaseToolchain
+     GXX_5_RESULT = CompilerResult(
+         flags=['-std=gnu++14'],
+         version='5.2.1',
+         type='gcc',
+         compiler='/usr/bin/g++-5',
+         language='C++',
+     )
+ 
+-    # VS2015u3 or greater is required.
++    # VS2017u6 or greater is required.
+     def test_msvc(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.VS_2015u3_RESULT,
+-            'cxx_compiler': self.VSXX_2015u3_RESULT,
++            'c_compiler': self.VS_2017u6_RESULT,
++            'cxx_compiler': self.VSXX_2017u6_RESULT,
+         })
+ 
+     def test_unsupported_msvc(self):
+         self.do_toolchain_test(self.PATHS, {
++            'c_compiler': self.VS_2017u4_RESULT,
++        }, environ={
++            'CC': '/opt/VS_2017u4/bin/cl',
++        })
++
++        self.do_toolchain_test(self.PATHS, {
++            'c_compiler': self.VS_2015u3_RESULT,
++        }, environ={
++            'CC': '/opt/VS_2015u3/bin/cl',
++        })
++
++        self.do_toolchain_test(self.PATHS, {
+             'c_compiler': self.VS_2015u2_RESULT,
+         }, environ={
+             'CC': '/opt/VS_2015u2/bin/cl',
+         })
+ 
+         self.do_toolchain_test(self.PATHS, {
+             'c_compiler': self.VS_2015u1_RESULT,
+         }, environ={
+@@ -1021,17 +1045,17 @@ class WindowsToolchainTest(BaseToolchain
+             'cxx_compiler': self.CLANGXX_3_3_RESULT,
+         }, environ={
+             'CC': 'clang-3.3',
+             'CXX': 'clang++-3.3',
+         })
+ 
+     def test_cannot_cross(self):
+         paths = {
+-            '/usr/bin/cl': VS_2015u3 + VS_PLATFORM_X86_64,
++            '/usr/bin/cl': VS_2017u6 + VS_PLATFORM_X86_64,
+         }
+         self.do_toolchain_test(paths, {
+             'c_compiler': ('Target C compiler target CPU (x86_64) '
+                            'does not match --target CPU (i686)'),
+         })
+ 
+ 
+ class Windows64ToolchainTest(WindowsToolchainTest):
+@@ -1040,17 +1064,19 @@ class Windows64ToolchainTest(WindowsTool
+     # For the purpose of this test, it doesn't matter that the paths are not
+     # real Windows paths.
+     PATHS = {
+         '/opt/VS_2013u2/bin/cl': VS_2013u2 + VS_PLATFORM_X86_64,
+         '/opt/VS_2013u3/bin/cl': VS_2013u3 + VS_PLATFORM_X86_64,
+         '/opt/VS_2015/bin/cl': VS_2015 + VS_PLATFORM_X86_64,
+         '/opt/VS_2015u1/bin/cl': VS_2015u1 + VS_PLATFORM_X86_64,
+         '/opt/VS_2015u2/bin/cl': VS_2015u2 + VS_PLATFORM_X86_64,
+-        '/usr/bin/cl': VS_2015u3 + VS_PLATFORM_X86_64,
++        '/opt/VS_2015u3/bin/cl': VS_2015u3 + VS_PLATFORM_X86_64,
++        '/opt/VS_2017u4/bin/cl': VS_2017u4 + VS_PLATFORM_X86_64,
++        '/usr/bin/cl': VS_2017u6 + VS_PLATFORM_X86_64,
+         '/usr/bin/clang-cl': CLANG_CL_3_9 + CLANG_CL_PLATFORM_X86_64,
+         '/usr/bin/gcc': GCC_4_9 + GCC_PLATFORM_X86_64_WIN,
+         '/usr/bin/g++': GXX_4_9 + GCC_PLATFORM_X86_64_WIN,
+         '/usr/bin/gcc-4.7': GCC_4_7 + GCC_PLATFORM_X86_64_WIN,
+         '/usr/bin/g++-4.7': GXX_4_7 + GCC_PLATFORM_X86_64_WIN,
+         '/usr/bin/gcc-5': GCC_5 + GCC_PLATFORM_X86_64_WIN,
+         '/usr/bin/g++-5': GXX_5 + GCC_PLATFORM_X86_64_WIN,
+         '/usr/bin/clang': CLANG_3_6 + CLANG_PLATFORM_X86_64_WIN,
+@@ -1058,17 +1084,17 @@ class Windows64ToolchainTest(WindowsTool
+         '/usr/bin/clang-3.6': CLANG_3_6 + CLANG_PLATFORM_X86_64_WIN,
+         '/usr/bin/clang++-3.6': CLANGXX_3_6 + CLANG_PLATFORM_X86_64_WIN,
+         '/usr/bin/clang-3.3': CLANG_3_3 + CLANG_PLATFORM_X86_64_WIN,
+         '/usr/bin/clang++-3.3': CLANGXX_3_3 + CLANG_PLATFORM_X86_64_WIN,
+     }
+ 
+     def test_cannot_cross(self):
+         paths = {
+-            '/usr/bin/cl': VS_2015u3 + VS_PLATFORM_X86,
++            '/usr/bin/cl': VS_2017u6 + VS_PLATFORM_X86,
+         }
+         self.do_toolchain_test(paths, {
+             'c_compiler': ('Target C compiler target CPU (x86) '
+                            'does not match --target CPU (x86_64)'),
+         })
+ 
+ 
+ class LinuxCrossCompileToolchainTest(BaseToolchainTest):

+ 234 - 0
rel-257/ian/patches/1429016-67a1.patch

@@ -0,0 +1,234 @@
+# HG changeset patch
+# User ui.manish <1991manish.kumar@gmail.com>
+# Date 1550915768 0
+# Node ID 9eb8e5cca281f47dbdcc9b43baba61a82d68258a
+# Parent  e4df812ff61b876f4c9f5880ba5c9fefda46f528
+Bug 1429016 - Remove expiring WEB_NOTIFICATION_* telemetry probes r=MattN
+
+Differential Revision: https://phabricator.services.mozilla.com/D18877
+
+diff --git a/browser/components/preferences/in-content/privacy.js b/browser/components/preferences/in-content/privacy.js
+--- a/browser/components/preferences/in-content/privacy.js
++++ b/browser/components/preferences/in-content/privacy.js
+@@ -1035,21 +1035,16 @@ var gPrivacyPane = {
+     let params = { permissionType: "desktop-notification" };
+     params.windowTitle = bundlePreferences.getString("notificationspermissionstitle2");
+     params.introText = bundlePreferences.getString("notificationspermissionstext6");
+     params.disablePermissionsLabel = bundlePreferences.getString("notificationspermissionsdisablelabel");
+     params.disablePermissionsDescription = bundlePreferences.getString("notificationspermissionsdisabledescription");
+ 
+     gSubDialog.open("chrome://browser/content/preferences/sitePermissions.xul",
+       "resizable=yes", params);
+-
+-    try {
+-      Services.telemetry
+-        .getHistogramById("WEB_NOTIFICATION_EXCEPTIONS_OPENED").add();
+-    } catch (e) { }
+   },
+ 
+ 
+   // POP-UPS
+ 
+   /**
+    * Displays the popup exceptions dialog where specific site popup preferences
+    * can be set.
+diff --git a/dom/notification/Notification.cpp b/dom/notification/Notification.cpp
+--- a/dom/notification/Notification.cpp
++++ b/dom/notification/Notification.cpp
+@@ -655,21 +655,16 @@ void NotificationTelemetryService::Recor
+     rv = enumerator->GetNext(getter_AddRefs(supportsPermission));
+     if (NS_WARN_IF(NS_FAILED(rv))) {
+       return;
+     }
+     uint32_t capability;
+     if (!GetNotificationPermission(supportsPermission, &capability)) {
+       continue;
+     }
+-    if (capability == nsIPermissionManager::DENY_ACTION) {
+-      Telemetry::Accumulate(Telemetry::WEB_NOTIFICATION_PERMISSIONS, 0);
+-    } else if (capability == nsIPermissionManager::ALLOW_ACTION) {
+-      Telemetry::Accumulate(Telemetry::WEB_NOTIFICATION_PERMISSIONS, 1);
+-    }
+   }
+ }
+ 
+ bool NotificationTelemetryService::GetNotificationPermission(
+     nsISupports* aSupports, uint32_t* aCapability) {
+   nsCOMPtr<nsIPermission> permission = do_QueryInterface(aSupports);
+   if (!permission) {
+     return false;
+@@ -1198,30 +1193,26 @@ class NotificationClickWorkerRunnable fi
+ };
+ 
+ NS_IMETHODIMP
+ NotificationObserver::Observe(nsISupports* aSubject, const char* aTopic,
+                               const char16_t* aData) {
+   AssertIsOnMainThread();
+ 
+   if (!strcmp("alertdisablecallback", aTopic)) {
+-    Telemetry::Accumulate(Telemetry::WEB_NOTIFICATION_MENU, 1);
+     if (XRE_IsParentProcess()) {
+       return Notification::RemovePermission(mPrincipal);
+     }
+     // Permissions can't be removed from the content process. Send a message
+     // to the parent; `ContentParent::RecvDisableNotifications` will call
+     // `RemovePermission`.
+     ContentChild::GetSingleton()->SendDisableNotifications(
+         IPC::Principal(mPrincipal));
+     return NS_OK;
+-  } else if (!strcmp("alertclickcallback", aTopic)) {
+-    Telemetry::Accumulate(Telemetry::WEB_NOTIFICATION_CLICKED, 1);
+   } else if (!strcmp("alertsettingscallback", aTopic)) {
+-    Telemetry::Accumulate(Telemetry::WEB_NOTIFICATION_MENU, 2);
+     if (XRE_IsParentProcess()) {
+       return Notification::OpenSettings(mPrincipal);
+     }
+     // `ContentParent::RecvOpenNotificationSettings` notifies observers in the
+     // parent process.
+     ContentChild::GetSingleton()->SendOpenNotificationSettings(
+         IPC::Principal(mPrincipal));
+     return NS_OK;
+@@ -1229,21 +1220,16 @@ NotificationObserver::Observe(nsISupport
+     RefPtr<NotificationTelemetryService> telemetry =
+         NotificationTelemetryService::GetInstance();
+     if (telemetry) {
+       // Record whether "do not disturb" is supported after the first
+       // notification, to account for falling back to XUL alerts.
+       telemetry->RecordDNDSupported();
+     }
+     Unused << NS_WARN_IF(NS_FAILED(AdjustPushQuota(aTopic)));
+-
+-    if (!strcmp("alertshow", aTopic)) {
+-      // Record notifications actually shown (e.g. don't count if DND is on).
+-      Telemetry::Accumulate(Telemetry::WEB_NOTIFICATION_SHOWN, 1);
+-    }
+   }
+ 
+   return mObserver->Observe(aSubject, aTopic, aData);
+ }
+ 
+ nsresult NotificationObserver::AdjustPushQuota(const char* aTopic) {
+   nsCOMPtr<nsIPushQuotaManager> pushQuotaManager =
+       do_GetService("@mozilla.org/push/Service;1");
+diff --git a/toolkit/components/alerts/resources/content/alert.js b/toolkit/components/alerts/resources/content/alert.js
+--- a/toolkit/components/alerts/resources/content/alert.js
++++ b/toolkit/components/alerts/resources/content/alert.js
+@@ -287,18 +287,16 @@ function onAlertClick() {
+   }
+ }
+ 
+ function doNotDisturb() {
+   const alertService = Cc["@mozilla.org/alerts-service;1"]
+                          .getService(Ci.nsIAlertsService)
+                          .QueryInterface(Ci.nsIAlertsDoNotDisturb);
+   alertService.manualDoNotDisturb = true;
+-  Services.telemetry.getHistogramById("WEB_NOTIFICATION_MENU")
+-                    .add(0);
+   onAlertClose();
+ }
+ 
+ function disableForOrigin() {
+   gAlertListener.observe(null, "alertdisablecallback", gAlertCookie);
+   onAlertClose();
+ }
+ 
+diff --git a/toolkit/components/telemetry/Histograms.json b/toolkit/components/telemetry/Histograms.json
+--- a/toolkit/components/telemetry/Histograms.json
++++ b/toolkit/components/telemetry/Histograms.json
+@@ -12259,43 +12259,16 @@
+     "alert_emails": ["hkirschner@mozilla.com"],
+     "bug_numbers": [1312881],
+     "expires_in_version": "58",
+     "kind": "exponential",
+     "high": 100000,
+     "n_buckets": 50,
+     "description": "Maximum distance in CSS pixels a user scrolls down the vertical axis of the root frame of a page. This doesn't include any scrolling of nested scroll frames such as inputs, iframes, or scrollable divs."
+   },
+-  "WEB_NOTIFICATION_CLICKED": {
+-    "record_in_processes": ["main", "content"],
+-    "releaseChannelCollection": "opt-out",
+-    "alert_emails": ["firefox-dev@mozilla.org", "push@mozilla.com"],
+-    "bug_numbers": [1225336, 1429286],
+-    "expires_in_version": "never",
+-    "kind": "count",
+-    "description": "Count of times a web notification was clicked"
+-  },
+-  "WEB_NOTIFICATION_MENU": {
+-    "record_in_processes": ["main", "content"],
+-    "alert_emails": ["firefox-dev@mozilla.org"],
+-    "bug_numbers": [1225336],
+-    "expires_in_version": "50",
+-    "kind": "enumerated",
+-    "n_values": 5,
+-    "description": "Count of times a contextual menu item was used from a Notification (0: DND, 1: Disable, 2: Settings)"
+-  },
+-  "WEB_NOTIFICATION_SHOWN": {
+-    "record_in_processes": ["main", "content"],
+-    "releaseChannelCollection": "opt-out",
+-    "alert_emails": ["firefox-dev@mozilla.org", "push@mozilla.com"],
+-    "bug_numbers": [1225336, 1429286],
+-    "expires_in_version": "never",
+-    "kind": "count",
+-    "description": "Count of times a Notification was rendered (accounting for XUL DND). A system backend may put the notification directly into the tray if its own DND is on."
+-  },
+   "WEBFONT_DOWNLOAD_TIME": {
+     "record_in_processes": ["main", "content"],
+     "alert_emails": ["jdaggett@mozilla.com"],
+     "expires_in_version": "never",
+     "kind": "exponential",
+     "high": 60000,
+     "n_buckets": 50,
+     "description": "Time to download a webfont (ms)"
+@@ -12385,34 +12358,16 @@
+   "ALERTS_SERVICE_DND_SUPPORTED_FLAG": {
+     "record_in_processes": ["main", "content"],
+     "alert_emails": ["firefox-dev@mozilla.org"],
+     "bug_numbers": [1219030],
+     "expires_in_version": "50",
+     "kind": "flag",
+     "description": "Whether the do not disturb option is supported. True if the browser uses XUL alerts."
+   },
+-  "WEB_NOTIFICATION_EXCEPTIONS_OPENED": {
+-    "record_in_processes": ["main", "content"],
+-    "alert_emails": ["firefox-dev@mozilla.org"],
+-    "bug_numbers": [1219030],
+-    "expires_in_version": "50",
+-    "kind": "count",
+-    "description": "Number of times the Notification Permissions dialog has been opened."
+-  },
+-  "WEB_NOTIFICATION_PERMISSIONS": {
+-    "record_in_processes": ["main", "content"],
+-    "releaseChannelCollection": "opt-out",
+-    "alert_emails": ["firefox-dev@mozilla.org", "push@mozilla.com"],
+-    "bug_numbers": [1219030, 1429286],
+-    "expires_in_version": "never",
+-    "kind": "enumerated",
+-    "n_values": 10,
+-    "description": "Number of origins with the web notifications permission (0 = denied, 1 = allowed)."
+-  },
+   "PLUGIN_DRAWING_MODEL": {
+     "record_in_processes": ["main", "content"],
+     "alert_emails": ["gfx-telemetry-alerts@mozilla.com","msreckovic@mozilla.com"],
+     "expires_in_version": "never",
+     "kind": "enumerated",
+     "bug_numbers": [1229961],
+     "n_values": 12,
+     "description": "Plugin drawing model. 0 when windowed, otherwise NPDrawingModel + 1."
+diff --git a/toolkit/components/telemetry/histogram-whitelists.json b/toolkit/components/telemetry/histogram-whitelists.json
+--- a/toolkit/components/telemetry/histogram-whitelists.json
++++ b/toolkit/components/telemetry/histogram-whitelists.json
+@@ -1699,14 +1699,11 @@
+     "UPDATE_SERVICE_MANUALLY_UNINSTALLED_NOTIFY",
+     "UPDATE_UNABLE_TO_APPLY_EXTERNAL",
+     "UPDATE_UNABLE_TO_APPLY_NOTIFY",
+     "VIDEO_FASTSEEK_USED",
+     "WEAVE_ENGINE_SYNC_ERRORS",
+     "WEBFONT_PER_PAGE",
+     "WEBRTC_CALL_COUNT_2",
+     "WEBVTT_USED_VTT_CUES",
+-    "WEB_NOTIFICATION_CLICKED",
+-    "WEB_NOTIFICATION_EXCEPTIONS_OPENED",
+-    "WEB_NOTIFICATION_SHOWN",
+     "XUL_CACHE_DISABLED"
+   ]
+ }

+ 103 - 0
rel-257/ian/patches/1429875-1-61a1.patch

@@ -0,0 +1,103 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1521588665 25200
+# Node ID 36f505b0e0da72cbcd109ec7eeb2fb449f6da927
+# Parent  2294c711e2cbca1c3c2eaae5c3e1199794694034
+Bug 1429875 - Add a "name" property to Library and Program objects that corresponds to the output basename. r=glandium
+
+MozReview-Commit-ID: J4gt1fGUzOa
+
+diff --git a/python/mozbuild/mozbuild/frontend/data.py b/python/mozbuild/mozbuild/frontend/data.py
+--- a/python/mozbuild/mozbuild/frontend/data.py
++++ b/python/mozbuild/mozbuild/frontend/data.py
+@@ -482,16 +482,19 @@ class BaseProgram(Linkable):
+         if self.installed:
+             return ObjDirPath(self._context, '!/' + mozpath.join(self.install_target, self.program))
+         else:
+             return ObjDirPath(self._context, '!' + self.program)
+ 
+     def __repr__(self):
+         return '<%s: %s/%s>' % (type(self).__name__, self.relobjdir, self.program)
+ 
++    @property
++    def name(self):
++        return self.program
+ 
+ class Program(BaseProgram):
+     """Context derived container object for PROGRAM"""
+     SUFFIX_VAR = 'BIN_SUFFIX'
+     KIND = 'target'
+ 
+ 
+ class HostProgram(HostMixin, BaseProgram):
+@@ -596,16 +599,20 @@ class BaseLibrary(Linkable):
+             )
+             self.import_name = self.lib_name
+ 
+         self.refs = []
+ 
+     def __repr__(self):
+         return '<%s: %s/%s>' % (type(self).__name__, self.relobjdir, self.lib_name)
+ 
++    @property
++    def name(self):
++        return self.lib_name
++
+ 
+ class Library(BaseLibrary):
+     """Context derived container object for a library"""
+     KIND = 'target'
+     __slots__ = (
+     )
+ 
+     def __init__(self, context, basename, real_name=None):
+diff --git a/python/mozbuild/mozbuild/test/frontend/test_emitter.py b/python/mozbuild/mozbuild/test/frontend/test_emitter.py
+--- a/python/mozbuild/mozbuild/test/frontend/test_emitter.py
++++ b/python/mozbuild/mozbuild/test/frontend/test_emitter.py
+@@ -649,16 +649,20 @@ class TestEmitterBasic(unittest.TestCase
+         self.assertIsInstance(objs[3], Program)
+         self.assertIsInstance(objs[4], SimpleProgram)
+         self.assertIsInstance(objs[5], SimpleProgram)
+ 
+         self.assertEqual(objs[3].program, 'test_program.prog')
+         self.assertEqual(objs[4].program, 'test_program1.prog')
+         self.assertEqual(objs[5].program, 'test_program2.prog')
+ 
++        self.assertEqual(objs[3].name, 'test_program.prog')
++        self.assertEqual(objs[4].name, 'test_program1.prog')
++        self.assertEqual(objs[5].name, 'test_program2.prog')
++
+         self.assertEqual(objs[4].objs,
+                          [mozpath.join(reader.config.topobjdir,
+                                        'test_program1.%s' %
+                                        reader.config.substs['OBJ_SUFFIX'])])
+         self.assertEqual(objs[5].objs,
+                          [mozpath.join(reader.config.topobjdir,
+                                        'test_program2.%s' %
+                                        reader.config.substs['OBJ_SUFFIX'])])
+@@ -1176,19 +1180,25 @@ class TestEmitterBasic(unittest.TestCase
+ 
+     def test_linkables_cxx_link(self):
+         """Test that linkables transitively set cxx_link properly."""
+         reader = self.reader('test-linkables-cxx-link')
+         got_results = 0
+         for obj in self.read_topsrcdir(reader):
+             if isinstance(obj, SharedLibrary):
+                 if obj.basename == 'cxx_shared':
++                    self.assertEquals(obj.name, '%scxx_shared%s' %
++                                      (reader.config.dll_prefix,
++                                       reader.config.dll_suffix))
+                     self.assertTrue(obj.cxx_link)
+                     got_results += 1
+                 elif obj.basename == 'just_c_shared':
++                    self.assertEquals(obj.name, '%sjust_c_shared%s' %
++                                      (reader.config.dll_prefix,
++                                       reader.config.dll_suffix))
+                     self.assertFalse(obj.cxx_link)
+                     got_results += 1
+         self.assertEqual(got_results, 2)
+ 
+     def test_generated_sources(self):
+         """Test that GENERATED_SOURCES works properly."""
+         reader = self.reader('generated-sources')
+         objs = self.read_topsrcdir(reader)

+ 54 - 0
rel-257/ian/patches/1429875-2-61a1.patch

@@ -0,0 +1,54 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1521588665 25200
+# Node ID 4cdc60a9f06ee184973d888f7013a4ab30fe4e99
+# Parent  d56542ab61fe486d03ca5b0faee11173351e631c
+Bug 1429875 - Do not take DIST_INSTALL into account when deciding to build static libraries. r=glandium
+
+Now that we're no longer shipping the SDK we no longer need real libraries for
+the libraries that were created by this rule.
+
+MozReview-Commit-ID: ALATVGBayHu
+
+diff --git a/config/rules.mk b/config/rules.mk
+--- a/config/rules.mk
++++ b/config/rules.mk
+@@ -95,38 +95,23 @@ endif # ENABLE_TESTS
+ # Library rules
+ #
+ # If FORCE_STATIC_LIB is set, build a static library.
+ # Otherwise, build a shared library.
+ #
+ 
+ ifndef LIBRARY
+ ifdef REAL_LIBRARY
+-# Don't build actual static library if a shared library is also built
+-ifdef FORCE_SHARED_LIB
+-# ... except when we really want one
+ ifdef NO_EXPAND_LIBS
+ LIBRARY			:= $(REAL_LIBRARY)
+ else
+ LIBRARY			:= $(REAL_LIBRARY).$(LIBS_DESC_SUFFIX)
+ endif
+-else
+-# Only build actual library if it is installed in DIST/lib
+-ifeq (,$(DIST_INSTALL)$(NO_EXPAND_LIBS))
+-LIBRARY			:= $(REAL_LIBRARY).$(LIBS_DESC_SUFFIX)
+-else
+-ifdef NO_EXPAND_LIBS
+-LIBRARY			:= $(REAL_LIBRARY)
+-else
+-LIBRARY			:= $(REAL_LIBRARY) $(REAL_LIBRARY).$(LIBS_DESC_SUFFIX)
+ endif
+ endif
+-endif
+-endif # REAL_LIBRARY
+-endif # LIBRARY
+ 
+ ifndef HOST_LIBRARY
+ ifdef HOST_LIBRARY_NAME
+ HOST_LIBRARY		:= $(LIB_PREFIX)$(HOST_LIBRARY_NAME).$(LIB_SUFFIX)
+ endif
+ endif
+ 
+ ifdef FORCE_SHARED_LIB

+ 287 - 0
rel-257/ian/patches/1429875-3-61a1.patch

@@ -0,0 +1,287 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1521588665 25200
+# Node ID decbe4a4cdc77b610f7b9bae8622dbfcd00f2694
+# Parent  a85771c6ff58c57782962c99a57b9a688306e209
+Bug 1429875 - Add a unit test for linkage variables in the make backend. r=glandium
+
+MozReview-Commit-ID: HREobMhWTwg
+
+diff --git a/python/mozbuild/mozbuild/test/backend/common.py b/python/mozbuild/mozbuild/test/backend/common.py
+--- a/python/mozbuild/mozbuild/test/backend/common.py
++++ b/python/mozbuild/mozbuild/test/backend/common.py
+@@ -200,16 +200,27 @@ CONFIGS = defaultdict(lambda: {
+     'program-paths': {
+         'defines': {},
+         'non_global_defines': [],
+         'substs': {
+             'COMPILE_ENVIRONMENT': '1',
+             'BIN_SUFFIX': '.prog',
+         },
+     },
++    'linkage': {
++        'defines': {},
++        'non_global_defines': [],
++        'substs': {
++            'COMPILE_ENVIRONMENT': '1',
++            'LIB_SUFFIX': 'a',
++            'BIN_SUFFIX': '.exe',
++            'DLL_SUFFIX': '.so',
++            'OBJ_SUFFIX': 'o',
++        },
++    },
+ })
+ 
+ 
+ class BackendTester(unittest.TestCase):
+     def setUp(self):
+         self._old_env = dict(os.environ)
+         os.environ.pop('MOZ_OBJDIR', None)
+ 
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/moz.build b/python/mozbuild/mozbuild/test/backend/data/linkage/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/moz.build
+@@ -0,0 +1,11 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++include('templates.mozbuild')
++
++DIRS += [
++     'real',
++     'shared',
++     'prog',
++     'static',
++]
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/prog/moz.build b/python/mozbuild/mozbuild/test/backend/data/linkage/prog/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/prog/moz.build
+@@ -0,0 +1,11 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++DIRS += ['qux']
++
++Program('MyProgram')
++
++USE_LIBS += [
++    'bar',
++    'baz',
++]
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/prog/qux/moz.build b/python/mozbuild/mozbuild/test/backend/data/linkage/prog/qux/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/prog/qux/moz.build
+@@ -0,0 +1,6 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++SOURCES += ['qux1.c']
++
++SharedLibrary('qux')
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/prog/qux/qux1.c b/python/mozbuild/mozbuild/test/backend/data/linkage/prog/qux/qux1.c
+new file mode 100644
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/real/foo/foo1.c b/python/mozbuild/mozbuild/test/backend/data/linkage/real/foo/foo1.c
+new file mode 100644
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/real/foo/foo2.c b/python/mozbuild/mozbuild/test/backend/data/linkage/real/foo/foo2.c
+new file mode 100644
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/real/foo/moz.build b/python/mozbuild/mozbuild/test/backend/data/linkage/real/foo/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/real/foo/moz.build
+@@ -0,0 +1,9 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++SOURCES += [
++    'foo1.c',
++    'foo2.c'
++]
++
++FINAL_LIBRARY = 'foo'
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/real/moz.build b/python/mozbuild/mozbuild/test/backend/data/linkage/real/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/real/moz.build
+@@ -0,0 +1,14 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++DIRS += [
++    'foo',
++]
++
++NO_EXPAND_LIBS = True
++
++OS_LIBS += ['-lbaz']
++
++USE_LIBS += ['static:baz']
++
++Library('foo')
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/shared/baz/baz1.c b/python/mozbuild/mozbuild/test/backend/data/linkage/shared/baz/baz1.c
+new file mode 100644
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/shared/baz/moz.build b/python/mozbuild/mozbuild/test/backend/data/linkage/shared/baz/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/shared/baz/moz.build
+@@ -0,0 +1,6 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++SOURCES += ['baz1.c']
++
++FINAL_LIBRARY = 'baz'
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/shared/moz.build b/python/mozbuild/mozbuild/test/backend/data/linkage/shared/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/shared/moz.build
+@@ -0,0 +1,14 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++DIRS += [
++    'baz',
++]
++
++STATIC_LIBRARY_NAME = 'baz_s'
++FORCE_STATIC_LIB = True
++
++OS_LIBS += ['-lfoo']
++USE_LIBS += ['qux']
++
++SharedLibrary('baz')
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/bar1.cc b/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/bar1.cc
+new file mode 100644
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/moz.build b/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/moz.build
+@@ -0,0 +1,8 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++SOURCES += [
++    'bar1.cc',
++]
++
++FINAL_LIBRARY = 'bar'
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/static/moz.build b/python/mozbuild/mozbuild/test/backend/data/linkage/static/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/static/moz.build
+@@ -0,0 +1,12 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++DIRS += [
++    'bar',
++]
++
++USE_LIBS += ['foo']
++
++OS_LIBS += ['-lbar']
++
++Library('bar')
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/templates.mozbuild b/python/mozbuild/mozbuild/test/backend/data/linkage/templates.mozbuild
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/templates.mozbuild
+@@ -0,0 +1,23 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++@template
++def Library(name):
++    LIBRARY_NAME = name
++
++@template
++def SharedLibrary(name):
++    FORCE_SHARED_LIB = True
++    LIBRARY_NAME = name
++
++@template
++def Binary():
++    # Add -lfoo for testing purposes.
++    OS_LIBS += ['foo']
++
++
++@template
++def Program(name):
++    PROGRAM = name
++
++    Binary()
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/test_recursivemake.py b/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
+--- a/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
++++ b/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
+@@ -982,16 +982,61 @@ class TestRecursiveMakeBackend(BackendTe
+ 
+         with open(os.path.join(env.topobjdir, 'cxx-library', 'backend.mk'), 'rb') as fh:
+             lines = fh.readlines()
+             lines = [line.rstrip() for line in lines]
+ 
+             for line in lines:
+                 self.assertNotIn('LIB_IS_C_ONLY', line)
+ 
++    def test_linkage(self):
++        env = self._consume('linkage', RecursiveMakeBackend)
++        expected_linkage = {
++            'prog': {
++                'SHARED_LIBS': ['$(DEPTH)/shared/baz', '$(DEPTH)/prog/qux/qux'],
++                'STATIC_LIBS': ['$(DEPTH)/static/bar%s' % env.lib_suffix],
++                'OS_LIBS': ['-lfoo', '-lbaz', '-lbar'],
++            },
++            'shared': {
++                'OS_LIBS': ['-lfoo'],
++                'SHARED_LIBS': ['$(DEPTH)/prog/qux/qux'],
++                'STATIC_LIBS': ['$(DEPTH)/shared/baz/shared_baz%s' %
++                                env.lib_suffix],
++            },
++            'static': {
++                'STATIC_LIBS': [
++                    '$(DEPTH)/static/bar/static_bar.a',
++                    '$(DEPTH)/real/foo.a',
++                ],
++                'OS_LIBS': ['-lbar'],
++                'SHARED_LIBS': [],
++            },
++            'real': {
++                'STATIC_LIBS': [
++                    '$(DEPTH)/shared/baz_s%s' % env.lib_suffix,
++                    '$(DEPTH)/real/foo/real_foo%s' % env.lib_suffix,
++                ],
++                'SHARED_LIBS': [],
++                'OS_LIBS': ['-lbaz'],
++            }
++        }
++        actual_linkage = {}
++        for name in expected_linkage.keys():
++            with open(os.path.join(env.topobjdir, name, 'backend.mk'), 'rb') as fh:
++                actual_linkage[name] = [line.rstrip() for line in fh.readlines()]
++        for name in expected_linkage:
++            for var in expected_linkage[name]:
++                for val in expected_linkage[name][var]:
++                    line = '%s += %s' % (var, val)
++                    self.assertIn(line,
++                                  actual_linkage[name])
++                    actual_linkage[name].remove(line)
++                for line in actual_linkage[name]:
++                    self.assertNotIn('%s +=' % var, line)
++
+     def test_jar_manifests(self):
+         env = self._consume('jar-manifests', RecursiveMakeBackend)
+ 
+         with open(os.path.join(env.topobjdir, 'backend.mk'), 'rb') as fh:
+             lines = fh.readlines()
+ 
+         lines = [line.rstrip() for line in lines]
+ 

+ 1776 - 0
rel-257/ian/patches/1429875-4-61a1.patch

@@ -0,0 +1,1776 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1521588665 25200
+# Node ID 7547d66e0f518d20f61b492eac027d5a34ac6fb4
+# Parent  69a2fcd14b36bab49849d2f63507b8ad7e0b0a7c
+Bug 1429875 - Remove expandlibs and instead generate list files in the mozbuild backend. r=glandium
+
+MozReview-Commit-ID: 5eLwnh1HHGj
+
+diff --git a/build/clang-plugin/Makefile.in b/build/clang-plugin/Makefile.in
+--- a/build/clang-plugin/Makefile.in
++++ b/build/clang-plugin/Makefile.in
+@@ -8,20 +8,16 @@ include $(topsrcdir)/config/config.mk
+ # variable to limit ourselves to what we need to build the clang plugin.
+ ifneq ($(HOST_OS_ARCH),WINNT)
+ DSO_LDOPTS := -shared
+ endif
+ 
+ ifeq ($(HOST_OS_ARCH)_$(OS_ARCH),Linux_Darwin)
+ # Use the host compiler instead of the target compiler.
+ CXX := $(HOST_CXX)
+-# expandlibs doesn't know the distinction between host and target toolchains,
+-# and on cross linux/darwin builds, the options to give to the linker for file
+-# lists differ between both, so don't use file lists.
+-EXPAND_MKSHLIB_ARGS :=
+ endif
+ 
+ # Use the default OS X deployment target to enable using the libc++ headers
+ # correctly.  Note that the binary produced here is a host tool and doesn't need
+ # to be distributed.
+ MACOSX_DEPLOYMENT_TARGET :=
+ 
+ # Temporarily relax the requirements for libstdc++ symbol versions on static
+diff --git a/config/config.mk b/config/config.mk
+--- a/config/config.mk
++++ b/config/config.mk
+@@ -411,28 +411,16 @@ JAVAC_FLAGS += -source 1.4
+ 
+ ifdef MOZ_DEBUG
+ JAVAC_FLAGS += -g
+ endif
+ 
+ # MDDEPDIR is the subdirectory where dependency files are stored
+ MDDEPDIR := .deps
+ 
+-EXPAND_LIBS_EXEC = $(PYTHON) $(MOZILLA_DIR)/config/expandlibs_exec.py
+-EXPAND_LIBS_GEN = $(PYTHON) $(MOZILLA_DIR)/config/expandlibs_gen.py
+-EXPAND_AR = $(EXPAND_LIBS_EXEC) --extract -- $(AR)
+-EXPAND_CC = $(EXPAND_LIBS_EXEC) --uselist -- $(CC)
+-EXPAND_CCC = $(EXPAND_LIBS_EXEC) --uselist -- $(CCC)
+-EXPAND_LINK = $(EXPAND_LIBS_EXEC) --uselist -- $(LINKER)
+-EXPAND_MKSHLIB_ARGS = --uselist
+-ifdef SYMBOL_ORDER
+-EXPAND_MKSHLIB_ARGS += --symbol-order $(SYMBOL_ORDER)
+-endif
+-EXPAND_MKSHLIB = $(EXPAND_LIBS_EXEC) $(EXPAND_MKSHLIB_ARGS) -- $(MKSHLIB)
+-
+ # autoconf.mk sets OBJ_SUFFIX to an error to avoid use before including
+ # this file
+ OBJ_SUFFIX := $(_OBJ_SUFFIX)
+ 
+ # PGO builds with GCC build objects with instrumentation in a first pass,
+ # then objects optimized, without instrumentation, in a second pass. If
+ # we overwrite the objects from the first pass with those from the second,
+ # we end up not getting instrumentation data for better optimization on
+diff --git a/config/expandlibs.py b/config/expandlibs.py
+deleted file mode 100644
+--- a/config/expandlibs.py
++++ /dev/null
+@@ -1,143 +0,0 @@
+-# This Source Code Form is subject to the terms of the Mozilla Public
+-# 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/.
+-
+-'''Expandlibs is a system that allows to replace some libraries with a
+-descriptor file containing some linking information about them.
+-
+-The descriptor file format is as follows:
+----8<-----
+-OBJS = a.o b.o ...
+-LIBS = libfoo.a libbar.a ...
+---->8-----
+-
+-(In the example above, OBJ_SUFFIX is o and LIB_SUFFIX is a).
+-
+-Expandlibs also canonicalizes how to pass libraries to the linker, such
+-that only the ${LIB_PREFIX}${ROOT}.${LIB_SUFFIX} form needs to be used:
+-given a list of files, expandlibs will replace items with the form
+-${LIB_PREFIX}${ROOT}.${LIB_SUFFIX} following these rules:
+-
+-- If a ${DLL_PREFIX}${ROOT}.${DLL_SUFFIX} or
+-  ${DLL_PREFIX}${ROOT}.${IMPORT_LIB_SUFFIX} file exists, use that instead
+-- If the ${LIB_PREFIX}${ROOT}.${LIB_SUFFIX} file exists, use it
+-- If a ${LIB_PREFIX}${ROOT}.${LIB_SUFFIX}.${LIB_DESC_SUFFIX} file exists,
+-  replace ${LIB_PREFIX}${ROOT}.${LIB_SUFFIX} with the OBJS and LIBS the
+-  descriptor contains. And for each of these LIBS, also apply the same
+-  rules.
+-'''
+-from __future__ import with_statement
+-import sys, os, errno
+-import expandlibs_config as conf
+-
+-def ensureParentDir(file):
+-    '''Ensures the directory parent to the given file exists'''
+-    dir = os.path.dirname(file)
+-    if dir and not os.path.exists(dir):
+-        try:
+-            os.makedirs(dir)
+-        except OSError, error:
+-            if error.errno != errno.EEXIST:
+-                raise
+-
+-def relativize(path):
+-    '''Returns a path relative to the current working directory, if it is
+-    shorter than the given path'''
+-    def splitpath(path):
+-        dir, file = os.path.split(path)
+-        if os.path.splitdrive(dir)[1] == os.sep:
+-            return [file]
+-        return splitpath(dir) + [file]
+-
+-    if not os.path.exists(path):
+-        return path
+-    curdir = splitpath(os.path.abspath(os.curdir))
+-    abspath = splitpath(os.path.abspath(path))
+-    while curdir and abspath and curdir[0] == abspath[0]:
+-        del curdir[0]
+-        del abspath[0]
+-    if not curdir and not abspath:
+-        return '.'
+-    relpath = os.path.join(*[os.pardir for i in curdir] + abspath)
+-    if len(path) > len(relpath):
+-        return relpath
+-    return path
+-
+-def isObject(path):
+-    '''Returns whether the given path points to an object file, that is,
+-    ends with OBJ_SUFFIX or .i_o'''
+-    return os.path.splitext(path)[1] in [conf.OBJ_SUFFIX, '.i_o']
+-
+-def isDynamicLib(path):
+-    '''Returns whether the given path points to a dynamic library, that is,
+-    ends with DLL_SUFFIX.'''
+-    # On mac, the xul library is named XUL, instead of libxul.dylib. Assume any
+-    # file by that name is a dynamic library.
+-    return os.path.splitext(path)[1] == conf.DLL_SUFFIX or os.path.basename(path) == 'XUL'
+-
+-class LibDescriptor(dict):
+-    KEYS = ['OBJS', 'LIBS']
+-
+-    def __init__(self, content=None):
+-        '''Creates an instance of a lib descriptor, initialized with contents
+-        from a list of strings when given. This is intended for use with
+-        file.readlines()'''
+-        if isinstance(content, list) and all([isinstance(item, str) for item in content]):
+-            pass
+-        elif content is not None:
+-            raise TypeError("LibDescriptor() arg 1 must be None or a list of strings")
+-        super(LibDescriptor, self).__init__()
+-        for key in self.KEYS:
+-            self[key] = []
+-        if not content:
+-            return
+-        for key, value in [(s.strip() for s in item.split('=', 2)) for item in content if item.find('=') >= 0]:
+-            if key in self.KEYS:
+-                self[key] = value.split()
+-
+-    def __str__(self):
+-        '''Serializes the lib descriptor'''
+-        return '\n'.join('%s = %s' % (k, ' '.join(self[k])) for k in self.KEYS if len(self[k]))
+-
+-class ExpandArgs(list):
+-    def __init__(self, args):
+-        '''Creates a clone of the |args| list and performs file expansion on
+-        each item it contains'''
+-        super(ExpandArgs, self).__init__()
+-        self._descs = set()
+-        for arg in args:
+-            self += self._expand(arg)
+-
+-    def _expand(self, arg):
+-        '''Internal function doing the actual work'''
+-        (root, ext) = os.path.splitext(arg)
+-        if ext != conf.LIB_SUFFIX or not os.path.basename(root).startswith(conf.LIB_PREFIX):
+-            return [relativize(arg)]
+-        if conf.LIB_PREFIX:
+-            dll = root.replace(conf.LIB_PREFIX, conf.DLL_PREFIX, 1) + conf.DLL_SUFFIX
+-        else:
+-            dll = root + conf.DLL_SUFFIX
+-        if os.path.exists(dll):
+-            if conf.IMPORT_LIB_SUFFIX:
+-                return [relativize(root + conf.IMPORT_LIB_SUFFIX)]
+-            else:
+-                return [relativize(dll)]
+-        return self._expand_desc(arg)
+-
+-    def _expand_desc(self, arg):
+-        '''Internal function taking care of lib descriptor expansion only'''
+-        desc = os.path.abspath(arg + conf.LIBS_DESC_SUFFIX)
+-        if os.path.exists(desc):
+-            if desc in self._descs:
+-                return []
+-            self._descs.add(desc)
+-            with open(desc, 'r') as f:
+-                desc = LibDescriptor(f.readlines())
+-            objs = [relativize(o) for o in desc['OBJS']]
+-            for lib in desc['LIBS']:
+-                objs += self._expand(lib)
+-            return objs
+-        return [relativize(arg)]
+-
+-if __name__ == '__main__':
+-    print " ".join(ExpandArgs(sys.argv[1:]))
+diff --git a/config/expandlibs_config.py b/config/expandlibs_config.py
+deleted file mode 100644
+--- a/config/expandlibs_config.py
++++ /dev/null
+@@ -1,29 +0,0 @@
+-# This Source Code Form is subject to the terms of the Mozilla Public
+-# 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/.
+-
+-from buildconfig import substs
+-
+-def normalize_suffix(suffix):
+-    '''Returns a normalized suffix, i.e. ensures it starts with a dot and
+-    doesn't starts or ends with whitespace characters'''
+-    value = suffix.strip()
+-    if len(value) and not value.startswith('.'):
+-        value = '.' + value
+-    return value
+-
+-# Variables from the build system
+-AR = substs['AR']
+-AR_EXTRACT = substs['AR_EXTRACT'].replace('$(AR)', AR)
+-DLL_PREFIX = substs['DLL_PREFIX']
+-LIB_PREFIX = substs['LIB_PREFIX']
+-RUST_LIB_PREFIX = substs['RUST_LIB_PREFIX']
+-OBJ_SUFFIX = normalize_suffix(substs['OBJ_SUFFIX'])
+-LIB_SUFFIX = normalize_suffix(substs['LIB_SUFFIX'])
+-RUST_LIB_SUFFIX = normalize_suffix(substs['RUST_LIB_SUFFIX'])
+-DLL_SUFFIX = normalize_suffix(substs['DLL_SUFFIX'])
+-IMPORT_LIB_SUFFIX = normalize_suffix(substs['IMPORT_LIB_SUFFIX'])
+-LIBS_DESC_SUFFIX = normalize_suffix(substs['LIBS_DESC_SUFFIX'])
+-EXPAND_LIBS_LIST_STYLE = substs['EXPAND_LIBS_LIST_STYLE']
+-EXPAND_LIBS_ORDER_STYLE = substs['EXPAND_LIBS_ORDER_STYLE']
+-LD_PRINT_ICF_SECTIONS = substs['LD_PRINT_ICF_SECTIONS']
+diff --git a/config/expandlibs_exec.py b/config/expandlibs_exec.py
+deleted file mode 100644
+--- a/config/expandlibs_exec.py
++++ /dev/null
+@@ -1,354 +0,0 @@
+-# This Source Code Form is subject to the terms of the Mozilla Public
+-# 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/.
+-
+-'''expandlibs-exec.py applies expandlibs rules, and some more (see below) to
+-a given command line, and executes that command line with the expanded
+-arguments.
+-
+-With the --extract argument (useful for e.g. $(AR)), it extracts object files
+-from static libraries (or use those listed in library descriptors directly).
+-
+-With the --uselist argument (useful for e.g. $(CC)), it replaces all object
+-files with a list file. This can be used to avoid limitations in the length
+-of a command line. The kind of list file format used depends on the
+-EXPAND_LIBS_LIST_STYLE variable: 'list' for MSVC style lists (@file.list)
+-or 'linkerscript' for GNU ld linker scripts.
+-See https://bugzilla.mozilla.org/show_bug.cgi?id=584474#c59 for more details.
+-
+-With the --symbol-order argument, followed by a file name, it will add the
+-relevant linker options to change the order in which the linker puts the
+-symbols appear in the resulting binary. Only works for ELF targets.
+-'''
+-from __future__ import with_statement
+-import sys
+-import os
+-from expandlibs import (
+-    ExpandArgs,
+-    relativize,
+-    isDynamicLib,
+-    isObject,
+-)
+-import expandlibs_config as conf
+-from optparse import OptionParser
+-import subprocess
+-import tempfile
+-import shutil
+-import subprocess
+-import re
+-from mozbuild.makeutil import Makefile
+-
+-# The are the insert points for a GNU ld linker script, assuming a more
+-# or less "standard" default linker script. This is not a dict because
+-# order is important.
+-SECTION_INSERT_BEFORE = [
+-  ('.text', '.fini'),
+-  ('.rodata', '.rodata1'),
+-  ('.data.rel.ro', '.dynamic'),
+-  ('.data', '.data1'),
+-]
+-
+-class ExpandArgsMore(ExpandArgs):
+-    ''' Meant to be used as 'with ExpandArgsMore(args) as ...: '''
+-    def __enter__(self):
+-        self.tmp = []
+-        return self
+-        
+-    def __exit__(self, type, value, tb):
+-        '''Automatically remove temporary files'''
+-        for tmp in self.tmp:
+-            if os.path.isdir(tmp):
+-                shutil.rmtree(tmp, True)
+-            else:
+-                os.remove(tmp)
+-
+-    def extract(self):
+-        self[0:] = self._extract(self)
+-
+-    def _extract(self, args):
+-        '''When a static library name is found, either extract its contents
+-        in a temporary directory or use the information found in the
+-        corresponding lib descriptor.
+-        '''
+-        ar_extract = conf.AR_EXTRACT.split()
+-        newlist = []
+-
+-        def lookup(base, f):
+-            for root, dirs, files in os.walk(base):
+-                if f in files:
+-                    return os.path.join(root, f)
+-
+-        for arg in args:
+-            if os.path.splitext(arg)[1] == conf.LIB_SUFFIX:
+-                if os.path.exists(arg + conf.LIBS_DESC_SUFFIX):
+-                    newlist += self._extract(self._expand_desc(arg))
+-                    continue
+-                elif os.path.exists(arg) and (len(ar_extract) or conf.AR == 'lib'):
+-                    tmp = tempfile.mkdtemp(dir=os.curdir)
+-                    self.tmp.append(tmp)
+-                    if conf.AR == 'lib':
+-                        out = subprocess.check_output([conf.AR, '-NOLOGO', '-LIST', arg])
+-                        files = out.splitlines()
+-                        # If lib -list returns a list full of dlls, it's an
+-                        # import lib.
+-                        if all(isDynamicLib(f) for f in files):
+-                            newlist += [arg]
+-                            continue
+-                        for f in files:
+-                            subprocess.call([conf.AR, '-NOLOGO', '-EXTRACT:%s' % f, os.path.abspath(arg)], cwd=tmp)
+-                    else:
+-                        subprocess.call(ar_extract + [os.path.abspath(arg)], cwd=tmp)
+-                    objs = []
+-                    basedir = os.path.dirname(arg)
+-                    for root, dirs, files in os.walk(tmp):
+-                        for f in files:
+-                            if isObject(f):
+-                                # If the file extracted from the library also
+-                                # exists in the directory containing the
+-                                # library, or one of its subdirectories, use
+-                                # that instead.
+-                                maybe_obj = lookup(os.path.join(basedir, os.path.relpath(root, tmp)), f)
+-                                if maybe_obj:
+-                                    objs.append(relativize(maybe_obj))
+-                                else:
+-                                    objs.append(relativize(os.path.join(root, f)))
+-                    newlist += sorted(objs)
+-                    continue
+-            newlist += [arg]
+-        return newlist
+-
+-    def makelist(self):
+-        '''Replaces object file names with a temporary list file, using a
+-        list format depending on the EXPAND_LIBS_LIST_STYLE variable
+-        '''
+-        objs = [o for o in self if isObject(o)]
+-        if not len(objs): return
+-        fd, tmp = tempfile.mkstemp(suffix=".list",dir=os.curdir)
+-        if conf.EXPAND_LIBS_LIST_STYLE == "linkerscript":
+-            content = ['INPUT("%s")\n' % obj for obj in objs]
+-            ref = tmp
+-        elif conf.EXPAND_LIBS_LIST_STYLE == "filelist":
+-            content = ["%s\n" % obj for obj in objs]
+-            ref = "-Wl,-filelist," + tmp
+-        elif conf.EXPAND_LIBS_LIST_STYLE == "list":
+-            content = ["%s\n" % obj for obj in objs]
+-            ref = "@" + tmp
+-        else:
+-            os.close(fd)
+-            os.remove(tmp)
+-            return
+-        self.tmp.append(tmp)
+-        f = os.fdopen(fd, "w")
+-        f.writelines(content)
+-        f.close()
+-        idx = self.index(objs[0])
+-        newlist = self[0:idx] + [ref] + [os.path.normpath(item) for item in self[idx:] if item not in objs]
+-        self[0:] = newlist
+-
+-    def _getFoldedSections(self):
+-        '''Returns a dict about folded sections.
+-        When section A and B are folded into section C, the dict contains:
+-        { 'A': 'C',
+-          'B': 'C',
+-          'C': ['A', 'B'] }'''
+-        if not conf.LD_PRINT_ICF_SECTIONS:
+-            return {}
+-
+-        proc = subprocess.Popen(self + [conf.LD_PRINT_ICF_SECTIONS], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
+-        (stdout, stderr) = proc.communicate()
+-        result = {}
+-        # gold's --print-icf-sections output looks like the following:
+-        # ld: ICF folding section '.section' in file 'file.o'into '.section' in file 'file.o'
+-        # In terms of words, chances are this will change in the future,
+-        # especially considering "into" is misplaced. Splitting on quotes
+-        # seems safer.
+-        for l in stderr.split('\n'):
+-            quoted = l.split("'")
+-            if len(quoted) > 5 and quoted[1] != quoted[5]:
+-                result[quoted[1]] = [quoted[5]]
+-                if quoted[5] in result:
+-                    result[quoted[5]].append(quoted[1])
+-                else:
+-                    result[quoted[5]] = [quoted[1]]
+-        return result
+-
+-    def _getOrderedSections(self, ordered_symbols):
+-        '''Given an ordered list of symbols, returns the corresponding list
+-        of sections following the order.'''
+-        if not conf.EXPAND_LIBS_ORDER_STYLE in ['linkerscript', 'section-ordering-file']:
+-            raise Exception('EXPAND_LIBS_ORDER_STYLE "%s" is not supported' % conf.EXPAND_LIBS_ORDER_STYLE)
+-        finder = SectionFinder([arg for arg in self if isObject(arg) or os.path.splitext(arg)[1] == conf.LIB_SUFFIX])
+-        folded = self._getFoldedSections()
+-        sections = set()
+-        ordered_sections = []
+-        for symbol in ordered_symbols:
+-            symbol_sections = finder.getSections(symbol)
+-            all_symbol_sections = []
+-            for section in symbol_sections:
+-                if section in folded:
+-                    if isinstance(folded[section], str):
+-                        section = folded[section]
+-                    all_symbol_sections.append(section)
+-                    all_symbol_sections.extend(folded[section])
+-                else:
+-                    all_symbol_sections.append(section)
+-            for section in all_symbol_sections:
+-                if not section in sections:
+-                    ordered_sections.append(section)
+-                    sections.add(section)
+-        return ordered_sections
+-
+-    def orderSymbols(self, order):
+-        '''Given a file containing a list of symbols, adds the appropriate
+-        argument to make the linker put the symbols in that order.'''
+-        with open(order) as file:
+-            sections = self._getOrderedSections([l.strip() for l in file.readlines() if l.strip()])
+-        split_sections = {}
+-        linked_sections = [s[0] for s in SECTION_INSERT_BEFORE]
+-        for s in sections:
+-            for linked_section in linked_sections:
+-                if s.startswith(linked_section):
+-                    if linked_section in split_sections:
+-                        split_sections[linked_section].append(s)
+-                    else:
+-                        split_sections[linked_section] = [s]
+-                    break
+-        content = []
+-        # Order is important
+-        linked_sections = [s for s in linked_sections if s in split_sections]
+-
+-        if conf.EXPAND_LIBS_ORDER_STYLE == 'section-ordering-file':
+-            option = '-Wl,--section-ordering-file,%s'
+-            content = sections
+-            for linked_section in linked_sections:
+-                content.extend(split_sections[linked_section])
+-                content.append('%s.*' % linked_section)
+-                content.append(linked_section)
+-
+-        elif conf.EXPAND_LIBS_ORDER_STYLE == 'linkerscript':
+-            option = '-Wl,-T,%s'
+-            section_insert_before = dict(SECTION_INSERT_BEFORE)
+-            for linked_section in linked_sections:
+-                content.append('SECTIONS {')
+-                content.append('  %s : {' % linked_section)
+-                content.extend('    *(%s)' % s for s in split_sections[linked_section])
+-                content.append('  }')
+-                content.append('}')
+-                content.append('INSERT BEFORE %s' % section_insert_before[linked_section])
+-        else:
+-            raise Exception('EXPAND_LIBS_ORDER_STYLE "%s" is not supported' % conf.EXPAND_LIBS_ORDER_STYLE)
+-
+-        fd, tmp = tempfile.mkstemp(dir=os.curdir)
+-        f = os.fdopen(fd, "w")
+-        f.write('\n'.join(content)+'\n')
+-        f.close()
+-        self.tmp.append(tmp)
+-        self.append(option % tmp)
+-
+-class SectionFinder(object):
+-    '''Instances of this class allow to map symbol names to sections in
+-    object files.'''
+-
+-    def __init__(self, objs):
+-        '''Creates an instance, given a list of object files.'''
+-        if not conf.EXPAND_LIBS_ORDER_STYLE in ['linkerscript', 'section-ordering-file']:
+-            raise Exception('EXPAND_LIBS_ORDER_STYLE "%s" is not supported' % conf.EXPAND_LIBS_ORDER_STYLE)
+-        self.mapping = {}
+-        for obj in objs:
+-            if not isObject(obj) and os.path.splitext(obj)[1] != conf.LIB_SUFFIX:
+-                raise Exception('%s is not an object nor a static library' % obj)
+-            for symbol, section in SectionFinder._getSymbols(obj):
+-                sym = SectionFinder._normalize(symbol)
+-                if sym in self.mapping:
+-                    if not section in self.mapping[sym]:
+-                        self.mapping[sym].append(section)
+-                else:
+-                    self.mapping[sym] = [section]
+-
+-    def getSections(self, symbol):
+-        '''Given a symbol, returns a list of sections containing it or the
+-        corresponding thunks. When the given symbol is a thunk, returns the
+-        list of sections containing its corresponding normal symbol and the
+-        other thunks for that symbol.'''
+-        sym = SectionFinder._normalize(symbol)
+-        if sym in self.mapping:
+-            return self.mapping[sym]
+-        return []
+-
+-    @staticmethod
+-    def _normalize(symbol):
+-        '''For normal symbols, return the given symbol. For thunks, return
+-        the corresponding normal symbol.'''
+-        if re.match('^_ZThn[0-9]+_', symbol):
+-            return re.sub('^_ZThn[0-9]+_', '_Z', symbol)
+-        return symbol
+-
+-    @staticmethod
+-    def _getSymbols(obj):
+-        '''Returns a list of (symbol, section) contained in the given object
+-        file.'''
+-        proc = subprocess.Popen(['objdump', '-t', obj], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
+-        (stdout, stderr) = proc.communicate()
+-        syms = []
+-        for line in stdout.splitlines():
+-            # Each line has the following format:
+-            # <addr> [lgu!][w ][C ][W ][Ii ][dD ][FfO ] <section>\t<length> <symbol>
+-            tmp = line.split(' ',1)
+-            # This gives us ["<addr>", "[lgu!][w ][C ][W ][Ii ][dD ][FfO ] <section>\t<length> <symbol>"]
+-            # We only need to consider cases where "<section>\t<length> <symbol>" is present,
+-            # and where the [FfO] flag is either F (function) or O (object).
+-            if len(tmp) > 1 and len(tmp[1]) > 6 and tmp[1][6] in ['O', 'F']:
+-                tmp = tmp[1][8:].split()
+-                # That gives us ["<section>","<length>", "<symbol>"]
+-                syms.append((tmp[-1], tmp[0]))
+-        return syms
+-
+-def print_command(out, args):
+-    print >>out, "Executing: " + " ".join(args)
+-    for tmp in [f for f in args.tmp if os.path.isfile(f)]:
+-        print >>out, tmp + ":"
+-        with open(tmp) as file:
+-            print >>out, "".join(["    " + l for l in file.readlines()])
+-    out.flush()
+-
+-def main(args, proc_callback=None):
+-    parser = OptionParser()
+-    parser.add_option("--extract", action="store_true", dest="extract",
+-        help="when a library has no descriptor file, extract it first, when possible")
+-    parser.add_option("--uselist", action="store_true", dest="uselist",
+-        help="use a list file for objects when executing a command")
+-    parser.add_option("--verbose", action="store_true", dest="verbose",
+-        help="display executed command and temporary files content")
+-    parser.add_option("--symbol-order", dest="symbol_order", metavar="FILE",
+-        help="use the given list of symbols to order symbols in the resulting binary when using with a linker")
+-
+-    (options, args) = parser.parse_args(args)
+-
+-    with ExpandArgsMore(args) as args:
+-        if options.extract:
+-            args.extract()
+-        if options.symbol_order:
+-            args.orderSymbols(options.symbol_order)
+-        if options.uselist:
+-            args.makelist()
+-
+-        if options.verbose:
+-            print_command(sys.stderr, args)
+-        try:
+-            proc = subprocess.Popen(args, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
+-            if proc_callback:
+-                proc_callback(proc)
+-        except Exception, e:
+-            print >>sys.stderr, 'error: Launching', args, ':', e
+-            raise e
+-        (stdout, stderr) = proc.communicate()
+-        if proc.returncode and not options.verbose:
+-            print_command(sys.stderr, args)
+-        sys.stderr.write(stdout)
+-        sys.stderr.flush()
+-        if proc.returncode:
+-            return proc.returncode
+-        return 0
+-
+-if __name__ == '__main__':
+-    exit(main(sys.argv[1:]))
+diff --git a/config/expandlibs_gen.py b/config/expandlibs_gen.py
+deleted file mode 100644
+--- a/config/expandlibs_gen.py
++++ /dev/null
+@@ -1,41 +0,0 @@
+-# This Source Code Form is subject to the terms of the Mozilla Public
+-# 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/.
+-
+-'''Given a list of object files and library names, prints a library
+-descriptor to standard output'''
+-
+-from __future__ import with_statement
+-import sys
+-import os
+-import expandlibs_config as conf
+-from expandlibs import LibDescriptor, isObject, ensureParentDir
+-from optparse import OptionParser
+-
+-def generate(args):
+-    desc = LibDescriptor()
+-    for arg in args:
+-        if isObject(arg):
+-            if os.path.exists(arg):
+-                desc['OBJS'].append(os.path.abspath(arg))
+-            else:
+-                raise Exception("File not found: %s" % arg)
+-        elif os.path.splitext(arg)[1] == conf.LIB_SUFFIX:
+-            if os.path.exists(arg) or os.path.exists(arg + conf.LIBS_DESC_SUFFIX):
+-                desc['LIBS'].append(os.path.abspath(arg))
+-            else:
+-                raise Exception("File not found: %s" % arg)
+-    return desc
+-
+-if __name__ == '__main__':
+-    parser = OptionParser()
+-    parser.add_option("-o", dest="output", metavar="FILE",
+-        help="send output to the given file")
+-
+-    (options, args) = parser.parse_args()
+-    if not options.output:
+-        raise Exception("Missing option: -o")
+-
+-    ensureParentDir(options.output)
+-    with open(options.output, 'w') as outfile:
+-        print >>outfile, generate(args)
+diff --git a/config/rules.mk b/config/rules.mk
+--- a/config/rules.mk
++++ b/config/rules.mk
+@@ -96,19 +96,18 @@ endif # ENABLE_TESTS
+ #
+ # If FORCE_STATIC_LIB is set, build a static library.
+ # Otherwise, build a shared library.
+ #
+ 
+ ifndef LIBRARY
+ ifdef REAL_LIBRARY
+ ifdef NO_EXPAND_LIBS
++# Only build actual library if it is requested.
+ LIBRARY			:= $(REAL_LIBRARY)
+-else
+-LIBRARY			:= $(REAL_LIBRARY).$(LIBS_DESC_SUFFIX)
+ endif
+ endif
+ endif
+ 
+ ifndef HOST_LIBRARY
+ ifdef HOST_LIBRARY_NAME
+ HOST_LIBRARY		:= $(LIB_PREFIX)$(HOST_LIBRARY_NAME).$(LIB_SUFFIX)
+ endif
+@@ -434,32 +433,35 @@ ECHO := true
+ QUIET := -q
+ endif
+ 
+ # Do everything from scratch
+ everything::
+ 	$(MAKE) clean
+ 	$(MAKE) all
+ 
+-STATIC_LIB_DEP = $(if $(wildcard $(1).$(LIBS_DESC_SUFFIX)),$(1).$(LIBS_DESC_SUFFIX),$(1))
+-STATIC_LIBS_DEPS := $(foreach l,$(STATIC_LIBS),$(call STATIC_LIB_DEP,$(l)))
+-
+ # Dependencies which, if modified, should cause everything to rebuild
+ GLOBAL_DEPS += Makefile $(addprefix $(DEPTH)/config/,$(INCLUDED_AUTOCONF_MK)) $(MOZILLA_DIR)/config/config.mk
+ 
+ ##############################################
+ ifdef COMPILE_ENVIRONMENT
+ OBJ_TARGETS = $(OBJS) $(PROGOBJS) $(HOST_OBJS) $(HOST_PROGOBJS)
+ 
+ compile:: host target
+ 
+ host:: $(HOST_LIBRARY) $(HOST_PROGRAM) $(HOST_SIMPLE_PROGRAMS) $(HOST_RUST_PROGRAMS) $(HOST_RUST_LIBRARY_FILE)
+ 
+ target:: $(LIBRARY) $(SHARED_LIBRARY) $(PROGRAM) $(SIMPLE_PROGRAMS) $(RUST_LIBRARY_FILE) $(RUST_PROGRAMS)
+ 
++ifndef LIBRARY
++ifdef OBJS
++target:: $(OBJS)
++endif
++endif
++
+ syms::
+ 
+ include $(MOZILLA_DIR)/config/makefiles/target_binaries.mk
+ endif
+ 
+ ##############################################
+ ifneq (1,$(NO_PROFILE_GUIDED_OPTIMIZE))
+ ifdef MOZ_PROFILE_USE
+@@ -533,36 +535,35 @@ distclean::
+ 	$(wildcard *.$(LIB_SUFFIX)) $(wildcard *$(DLL_SUFFIX)) \
+ 	$(wildcard *.$(IMPORT_LIB_SUFFIX))
+ 
+ alltags:
+ 	$(RM) TAGS
+ 	find $(topsrcdir) -name dist -prune -o \( -name '*.[hc]' -o -name '*.cp' -o -name '*.cpp' -o -name '*.idl' \) -print | $(TAG_PROGRAM)
+ 
+ define EXPAND_CC_OR_CXX
+-$(if $(PROG_IS_C_ONLY_$(1)),$(EXPAND_CC),$(EXPAND_CCC))
++$(if $(PROG_IS_C_ONLY_$(1)),$(CC),$(CCC))
+ endef
+ 
+ # Workaround a bug of MSVC 2017 Update 8 (see bug 1485224)
+ ifeq ($(CC_TYPE)_$(HOST_OS_ARCH)_$(MOZ_PROFILE_GENERATE),msvc_WINNT_1)
+ LINKER_OUT=$(subst /,\,$1)
+ else
+ LINKER_OUT=$1
+ endif
+ 
+ #
+ # PROGRAM = Foo
+ # creates OBJS, links with LIBS to create Foo
+ #
+-$(PROGRAM): $(PROGOBJS) $(STATIC_LIBS_DEPS) $(EXTRA_DEPS) $(RESFILE) $(GLOBAL_DEPS) $(call mkdir_deps,$(FINAL_TARGET))
++$(PROGRAM): $(PROGOBJS) $(STATIC_LIBS) $(EXTRA_DEPS) $(RESFILE) $(GLOBAL_DEPS) $(call mkdir_deps,$(FINAL_TARGET))
+ 	$(REPORT_BUILD)
+ 	@$(RM) $@.manifest
+ ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+-	$(EXPAND_LINK) -NOLOGO -OUT:$(call LINKER_OUT,$@) -PDB:$(LINK_PDBFILE) -IMPLIB:$(basename $(@F)).lib $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
+-
++	$(LINKER) -NOLOGO -OUT:$(call LINKER_OUT,$@) -PDB:$(LINK_PDBFILE) -IMPLIB:$(basename $(@F)).lib $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $($(notdir $@)_OBJS) $(RESFILE) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
+ ifdef MSMANIFEST_TOOL
+ 	@if test -f $@.manifest; then \
+ 		if test -f '$(srcdir)/$(notdir $@).manifest'; then \
+ 			echo 'Embedding manifest from $(srcdir)/$(notdir $@).manifest and $@.manifest'; \
+ 			$(MT) -NOLOGO -MANIFEST '$(win_srcdir)/$(notdir $@).manifest' $@.manifest -OUTPUTRESOURCE:$@\;1; \
+ 		else \
+ 			echo 'Embedding manifest from $@.manifest'; \
+ 			$(MT) -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
+@@ -573,140 +574,133 @@ ifdef MSMANIFEST_TOOL
+ 	fi
+ endif	# MSVC with manifest tool
+ ifdef MOZ_PROFILE_GENERATE
+ # touch it a few seconds into the future to work around FAT's
+ # 2-second granularity
+ 	touch -t `date +%Y%m%d%H%M.%S -d 'now+5seconds'` pgo.relink
+ endif
+ else # !WINNT || GNU_CC
+-	$(call EXPAND_CC_OR_CXX,$@) -o $@ $(COMPUTED_CXX_LDFLAGS) $(PGO_CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(STATIC_LIBS) $(MOZ_PROGRAM_LDFLAGS) $(SHARED_LIBS) $(OS_LIBS)
++	$(call EXPAND_CC_OR_CXX,$@) -o $@ $(COMPUTED_CXX_LDFLAGS) $(PGO_CFLAGS) $($(notdir $@)_OBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(STATIC_LIBS) $(MOZ_PROGRAM_LDFLAGS) $(SHARED_LIBS) $(OS_LIBS)
+ 	$(call py_action,check_binary,--target $@)
+ endif # WINNT && !GNU_CC
+ 
+ ifdef ENABLE_STRIP
+ 	$(STRIP) $(STRIP_FLAGS) $@
+ endif
+ ifdef MOZ_POST_PROGRAM_COMMAND
+ 	$(MOZ_POST_PROGRAM_COMMAND) $@
+ endif
+ 
+ $(HOST_PROGRAM): $(HOST_PROGOBJS) $(HOST_LIBS) $(HOST_EXTRA_DEPS) $(GLOBAL_DEPS)
+ 	$(REPORT_BUILD)
+ ifeq (_WINNT,$(GNU_CC)_$(HOST_OS_ARCH))
+-	$(EXPAND_LIBS_EXEC) -- $(LINKER) -NOLOGO -OUT:$@ -PDB:$(HOST_PDBFILE) $(HOST_OBJS) $(WIN32_EXE_LDFLAGS) $(HOST_LDFLAGS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
++	$(LINKER) -NOLOGO -OUT:$@ -PDB:$(HOST_PDBFILE) $(HOST_OBJS) $(WIN32_EXE_LDFLAGS) $(HOST_LDFLAGS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+ ifdef MSMANIFEST_TOOL
+ 	@if test -f $@.manifest; then \
+ 		if test -f '$(srcdir)/$@.manifest'; then \
+ 			echo 'Embedding manifest from $(srcdir)/$@.manifest and $@.manifest'; \
+ 			$(MT) -NOLOGO -MANIFEST '$(win_srcdir)/$@.manifest' $@.manifest -OUTPUTRESOURCE:$@\;1; \
+ 		else \
+ 			echo 'Embedding manifest from $@.manifest'; \
+ 			$(MT) -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
+ 		fi; \
+ 	elif test -f '$(srcdir)/$@.manifest'; then \
+ 		echo 'Embedding manifest from $(srcdir)/$@.manifest'; \
+ 		$(MT) -NOLOGO -MANIFEST '$(win_srcdir)/$@.manifest' -OUTPUTRESOURCE:$@\;1; \
+ 	fi
+ endif	# MSVC with manifest tool
+ else
+ ifeq ($(HOST_CPP_PROG_LINK),1)
+-	$(EXPAND_LIBS_EXEC) -- $(HOST_CXX) -o $@ $(HOST_CXX_LDFLAGS) $(HOST_LDFLAGS) $(HOST_PROGOBJS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
++	$(HOST_CXX) -o $@ $(HOST_CXX_LDFLAGS) $(HOST_LDFLAGS) $(HOST_PROGOBJS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+ else
+-	$(EXPAND_LIBS_EXEC) -- $(HOST_CC) -o $@ $(HOST_C_LDFLAGS) $(HOST_LDFLAGS) $(HOST_PROGOBJS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
++	$(HOST_CC) -o $@ $(HOST_C_LDFLAGS) $(HOST_LDFLAGS) $(HOST_PROGOBJS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+ endif # HOST_CPP_PROG_LINK
+ endif
+ ifndef CROSS_COMPILE
+ 	$(call py_action,check_binary,--host $@)
+ endif
+ 
+ #
+ # This is an attempt to support generation of multiple binaries
+ # in one directory, it assumes everything to compile Foo is in
+ # Foo.o (from either Foo.c or Foo.cpp).
+ #
+ # SIMPLE_PROGRAMS = Foo Bar
+ # creates Foo.o Bar.o, links with LIBS to create Foo, Bar.
+ #
+-$(SIMPLE_PROGRAMS): %$(BIN_SUFFIX): %.$(OBJ_SUFFIX) $(STATIC_LIBS_DEPS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
++$(SIMPLE_PROGRAMS): %$(BIN_SUFFIX): %.$(OBJ_SUFFIX) $(STATIC_LIBS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+ 	$(REPORT_BUILD)
+ ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+-	$(EXPAND_LINK) -nologo -out:$@ -pdb:$(LINK_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
++	$(LINKER) -nologo -out:$@ -pdb:$(LINK_PDBFILE) $($@_OBJS) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
+ ifdef MSMANIFEST_TOOL
+ 	@if test -f $@.manifest; then \
+ 		$(MT) -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
+ 		rm -f $@.manifest; \
+ 	fi
+ endif	# MSVC with manifest tool
+ else
+-	$(call EXPAND_CC_OR_CXX,$@) $(COMPUTED_CXX_LDFLAGS) $(PGO_CFLAGS) -o $@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(STATIC_LIBS) $(MOZ_PROGRAM_LDFLAGS) $(SHARED_LIBS) $(OS_LIBS)
++	$(call EXPAND_CC_OR_CXX,$@) $(COMPUTED_CXX_LDFLAGS) $(PGO_CFLAGS) -o $@ $($@_OBJS) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(STATIC_LIBS) $(MOZ_PROGRAM_LDFLAGS) $(SHARED_LIBS) $(OS_LIBS)
+ 	$(call py_action,check_binary,--target $@)
+ endif # WINNT && !GNU_CC
+ 
+ ifdef ENABLE_STRIP
+ 	$(STRIP) $(STRIP_FLAGS) $@
+ endif
+ ifdef MOZ_POST_PROGRAM_COMMAND
+ 	$(MOZ_POST_PROGRAM_COMMAND) $@
+ endif
+ 
+ $(HOST_SIMPLE_PROGRAMS): host_%$(HOST_BIN_SUFFIX): host_%.$(OBJ_SUFFIX) $(HOST_LIBS) $(HOST_EXTRA_DEPS) $(GLOBAL_DEPS)
+ 	$(REPORT_BUILD)
+ ifeq (WINNT_,$(HOST_OS_ARCH)_$(GNU_CC))
+-	$(EXPAND_LIBS_EXEC) -- $(LINKER) -NOLOGO -OUT:$@ -PDB:$(HOST_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
++	$(LINKER) -NOLOGO -OUT:$@ -PDB:$(HOST_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+ else
+ ifneq (,$(HOST_CPPSRCS)$(USE_HOST_CXX))
+-	$(EXPAND_LIBS_EXEC) -- $(HOST_CXX) $(HOST_OUTOPTION)$@ $(HOST_CXX_LDFLAGS) $< $(HOST_LIBS) $(HOST_EXTRA_LIBS)
++	$(HOST_CXX) $(HOST_OUTOPTION)$@ $(HOST_CXX_LDFLAGS) $< $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+ else
+-	$(EXPAND_LIBS_EXEC) -- $(HOST_CC) $(HOST_OUTOPTION)$@ $(HOST_C_LDFLAGS) $< $(HOST_LIBS) $(HOST_EXTRA_LIBS)
++	$(HOST_CC) $(HOST_OUTOPTION)$@ $(HOST_C_LDFLAGS) $< $(HOST_LIBS) $(HOST_EXTRA_LIBS)
+ endif
+ endif
+ ifndef CROSS_COMPILE
+ 	$(call py_action,check_binary,--host $@)
+ endif
+ 
+-$(filter %.$(LIB_SUFFIX),$(LIBRARY)): $(OBJS) $(STATIC_LIBS_DEPS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
++$(LIBRARY): $(OBJS) $(STATIC_LIBS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+ 	$(REPORT_BUILD)
+-# Always remove both library and library descriptor
+-	$(RM) $(REAL_LIBRARY) $(REAL_LIBRARY).$(LIBS_DESC_SUFFIX)
+-	$(EXPAND_AR) $(AR_FLAGS) $(OBJS) $(STATIC_LIBS)
+-
+-$(filter-out %.$(LIB_SUFFIX),$(LIBRARY)): $(filter %.$(LIB_SUFFIX),$(LIBRARY)) $(OBJS) $(STATIC_LIBS_DEPS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+-# When we only build a library descriptor, blow out any existing library
+-	$(REPORT_BUILD)
+-	$(if $(filter %.$(LIB_SUFFIX),$(LIBRARY)),,$(RM) $(REAL_LIBRARY))
+-	$(EXPAND_LIBS_GEN) -o $@ $(OBJS) $(STATIC_LIBS)
++	$(RM) $(REAL_LIBRARY)
++	$(AR) $(AR_FLAGS) $(OBJS) $($@_OBJS)
+ 
+ ifeq ($(OS_ARCH),WINNT)
+ # Import libraries are created by the rules creating shared libraries.
+ # The rules to copy them to $(DIST)/lib depend on $(IMPORT_LIBRARY),
+ # but make will happily consider the import library before it is refreshed
+ # when rebuilding the corresponding shared library. Defining an empty recipe
+ # for import libraries forces make to wait for the shared library recipe to
+ # have run before considering other targets that depend on the import library.
+ # See bug 795204.
+ $(IMPORT_LIBRARY): $(SHARED_LIBRARY) ;
+ endif
+ 
+ $(HOST_LIBRARY): $(HOST_OBJS) Makefile
+ 	$(REPORT_BUILD)
+ 	$(RM) $@
+-	$(EXPAND_LIBS_EXEC) --extract -- $(HOST_AR) $(HOST_AR_FLAGS) $(HOST_OBJS)
++	$(HOST_AR) $(HOST_AR_FLAGS) $(HOST_OBJS)
+ 
+ # On Darwin (Mac OS X), dwarf2 debugging uses debug info left in .o files,
+ # so instead of deleting .o files after repacking them into a dylib, we make
+ # symlinks back to the originals. The symlinks are a no-op for stabs debugging,
+ # so no need to conditionalize on OS version or debugging format.
+ 
+-$(SHARED_LIBRARY): $(OBJS) $(RESFILE) $(RUST_STATIC_LIB_FOR_SHARED_LIB) $(STATIC_LIBS_DEPS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
++$(SHARED_LIBRARY): $(OBJS) $(RESFILE) $(RUST_STATIC_LIB_FOR_SHARED_LIB) $(STATIC_LIBS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+ 	$(REPORT_BUILD)
+ ifndef INCREMENTAL_LINKER
+ 	$(RM) $@
+ endif
+-	$(EXPAND_MKSHLIB) $(OBJS) $(RESFILE) $(LDFLAGS) $(STATIC_LIBS) $(RUST_STATIC_LIB_FOR_SHARED_LIB) $(SHARED_LIBS) $(EXTRA_DSO_LDOPTS) $(MOZ_GLUE_LDFLAGS) $(OS_LIBS)
++	$(MKSHLIB) $($@_OBJS) $(RESFILE) $(LDFLAGS) $(STATIC_LIBS) $(RUST_STATIC_LIB_FOR_SHARED_LIB) $(SHARED_LIBS) $(EXTRA_DSO_LDOPTS) $(MOZ_GLUE_LDFLAGS) $(OS_LIBS)
+ 	$(call py_action,check_binary,--target $@)
+ 
+ ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+ ifdef MSMANIFEST_TOOL
+ ifdef EMBED_MANIFEST_AT
+ 	@if test -f $@.manifest; then \
+ 		if test -f '$(srcdir)/$@.manifest'; then \
+ 			echo 'Embedding manifest from $(srcdir)/$@.manifest and $@.manifest'; \
+diff --git a/config/tests/python.ini b/config/tests/python.ini
+--- a/config/tests/python.ini
++++ b/config/tests/python.ini
+@@ -1,5 +1,4 @@
+ [test_mozbuild_reading.py]
+-[unit-expandlibs.py]
+ [unit-mozunit.py]
+ [unit-nsinstall.py]
+ [unit-printprereleasesuffix.py]
+diff --git a/config/tests/unit-expandlibs.py b/config/tests/unit-expandlibs.py
+deleted file mode 100644
+--- a/config/tests/unit-expandlibs.py
++++ /dev/null
+@@ -1,431 +0,0 @@
+-import subprocess
+-import unittest
+-import sys
+-import os
+-import imp
+-from tempfile import mkdtemp
+-from shutil import rmtree
+-import mozunit
+-
+-from UserString import UserString
+-# Create a controlled configuration for use by expandlibs
+-config_win = {
+-    'AR': 'lib',
+-    'AR_EXTRACT': '',
+-    'DLL_PREFIX': '',
+-    'LIB_PREFIX': '',
+-    'OBJ_SUFFIX': '.obj',
+-    'LIB_SUFFIX': '.lib',
+-    'DLL_SUFFIX': '.dll',
+-    'IMPORT_LIB_SUFFIX': '.lib',
+-    'LIBS_DESC_SUFFIX': '.desc',
+-    'EXPAND_LIBS_LIST_STYLE': 'list',
+-}
+-config_unix = {
+-    'AR': 'ar',
+-    'AR_EXTRACT': 'ar -x',
+-    'DLL_PREFIX': 'lib',
+-    'LIB_PREFIX': 'lib',
+-    'OBJ_SUFFIX': '.o',
+-    'LIB_SUFFIX': '.a',
+-    'DLL_SUFFIX': '.so',
+-    'IMPORT_LIB_SUFFIX': '',
+-    'LIBS_DESC_SUFFIX': '.desc',
+-    'EXPAND_LIBS_LIST_STYLE': 'linkerscript',
+-}
+-
+-config = sys.modules['expandlibs_config'] = imp.new_module('expandlibs_config')
+-
+-from expandlibs import LibDescriptor, ExpandArgs, relativize
+-from expandlibs_gen import generate
+-from expandlibs_exec import ExpandArgsMore, SectionFinder
+-
+-def Lib(name):
+-    return config.LIB_PREFIX + name + config.LIB_SUFFIX
+-
+-def Obj(name):
+-    return name + config.OBJ_SUFFIX
+-
+-def Dll(name):
+-    return config.DLL_PREFIX + name + config.DLL_SUFFIX
+-
+-def ImportLib(name):
+-    if not len(config.IMPORT_LIB_SUFFIX): return Dll(name)
+-    return config.LIB_PREFIX + name + config.IMPORT_LIB_SUFFIX
+-
+-class TestRelativize(unittest.TestCase):
+-    def test_relativize(self):
+-        '''Test relativize()'''
+-        os_path_exists = os.path.exists
+-        def exists(path):
+-            return True
+-        os.path.exists = exists
+-        self.assertEqual(relativize(os.path.abspath(os.curdir)), os.curdir)
+-        self.assertEqual(relativize(os.path.abspath(os.pardir)), os.pardir)
+-        self.assertEqual(relativize(os.path.join(os.curdir, 'a')), 'a')
+-        self.assertEqual(relativize(os.path.join(os.path.abspath(os.curdir), 'a')), 'a')
+-        # relativize is expected to return the absolute path if it is shorter
+-        self.assertEqual(relativize(os.sep), os.sep)
+-        os.path.exists = os.path.exists
+-
+-class TestLibDescriptor(unittest.TestCase):
+-    def test_serialize(self):
+-        '''Test LibDescriptor's serialization'''
+-        desc = LibDescriptor()
+-        desc[LibDescriptor.KEYS[0]] = ['a', 'b']
+-        self.assertEqual(str(desc), "{0} = a b".format(LibDescriptor.KEYS[0]))
+-        desc['unsupported-key'] = ['a']
+-        self.assertEqual(str(desc), "{0} = a b".format(LibDescriptor.KEYS[0]))
+-        desc[LibDescriptor.KEYS[1]] = ['c', 'd', 'e']
+-        self.assertEqual(str(desc),
+-                         "{0} = a b\n{1} = c d e"
+-                         .format(LibDescriptor.KEYS[0], LibDescriptor.KEYS[1]))
+-        desc[LibDescriptor.KEYS[0]] = []
+-        self.assertEqual(str(desc), "{0} = c d e".format(LibDescriptor.KEYS[1]))
+-
+-    def test_read(self):
+-        '''Test LibDescriptor's initialization'''
+-        desc_list = ["# Comment",
+-                     "{0} = a b".format(LibDescriptor.KEYS[1]),
+-                     "", # Empty line
+-                     "foo = bar", # Should be discarded
+-                     "{0} = c d e".format(LibDescriptor.KEYS[0])]
+-        desc = LibDescriptor(desc_list)
+-        self.assertEqual(desc[LibDescriptor.KEYS[1]], ['a', 'b'])
+-        self.assertEqual(desc[LibDescriptor.KEYS[0]], ['c', 'd', 'e'])
+-        self.assertEqual(False, 'foo' in desc)
+-
+-def wrap_method(conf, wrapped_method):
+-    '''Wrapper used to call a test with a specific configuration'''
+-    def _method(self):
+-        for key in conf:
+-            setattr(config, key, conf[key])
+-        self.init()
+-        try:
+-            wrapped_method(self)
+-        except:
+-            raise
+-        finally:
+-            self.cleanup()
+-    return _method
+-
+-class ReplicateTests(type):
+-    '''Replicates tests for unix and windows variants'''
+-    def __new__(cls, clsName, bases, dict):
+-        for name in [key for key in dict if key.startswith('test_')]:
+-            dict[name + '_unix'] = wrap_method(config_unix, dict[name])
+-            dict[name + '_unix'].__doc__ = dict[name].__doc__ + ' (unix)'
+-            dict[name + '_win'] = wrap_method(config_win, dict[name])
+-            dict[name + '_win'].__doc__ = dict[name].__doc__ + ' (win)'
+-            del dict[name]
+-        return type.__new__(cls, clsName, bases, dict)
+-
+-class TestCaseWithTmpDir(unittest.TestCase):
+-    __metaclass__ = ReplicateTests
+-    def init(self):
+-        self.tmpdir = os.path.abspath(mkdtemp(dir=os.curdir))
+-
+-    def cleanup(self):
+-        rmtree(self.tmpdir)
+-
+-    def touch(self, files):
+-        for f in files:
+-            open(f, 'w').close()
+-
+-    def tmpfile(self, *args):
+-        return os.path.join(self.tmpdir, *args)
+-
+-class TestExpandLibsGen(TestCaseWithTmpDir):
+-    def test_generate(self):
+-        '''Test library descriptor generation'''
+-        files = [self.tmpfile(f) for f in
+-                 [Lib('a'), Obj('b'), Lib('c'), Obj('d'), Obj('e'), Lib('f')]]
+-        self.touch(files[:-1])
+-        self.touch([files[-1] + config.LIBS_DESC_SUFFIX])
+-
+-        desc = generate(files)
+-        self.assertEqual(desc['OBJS'], [self.tmpfile(Obj(s)) for s in ['b', 'd', 'e']])
+-        self.assertEqual(desc['LIBS'], [self.tmpfile(Lib(s)) for s in ['a', 'c', 'f']])
+-
+-        self.assertRaises(Exception, generate, files + [self.tmpfile(Obj('z'))])
+-        self.assertRaises(Exception, generate, files + [self.tmpfile(Lib('y'))])
+-
+-class TestExpandInit(TestCaseWithTmpDir):
+-    def init(self):
+-        ''' Initializes test environment for library expansion tests'''
+-        super(TestExpandInit, self).init()
+-        # Create 2 fake libraries, each containing 3 objects, and the second
+-        # including the first one and another library.
+-        os.mkdir(self.tmpfile('libx'))
+-        os.mkdir(self.tmpfile('liby'))
+-        self.libx_files = [self.tmpfile('libx', Obj(f)) for f in ['g', 'h', 'i']]
+-        self.liby_files = [self.tmpfile('liby', Obj(f)) for f in ['j', 'k', 'l']] + [self.tmpfile('liby', Lib('z'))]
+-        self.touch(self.libx_files + self.liby_files)
+-        with open(self.tmpfile('libx', Lib('x') + config.LIBS_DESC_SUFFIX), 'w') as f:
+-            f.write(str(generate(self.libx_files)))
+-        with open(self.tmpfile('liby', Lib('y') + config.LIBS_DESC_SUFFIX), 'w') as f:
+-            f.write(str(generate(self.liby_files + [self.tmpfile('libx', Lib('x'))])))
+-
+-        # Create various objects and libraries 
+-        self.arg_files = [self.tmpfile(f) for f in [Lib('a'), Obj('b'), Obj('c'), Lib('d'), Obj('e')]]
+-        # We always give library names (LIB_PREFIX/SUFFIX), even for
+-        # dynamic/import libraries
+-        self.files = self.arg_files + [self.tmpfile(ImportLib('f'))]
+-        self.arg_files += [self.tmpfile(Lib('f'))]
+-        self.touch(self.files)
+-
+-    def assertRelEqual(self, args1, args2):
+-        self.assertEqual(args1, [relativize(a) for a in args2])
+-
+-class TestExpandArgs(TestExpandInit):
+-    def test_expand(self):
+-        '''Test library expansion'''
+-        # Expanding arguments means libraries with a descriptor are expanded
+-        # with the descriptor content, and import libraries are used when
+-        # a library doesn't exist
+-        args = ExpandArgs(['foo', '-bar'] + self.arg_files + [self.tmpfile('liby', Lib('y'))])
+-        self.assertRelEqual(args, ['foo', '-bar'] + self.files + self.liby_files + self.libx_files) 
+-
+-        # When a library exists at the same time as a descriptor, we still use
+-        # the descriptor.
+-        self.touch([self.tmpfile('libx', Lib('x'))])
+-        args = ExpandArgs(['foo', '-bar'] + self.arg_files + [self.tmpfile('liby', Lib('y'))])
+-        self.assertRelEqual(args, ['foo', '-bar'] + self.files + self.liby_files + self.libx_files)
+-
+-        self.touch([self.tmpfile('liby', Lib('y'))])
+-        args = ExpandArgs(['foo', '-bar'] + self.arg_files + [self.tmpfile('liby', Lib('y'))])
+-        self.assertRelEqual(args, ['foo', '-bar'] + self.files + self.liby_files + self.libx_files)
+-
+-class TestExpandArgsMore(TestExpandInit):
+-    def test_makelist(self):
+-        '''Test grouping object files in lists'''
+-        # ExpandArgsMore does the same as ExpandArgs
+-        with ExpandArgsMore(['foo', '-bar'] + self.arg_files + [self.tmpfile('liby', Lib('y'))]) as args:
+-            self.assertRelEqual(args, ['foo', '-bar'] + self.files + self.liby_files + self.libx_files) 
+-
+-            # But also has an extra method replacing object files with a list
+-            args.makelist()
+-            # self.files has objects at #1, #2, #4
+-            self.assertRelEqual(args[:3], ['foo', '-bar'] + self.files[:1])
+-            self.assertRelEqual(args[4:], [self.files[3]] + self.files[5:] + [self.tmpfile('liby', Lib('z'))])
+-
+-            # Check the list file content
+-            objs = [f for f in self.files + self.liby_files + self.libx_files if f.endswith(config.OBJ_SUFFIX)]
+-            if config.EXPAND_LIBS_LIST_STYLE == "linkerscript":
+-                self.assertNotEqual(args[3][0], '@')
+-                filename = args[3]
+-                content = ['INPUT("{0}")'.format(relativize(f)) for f in objs]
+-                with open(filename, 'r') as f:
+-                    self.assertEqual([l.strip() for l in f.readlines() if len(l.strip())], content)
+-            elif config.EXPAND_LIBS_LIST_STYLE == "list":
+-                self.assertEqual(args[3][0], '@')
+-                filename = args[3][1:]
+-                content = objs
+-                with open(filename, 'r') as f:
+-                    self.assertRelEqual([l.strip() for l in f.readlines() if len(l.strip())], content)
+-
+-            tmp = args.tmp
+-        # Check that all temporary files are properly removed
+-        self.assertEqual(True, all([not os.path.exists(f) for f in tmp]))
+-
+-    def test_extract(self):
+-        '''Test library extraction'''
+-        # Divert subprocess.call
+-        subprocess_call = subprocess.call
+-        subprocess_check_output = subprocess.check_output
+-        def call(args, **kargs):
+-            if config.AR == 'lib':
+-                self.assertEqual(args[:2], [config.AR, '-NOLOGO'])
+-                self.assertTrue(args[2].startswith('-EXTRACT:'))
+-                extract = [args[2][len('-EXTRACT:'):]]
+-                self.assertTrue(extract)
+-                args = args[3:]
+-            else:
+-                # The command called is always AR_EXTRACT
+-                ar_extract = config.AR_EXTRACT.split()
+-                self.assertEqual(args[:len(ar_extract)], ar_extract)
+-                args = args[len(ar_extract):]
+-            # Remaining argument is always one library
+-            self.assertEqual(len(args), 1)
+-            arg = args[0]
+-            self.assertEqual(os.path.splitext(arg)[1], config.LIB_SUFFIX)
+-            # Simulate file extraction
+-            lib = os.path.splitext(os.path.basename(arg))[0]
+-            if config.AR != 'lib':
+-                extract = [lib, lib + '2']
+-            extract = [os.path.join(kargs['cwd'], f) for f in extract]
+-            if config.AR != 'lib':
+-                extract = [Obj(f) for f in extract]
+-            if not lib in extracted:
+-                extracted[lib] = []
+-            extracted[lib].extend(extract)
+-            self.touch(extract)
+-        subprocess.call = call
+-
+-        def check_output(args, **kargs):
+-            # The command called is always AR
+-            ar = config.AR
+-            self.assertEqual(args[0:3], [ar, '-NOLOGO', '-LIST'])
+-            # Remaining argument is always one library
+-            self.assertRelEqual([os.path.splitext(arg)[1] for arg in args[3:]],
+-[config.LIB_SUFFIX])
+-            # Simulate LIB -NOLOGO -LIST
+-            lib = os.path.splitext(os.path.basename(args[3]))[0]
+-            return '%s\n%s\n' % (Obj(lib), Obj(lib + '2'))
+-        subprocess.check_output = check_output
+-
+-        # ExpandArgsMore does the same as ExpandArgs
+-        self.touch([self.tmpfile('liby', Lib('y'))])
+-        for iteration in (1, 2):
+-            with ExpandArgsMore(['foo', '-bar'] + self.arg_files + [self.tmpfile('liby', Lib('y'))]) as args:
+-                files = self.files + self.liby_files + self.libx_files
+-
+-                self.assertRelEqual(args, ['foo', '-bar'] + files)
+-
+-                extracted = {}
+-                # ExpandArgsMore also has an extra method extracting static libraries
+-                # when possible
+-                args.extract()
+-
+-                # With AR_EXTRACT, it uses the descriptors when there are, and
+-                # actually
+-                # extracts the remaining libraries
+-                extracted_args = []
+-                for f in files:
+-                    if f.endswith(config.LIB_SUFFIX):
+-                        base = os.path.splitext(os.path.basename(f))[0]
+-                        # On the first iteration, we test the behavior of
+-                        # extracting archives that don't have a copy of their
+-                        # contents next to them, which is to use the file
+-                        # extracted from the archive in a temporary directory.
+-                        # On the second iteration, we test extracting archives
+-                        # that do have a copy of their contents next to them,
+-                        # in which case those contents are used instead of the
+-                        # temporarily extracted files.
+-                        if iteration == 1:
+-                            extracted_args.extend(sorted(extracted[base]))
+-                        else:
+-                            dirname = os.path.dirname(f[len(self.tmpdir)+1:])
+-                            if base.endswith('f'):
+-                                dirname = os.path.join(dirname, 'foo', 'bar')
+-                            extracted_args.extend([self.tmpfile(dirname, Obj(base)), self.tmpfile(dirname, Obj(base + '2'))])
+-                    else:
+-                        extracted_args.append(f)
+-                self.assertRelEqual(args, ['foo', '-bar'] + extracted_args)
+-
+-                tmp = args.tmp
+-            # Check that all temporary files are properly removed
+-            self.assertEqual(True, all([not os.path.exists(f) for f in tmp]))
+-
+-            # Create archives contents next to them for the second iteration.
+-            base = os.path.splitext(Lib('_'))[0]
+-            self.touch(self.tmpfile(Obj(base.replace('_', suffix))) for suffix in ('a', 'a2', 'd', 'd2'))
+-            try:
+-                os.makedirs(self.tmpfile('foo', 'bar'))
+-            except:
+-                pass
+-            self.touch(self.tmpfile('foo', 'bar', Obj(base.replace('_', suffix))) for suffix in ('f', 'f2'))
+-            self.touch(self.tmpfile('liby', Obj(base.replace('_', suffix))) for suffix in ('z', 'z2'))
+-
+-        # Restore subprocess.call and subprocess.check_output
+-        subprocess.call = subprocess_call
+-        subprocess.check_output = subprocess_check_output
+-
+-class FakeProcess(object):
+-    def __init__(self, out, err = ''):
+-        self.out = out
+-        self.err = err
+-
+-    def communicate(self):
+-        return (self.out, self.err)
+-
+-OBJDUMPS = {
+-'foo.o': '''
+-00000000 g     F .text\t00000001 foo
+-00000000 g     F .text._Z6foobarv\t00000001 _Z6foobarv
+-00000000 g     F .text.hello\t00000001 hello
+-00000000 g     F .text._ZThn4_6foobarv\t00000001 _ZThn4_6foobarv
+-''',
+-'bar.o': '''
+-00000000 g     F .text.hi\t00000001 hi
+-00000000 g     F .text.hot._Z6barbazv\t00000001 .hidden _Z6barbazv
+-''',
+-}
+-
+-PRINT_ICF = '''
+-ld: ICF folding section '.text.hello' in file 'foo.o'into '.text.hi' in file 'bar.o'
+-ld: ICF folding section '.foo' in file 'foo.o'into '.foo' in file 'bar.o'
+-'''
+-
+-class SubprocessPopen(object):
+-    def __init__(self, test):
+-        self.test = test
+-
+-    def __call__(self, args, stdout = None, stderr = None):
+-        self.test.assertEqual(stdout, subprocess.PIPE)
+-        self.test.assertEqual(stderr, subprocess.PIPE)
+-        if args[0] == 'objdump':
+-            self.test.assertEqual(args[1], '-t')
+-            self.test.assertTrue(args[2] in OBJDUMPS)
+-            return FakeProcess(OBJDUMPS[args[2]])
+-        else:
+-            return FakeProcess('', PRINT_ICF)
+-
+-class TestSectionFinder(unittest.TestCase):
+-    def test_getSections(self):
+-        '''Test SectionFinder'''
+-        # Divert subprocess.Popen
+-        subprocess_popen = subprocess.Popen
+-        subprocess.Popen = SubprocessPopen(self)
+-        config.EXPAND_LIBS_ORDER_STYLE = 'linkerscript'
+-        config.OBJ_SUFFIX = '.o'
+-        config.LIB_SUFFIX = '.a'
+-        finder = SectionFinder(['foo.o', 'bar.o'])
+-        self.assertEqual(finder.getSections('foobar'), [])
+-        self.assertEqual(finder.getSections('_Z6barbazv'), ['.text.hot._Z6barbazv'])
+-        self.assertEqual(finder.getSections('_Z6foobarv'), ['.text._Z6foobarv', '.text._ZThn4_6foobarv'])
+-        self.assertEqual(finder.getSections('_ZThn4_6foobarv'), ['.text._Z6foobarv', '.text._ZThn4_6foobarv'])
+-        subprocess.Popen = subprocess_popen
+-
+-class TestSymbolOrder(unittest.TestCase):
+-    def test_getOrderedSections(self):
+-        '''Test ExpandMoreArgs' _getOrderedSections'''
+-        # Divert subprocess.Popen
+-        subprocess_popen = subprocess.Popen
+-        subprocess.Popen = SubprocessPopen(self)
+-        config.EXPAND_LIBS_ORDER_STYLE = 'linkerscript'
+-        config.OBJ_SUFFIX = '.o'
+-        config.LIB_SUFFIX = '.a'
+-        config.LD_PRINT_ICF_SECTIONS = ''
+-        args = ExpandArgsMore(['foo', '-bar', 'bar.o', 'foo.o'])
+-        self.assertEqual(args._getOrderedSections(['_Z6foobarv', '_Z6barbazv']), ['.text._Z6foobarv', '.text._ZThn4_6foobarv', '.text.hot._Z6barbazv'])
+-        self.assertEqual(args._getOrderedSections(['_ZThn4_6foobarv', '_Z6barbazv']), ['.text._Z6foobarv', '.text._ZThn4_6foobarv', '.text.hot._Z6barbazv'])
+-        subprocess.Popen = subprocess_popen
+-
+-    def test_getFoldedSections(self):
+-        '''Test ExpandMoreArgs' _getFoldedSections'''
+-        # Divert subprocess.Popen
+-        subprocess_popen = subprocess.Popen
+-        subprocess.Popen = SubprocessPopen(self)
+-        config.LD_PRINT_ICF_SECTIONS = '-Wl,--print-icf-sections'
+-        args = ExpandArgsMore(['foo', '-bar', 'bar.o', 'foo.o'])
+-        self.assertEqual(args._getFoldedSections(), {'.text.hello': ['.text.hi'], '.text.hi': ['.text.hello']})
+-        subprocess.Popen = subprocess_popen
+-
+-    def test_getOrderedSectionsWithICF(self):
+-        '''Test ExpandMoreArgs' _getOrderedSections, with ICF'''
+-        # Divert subprocess.Popen
+-        subprocess_popen = subprocess.Popen
+-        subprocess.Popen = SubprocessPopen(self)
+-        config.EXPAND_LIBS_ORDER_STYLE = 'linkerscript'
+-        config.OBJ_SUFFIX = '.o'
+-        config.LIB_SUFFIX = '.a'
+-        config.LD_PRINT_ICF_SECTIONS = '-Wl,--print-icf-sections'
+-        args = ExpandArgsMore(['foo', '-bar', 'bar.o', 'foo.o'])
+-        self.assertEqual(args._getOrderedSections(['hello', '_Z6barbazv']), ['.text.hello', '.text.hi', '.text.hot._Z6barbazv'])
+-        self.assertEqual(args._getOrderedSections(['_ZThn4_6foobarv', 'hi', '_Z6barbazv']), ['.text._Z6foobarv', '.text._ZThn4_6foobarv', '.text.hi', '.text.hello', '.text.hot._Z6barbazv'])
+-        subprocess.Popen = subprocess_popen
+-
+-
+-if __name__ == '__main__':
+-    mozunit.main(runwith='unittest')
+diff --git a/python/mozbuild/mozbuild/backend/common.py b/python/mozbuild/mozbuild/backend/common.py
+--- a/python/mozbuild/mozbuild/backend/common.py
++++ b/python/mozbuild/mozbuild/backend/common.py
+@@ -22,30 +22,37 @@ from mozbuild.frontend.data import (
+     BaseProgram,
+     ChromeManifestEntry,
+     ConfigFileSubstitution,
+     Exports,
+     FinalTargetPreprocessedFiles,
+     FinalTargetFiles,
+     GeneratedSources,
+     GnProjectData,
++    HostLibrary,
++    HostRustLibrary,
+     IPDLCollection,
++    RustLibrary,
+     SharedLibrary,
++    StaticLibrary,
+     UnifiedSources,
+     XPIDLFile,
+     WebIDLCollection,
+ )
+ from mozbuild.jar import (
+     DeprecatedJarManifest,
+     JarManifestParser,
+ )
+ from mozbuild.preprocessor import Preprocessor
+ from mozpack.chrome.manifest import parse_manifest_line
+ 
+-from mozbuild.util import group_unified_files
++from mozbuild.util import (
++    group_unified_files,
++    mkdir,
++)
+ 
+ class XPIDLManager(object):
+     """Helps manage XPCOM IDLs in the context of the build system."""
+     def __init__(self, config):
+         self.config = config
+         self.topsrcdir = config.topsrcdir
+         self.topobjdir = config.topobjdir
+ 
+@@ -191,16 +198,97 @@ class CommonBackend(BuildBackend):
+ 
+         # Write out a file listing generated sources.
+         with self._write_file(mozpath.join(topobjdir, 'generated-sources.json')) as fh:
+             d = {
+                 'sources': sorted(self._generated_sources),
+             }
+             json.dump(d, fh, sort_keys=True, indent=4)
+ 
++    def _expand_libs(self, input_bin):
++        os_libs = []
++        shared_libs = []
++        static_libs = []
++        objs = []
++
++        seen_objs = set()
++        seen_libs = set()
++
++        def add_objs(lib):
++            for o in lib.objs:
++                if o not in seen_objs:
++                    seen_objs.add(o)
++                    objs.append(o)
++
++        def expand(lib, recurse_objs, system_libs):
++            if isinstance(lib, StaticLibrary):
++                if lib.no_expand_lib:
++                    static_libs.append(lib)
++                    recurse_objs = False
++                elif recurse_objs:
++                    add_objs(lib)
++
++                for l in lib.linked_libraries:
++                    expand(l, recurse_objs, system_libs)
++
++                if system_libs:
++                    for l in lib.linked_system_libs:
++                        if l not in seen_libs:
++                            seen_libs.add(l)
++                            os_libs.append(l)
++
++            elif isinstance(lib, SharedLibrary):
++                if lib not in seen_libs:
++                    seen_libs.add(lib)
++                    shared_libs.append(lib)
++
++        add_objs(input_bin)
++
++        system_libs = not isinstance(input_bin, StaticLibrary)
++        for lib in input_bin.linked_libraries:
++            if isinstance(lib, RustLibrary):
++                continue
++            elif isinstance(lib, StaticLibrary):
++                expand(lib, True, system_libs)
++            elif isinstance(lib, SharedLibrary):
++                if lib not in seen_libs:
++                    seen_libs.add(lib)
++                    shared_libs.append(lib)
++
++        for lib in input_bin.linked_system_libs:
++            if lib not in seen_libs:
++                seen_libs.add(lib)
++                os_libs.append(lib)
++
++        return objs, shared_libs, os_libs, static_libs
++
++    def _make_list_file(self, objdir, objs, name):
++        if not objs:
++            return None
++        list_style = self.environment.substs.get('EXPAND_LIBS_LIST_STYLE')
++        list_file_path = mozpath.join(objdir, name)
++        objs = [os.path.relpath(o, objdir) for o in objs]
++        if list_style == 'linkerscript':
++            ref = list_file_path
++            content = '\n'.join('INPUT("%s")' % o for o in objs)
++        elif list_style == 'filelist':
++            ref = "-Wl,-filelist," + list_file_path
++            content = '\n'.join(objs)
++        elif list_style == 'list':
++            ref = "@" + list_file_path
++            content = '\n'.join(objs)
++        else:
++            return None
++
++        mkdir(objdir)
++        with self._write_file(list_file_path) as fh:
++            fh.write(content)
++
++        return ref
++
+     def _handle_generated_sources(self, files):
+         self._generated_sources.update(mozpath.relpath(f, self.environment.topobjdir) for f in files)
+ 
+     def _handle_webidl_collection(self, webidls):
+ 
+         bindings_dir = mozpath.join(self.environment.topobjdir, 'dom', 'bindings')
+ 
+         all_inputs = set(webidls.all_static_sources())
+diff --git a/python/mozbuild/mozbuild/backend/recursivemake.py b/python/mozbuild/mozbuild/backend/recursivemake.py
+--- a/python/mozbuild/mozbuild/backend/recursivemake.py
++++ b/python/mozbuild/mozbuild/backend/recursivemake.py
+@@ -1307,77 +1307,78 @@ class RecursiveMakeBackend(CommonBackend
+     def _process_host_library(self, libdef, backend_file):
+         backend_file.write('HOST_LIBRARY_NAME = %s\n' % libdef.basename)
+ 
+     def _build_target_for_obj(self, obj):
+         return '%s/%s' % (mozpath.relpath(obj.objdir,
+             self.environment.topobjdir), obj.KIND)
+ 
+     def _process_linked_libraries(self, obj, backend_file):
+-        def write_shared_and_system_libs(lib):
+-            for l in lib.linked_libraries:
+-                if isinstance(l, (StaticLibrary, RustLibrary)):
+-                    write_shared_and_system_libs(l)
+-                else:
+-                    backend_file.write_once('SHARED_LIBS += %s/%s\n'
+-                        % (pretty_relpath(l), l.import_name))
+-            for l in lib.linked_system_libs:
+-                backend_file.write_once('OS_LIBS += %s\n' % l)
+-
+         def pretty_relpath(lib):
+             return '$(DEPTH)/%s' % mozpath.relpath(lib.objdir, topobjdir)
+ 
+         topobjdir = mozpath.normsep(obj.topobjdir)
+         # This will create the node even if there aren't any linked libraries.
+         build_target = self._build_target_for_obj(obj)
+         self._compile_graph[build_target]
+ 
++        objs, shared_libs, os_libs, static_libs = self._expand_libs(obj)
++
++        if obj.KIND == 'target':
++            obj_target = obj.name
++            if isinstance(obj, Program):
++                obj_target = self._pretty_path(obj.output_path, backend_file)
++
++            objs_ref = ' \\\n    '.join(os.path.relpath(o, obj.objdir)
++                                        for o in objs)
++            # Don't bother with a list file if we're only linking objects built
++            # in this directory or building a real static library. This
++            # accommodates clang-plugin, where we would otherwise pass an
++            # incorrect list file format to the host compiler as well as when
++            # creating an archive with AR, which doesn't understand list files.
++            if (objs == obj.objs and not isinstance(obj, StaticLibrary) or
++                isinstance(obj, StaticLibrary) and obj.no_expand_lib):
++                backend_file.write_once('%s_OBJS := %s\n' %
++                                        (obj.name, objs_ref))
++                backend_file.write_once('%s: %s\n' % (obj_target, objs_ref))
++            elif not isinstance(obj, StaticLibrary):
++                list_file_path = '%s.list' % obj.name.replace('.', '_')
++                list_file_ref = self._make_list_file(obj.objdir, objs,
++                                                     list_file_path)
++                backend_file.write_once('%s_OBJS := %s\n' %
++                                        (obj.name, list_file_ref))
++                backend_file.write_once('%s: %s\n' % (obj_target, list_file_path))
++                backend_file.write_once('%s: %s\n' % (obj_target, objs_ref))
++
++        for lib in shared_libs:
++            backend_file.write_once('SHARED_LIBS += %s/%s\n' %
++                                    (pretty_relpath(lib), lib.import_name))
++        for lib in static_libs:
++            backend_file.write_once('STATIC_LIBS += %s/%s\n' %
++                                    (pretty_relpath(lib), lib.import_name))
++        for lib in os_libs:
++            if obj.KIND == 'target':
++                backend_file.write_once('OS_LIBS += %s\n' % lib)
++            else:
++                backend_file.write_once('HOST_EXTRA_LIBS += %s\n' % lib)
++
+         for lib in obj.linked_libraries:
+             if not isinstance(lib, ExternalLibrary):
+                 self._compile_graph[build_target].add(
+                     self._build_target_for_obj(lib))
+-            relpath = pretty_relpath(lib)
+-            if isinstance(obj, Library):
+-                if isinstance(lib, RustLibrary):
+-                    # We don't need to do anything here; we will handle
+-                    # linkage for any RustLibrary elsewhere.
+-                    continue
+-                elif isinstance(lib, StaticLibrary):
+-                    backend_file.write_once('STATIC_LIBS += %s/%s\n'
+-                                        % (relpath, lib.import_name))
+-                    if isinstance(obj, SharedLibrary):
+-                        write_shared_and_system_libs(lib)
+-                elif isinstance(obj, SharedLibrary):
+-                    backend_file.write_once('SHARED_LIBS += %s/%s\n'
+-                                        % (relpath, lib.import_name))
+-            elif isinstance(obj, (Program, SimpleProgram)):
+-                if isinstance(lib, StaticLibrary):
+-                    backend_file.write_once('STATIC_LIBS += %s/%s\n'
+-                                        % (relpath, lib.import_name))
+-                    write_shared_and_system_libs(lib)
+-                else:
+-                    backend_file.write_once('SHARED_LIBS += %s/%s\n'
+-                                        % (relpath, lib.import_name))
+-            elif isinstance(obj, (HostLibrary, HostProgram, HostSimpleProgram)):
+-                assert isinstance(lib, (HostLibrary, HostRustLibrary))
+-                backend_file.write_once('HOST_LIBS += %s/%s\n'
+-                                   % (relpath, lib.import_name))
++            if isinstance(lib, (HostLibrary, HostRustLibrary)):
++                backend_file.write_once('HOST_LIBS += %s/%s\n' %
++                                        (pretty_relpath(lib), lib.import_name))
+ 
+         # We have to link any Rust libraries after all intermediate static
+         # libraries have been listed to ensure that the Rust libraries are
+         # searched after the C/C++ objects that might reference Rust symbols.
+         if isinstance(obj, SharedLibrary):
+             self._process_rust_libraries(obj, backend_file, pretty_relpath)
+ 
+-        for lib in obj.linked_system_libs:
+-            if obj.KIND == 'target':
+-                backend_file.write_once('OS_LIBS += %s\n' % lib)
+-            else:
+-                backend_file.write_once('HOST_EXTRA_LIBS += %s\n' % lib)
+-
+         # Process library-based defines
+         self._process_defines(obj.lib_defines, backend_file)
+ 
+     def _process_rust_libraries(self, obj, backend_file, pretty_relpath):
+         assert isinstance(obj, SharedLibrary)
+ 
+         # If this library does not depend on any Rust libraries, then we are done.
+         direct_linked = [l for l in obj.linked_libraries if isinstance(l, RustLibrary)]
+diff --git a/python/mozbuild/mozbuild/test/backend/common.py b/python/mozbuild/mozbuild/test/backend/common.py
+--- a/python/mozbuild/mozbuild/test/backend/common.py
++++ b/python/mozbuild/mozbuild/test/backend/common.py
+@@ -209,16 +209,17 @@ CONFIGS = defaultdict(lambda: {
+         'defines': {},
+         'non_global_defines': [],
+         'substs': {
+             'COMPILE_ENVIRONMENT': '1',
+             'LIB_SUFFIX': 'a',
+             'BIN_SUFFIX': '.exe',
+             'DLL_SUFFIX': '.so',
+             'OBJ_SUFFIX': 'o',
++            'EXPAND_LIBS_LIST_STYLE': 'list',
+         },
+     },
+ })
+ 
+ 
+ class BackendTester(unittest.TestCase):
+     def setUp(self):
+         self._old_env = dict(os.environ)
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/bar2.cc b/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/bar2.cc
+new file mode 100644
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/bar_helper/bar_helper1.cpp b/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/bar_helper/bar_helper1.cpp
+new file mode 100644
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/bar_helper/moz.build b/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/bar_helper/moz.build
+new file mode 100644
+--- /dev/null
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/bar_helper/moz.build
+@@ -0,0 +1,8 @@
++# Any copyright is dedicated to the Public Domain.
++# http://creativecommons.org/publicdomain/zero/1.0/
++
++SOURCES += [
++    'bar_helper1.cpp',
++]
++
++FINAL_LIBRARY = 'bar'
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/moz.build b/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/moz.build
+--- a/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/moz.build
++++ b/python/mozbuild/mozbuild/test/backend/data/linkage/static/bar/moz.build
+@@ -1,8 +1,13 @@
+ # Any copyright is dedicated to the Public Domain.
+ # http://creativecommons.org/publicdomain/zero/1.0/
+ 
+ SOURCES += [
+     'bar1.cc',
++    'bar2.cc',
++]
++
++DIRS += [
++    'bar_helper',
+ ]
+ 
+ FINAL_LIBRARY = 'bar'
+\ No newline at end of file
+diff --git a/python/mozbuild/mozbuild/test/backend/test_recursivemake.py b/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
+--- a/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
++++ b/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
+@@ -986,40 +986,34 @@ class TestRecursiveMakeBackend(BackendTe
+ 
+             for line in lines:
+                 self.assertNotIn('LIB_IS_C_ONLY', line)
+ 
+     def test_linkage(self):
+         env = self._consume('linkage', RecursiveMakeBackend)
+         expected_linkage = {
+             'prog': {
+-                'SHARED_LIBS': ['$(DEPTH)/shared/baz', '$(DEPTH)/prog/qux/qux'],
+-                'STATIC_LIBS': ['$(DEPTH)/static/bar%s' % env.lib_suffix],
++                'SHARED_LIBS': ['$(DEPTH)/prog/qux/qux.so',
++                                '$(DEPTH)/shared/baz.so'],
++                'STATIC_LIBS': ['$(DEPTH)/real/foo.a'],
+                 'OS_LIBS': ['-lfoo', '-lbaz', '-lbar'],
+             },
+             'shared': {
+                 'OS_LIBS': ['-lfoo'],
+-                'SHARED_LIBS': ['$(DEPTH)/prog/qux/qux'],
+-                'STATIC_LIBS': ['$(DEPTH)/shared/baz/shared_baz%s' %
+-                                env.lib_suffix],
++                'SHARED_LIBS': ['$(DEPTH)/prog/qux/qux.so'],
++                'STATIC_LIBS': [],
+             },
+             'static': {
+-                'STATIC_LIBS': [
+-                    '$(DEPTH)/static/bar/static_bar.a',
+-                    '$(DEPTH)/real/foo.a',
+-                ],
++                'STATIC_LIBS': ['$(DEPTH)/real/foo.a'],
+                 'OS_LIBS': ['-lbar'],
+-                'SHARED_LIBS': [],
++                'SHARED_LIBS': ['$(DEPTH)/prog/qux/qux.so'],
+             },
+             'real': {
+-                'STATIC_LIBS': [
+-                    '$(DEPTH)/shared/baz_s%s' % env.lib_suffix,
+-                    '$(DEPTH)/real/foo/real_foo%s' % env.lib_suffix,
+-                ],
+-                'SHARED_LIBS': [],
++                'STATIC_LIBS': [],
++                'SHARED_LIBS': ['$(DEPTH)/prog/qux/qux.so'],
+                 'OS_LIBS': ['-lbaz'],
+             }
+         }
+         actual_linkage = {}
+         for name in expected_linkage.keys():
+             with open(os.path.join(env.topobjdir, name, 'backend.mk'), 'rb') as fh:
+                 actual_linkage[name] = [line.rstrip() for line in fh.readlines()]
+         for name in expected_linkage:
+@@ -1027,16 +1021,44 @@ class TestRecursiveMakeBackend(BackendTe
+                 for val in expected_linkage[name][var]:
+                     line = '%s += %s' % (var, val)
+                     self.assertIn(line,
+                                   actual_linkage[name])
+                     actual_linkage[name].remove(line)
+                 for line in actual_linkage[name]:
+                     self.assertNotIn('%s +=' % var, line)
+ 
++    def test_list_files(self):
++        env = self._consume('linkage', RecursiveMakeBackend)
++        expected_list_files = {
++            'prog/MyProgram_exe.list': [
++                '../static/bar/bar1.o',
++                '../static/bar/bar2.o',
++                '../static/bar/bar_helper/bar_helper1.o',
++            ],
++            'shared/baz_so.list': [
++                'baz/baz1.o',
++            ],
++        }
++        actual_list_files = {}
++        for name in expected_list_files.keys():
++            with open(os.path.join(env.topobjdir, name), 'rb') as fh:
++                actual_list_files[name] = [mozpath.normsep(line.rstrip())
++                                           for line in fh.readlines()]
++        for name in expected_list_files:
++            self.assertEqual(actual_list_files[name],
++                             expected_list_files[name])
++
++        # We don't produce a list file for a shared library composed only of
++        # object files in its directory, but instead list them in a variable.
++        with open(os.path.join(env.topobjdir, 'prog', 'qux', 'backend.mk'), 'rb') as fh:
++            lines = [line.rstrip() for line in fh.readlines()]
++
++        self.assertIn('qux.so_OBJS := qux1.o', lines)
++
+     def test_jar_manifests(self):
+         env = self._consume('jar-manifests', RecursiveMakeBackend)
+ 
+         with open(os.path.join(env.topobjdir, 'backend.mk'), 'rb') as fh:
+             lines = fh.readlines()
+ 
+         lines = [line.rstrip() for line in lines]
+ 

+ 386 - 0
rel-257/ian/patches/1429875-5-61a1.patch

@@ -0,0 +1,386 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1521589452 25200
+# Node ID cd90d8ccc5be982afb1bab0a2f2a649e10491817
+# Parent  af91387c51716e6fbd3774083cce06a93328a606
+Bug 1429875 - Implement OBJ_SUFFIX overriding for the profile generation phase on linux in mozbuild. r=glandium
+
+MozReview-Commit-ID: 8PtgxfbxuE
+
+diff --git a/config/config.mk b/config/config.mk
+--- a/config/config.mk
++++ b/config/config.mk
+@@ -415,25 +415,28 @@ endif
+ 
+ # MDDEPDIR is the subdirectory where dependency files are stored
+ MDDEPDIR := .deps
+ 
+ # autoconf.mk sets OBJ_SUFFIX to an error to avoid use before including
+ # this file
+ OBJ_SUFFIX := $(_OBJ_SUFFIX)
+ 
++OBJS_VAR_SUFFIX := OBJS
++
+ # PGO builds with GCC build objects with instrumentation in a first pass,
+ # then objects optimized, without instrumentation, in a second pass. If
+ # we overwrite the objects from the first pass with those from the second,
+ # we end up not getting instrumentation data for better optimization on
+ # incremental builds. As a consequence, we use a different object suffix
+ # for the first pass.
+-ifndef NO_PROFILE_GUIDED_OPTIMIZE
+ ifdef MOZ_PROFILE_GENERATE
+ ifdef GNU_CC
++OBJS_VAR_SUFFIX := PGO_OBJS
++ifndef NO_PROFILE_GUIDED_OPTIMIZE
+ OBJ_SUFFIX := i_o
+ endif
+ endif
+ endif
+ 
+ PLY_INCLUDE = -I$(MOZILLA_DIR)/other-licenses/ply
+ 
+ export CL_INCLUDES_PREFIX
+diff --git a/config/rules.mk b/config/rules.mk
+--- a/config/rules.mk
++++ b/config/rules.mk
+@@ -553,17 +553,17 @@ endif
+ #
+ # PROGRAM = Foo
+ # creates OBJS, links with LIBS to create Foo
+ #
+ $(PROGRAM): $(PROGOBJS) $(STATIC_LIBS) $(EXTRA_DEPS) $(RESFILE) $(GLOBAL_DEPS) $(call mkdir_deps,$(FINAL_TARGET))
+ 	$(REPORT_BUILD)
+ 	@$(RM) $@.manifest
+ ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+-	$(LINKER) -NOLOGO -OUT:$(call LINKER_OUT,$@) -PDB:$(LINK_PDBFILE) -IMPLIB:$(basename $(@F)).lib $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $($(notdir $@)_OBJS) $(RESFILE) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
++	$(LINKER) -NOLOGO -OUT:$(call LINKER_OUT,$@) -PDB:$(LINK_PDBFILE) -IMPLIB:$(basename $(@F)).lib $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $($(notdir $@)_$(OBJS_VAR_SUFFIX)) $(RESFILE) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
+ ifdef MSMANIFEST_TOOL
+ 	@if test -f $@.manifest; then \
+ 		if test -f '$(srcdir)/$(notdir $@).manifest'; then \
+ 			echo 'Embedding manifest from $(srcdir)/$(notdir $@).manifest and $@.manifest'; \
+ 			$(MT) -NOLOGO -MANIFEST '$(win_srcdir)/$(notdir $@).manifest' $@.manifest -OUTPUTRESOURCE:$@\;1; \
+ 		else \
+ 			echo 'Embedding manifest from $@.manifest'; \
+ 			$(MT) -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
+@@ -574,17 +574,17 @@ ifdef MSMANIFEST_TOOL
+ 	fi
+ endif	# MSVC with manifest tool
+ ifdef MOZ_PROFILE_GENERATE
+ # touch it a few seconds into the future to work around FAT's
+ # 2-second granularity
+ 	touch -t `date +%Y%m%d%H%M.%S -d 'now+5seconds'` pgo.relink
+ endif
+ else # !WINNT || GNU_CC
+-	$(call EXPAND_CC_OR_CXX,$@) -o $@ $(COMPUTED_CXX_LDFLAGS) $(PGO_CFLAGS) $($(notdir $@)_OBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(STATIC_LIBS) $(MOZ_PROGRAM_LDFLAGS) $(SHARED_LIBS) $(OS_LIBS)
++	$(call EXPAND_CC_OR_CXX,$@) -o $@ $(COMPUTED_CXX_LDFLAGS) $(PGO_CFLAGS) $($(notdir $@)_$(OBJS_VAR_SUFFIX)) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(STATIC_LIBS) $(MOZ_PROGRAM_LDFLAGS) $(SHARED_LIBS) $(OS_LIBS)
+ 	$(call py_action,check_binary,--target $@)
+ endif # WINNT && !GNU_CC
+ 
+ ifdef ENABLE_STRIP
+ 	$(STRIP) $(STRIP_FLAGS) $@
+ endif
+ ifdef MOZ_POST_PROGRAM_COMMAND
+ 	$(MOZ_POST_PROGRAM_COMMAND) $@
+@@ -625,25 +625,25 @@ endif
+ # Foo.o (from either Foo.c or Foo.cpp).
+ #
+ # SIMPLE_PROGRAMS = Foo Bar
+ # creates Foo.o Bar.o, links with LIBS to create Foo, Bar.
+ #
+ $(SIMPLE_PROGRAMS): %$(BIN_SUFFIX): %.$(OBJ_SUFFIX) $(STATIC_LIBS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+ 	$(REPORT_BUILD)
+ ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+-	$(LINKER) -nologo -out:$@ -pdb:$(LINK_PDBFILE) $($@_OBJS) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
++	$(LINKER) -nologo -out:$@ -pdb:$(LINK_PDBFILE) $($@_$(OBJS_VAR_SUFFIX)) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_PROGRAM_LDFLAGS) $(STATIC_LIBS) $(SHARED_LIBS) $(OS_LIBS)
+ ifdef MSMANIFEST_TOOL
+ 	@if test -f $@.manifest; then \
+ 		$(MT) -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
+ 		rm -f $@.manifest; \
+ 	fi
+ endif	# MSVC with manifest tool
+ else
+-	$(call EXPAND_CC_OR_CXX,$@) $(COMPUTED_CXX_LDFLAGS) $(PGO_CFLAGS) -o $@ $($@_OBJS) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(STATIC_LIBS) $(MOZ_PROGRAM_LDFLAGS) $(SHARED_LIBS) $(OS_LIBS)
++	$(call EXPAND_CC_OR_CXX,$@) $(COMPUTED_CXX_LDFLAGS) $(PGO_CFLAGS) -o $@ $($@_$(OBJS_VAR_SUFFIX)) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(STATIC_LIBS) $(MOZ_PROGRAM_LDFLAGS) $(SHARED_LIBS) $(OS_LIBS)
+ 	$(call py_action,check_binary,--target $@)
+ endif # WINNT && !GNU_CC
+ 
+ ifdef ENABLE_STRIP
+ 	$(STRIP) $(STRIP_FLAGS) $@
+ endif
+ ifdef MOZ_POST_PROGRAM_COMMAND
+ 	$(MOZ_POST_PROGRAM_COMMAND) $@
+@@ -662,17 +662,17 @@ endif
+ endif
+ ifndef CROSS_COMPILE
+ 	$(call py_action,check_binary,--host $@)
+ endif
+ 
+ $(LIBRARY): $(OBJS) $(STATIC_LIBS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+ 	$(REPORT_BUILD)
+ 	$(RM) $(REAL_LIBRARY)
+-	$(AR) $(AR_FLAGS) $(OBJS) $($@_OBJS)
++	$(AR) $(AR_FLAGS) $(OBJS) $($@_$(OBJS_VAR_SUFFIX))
+ 
+ ifeq ($(OS_ARCH),WINNT)
+ # Import libraries are created by the rules creating shared libraries.
+ # The rules to copy them to $(DIST)/lib depend on $(IMPORT_LIBRARY),
+ # but make will happily consider the import library before it is refreshed
+ # when rebuilding the corresponding shared library. Defining an empty recipe
+ # for import libraries forces make to wait for the shared library recipe to
+ # have run before considering other targets that depend on the import library.
+@@ -690,17 +690,17 @@ endif
+ # symlinks back to the originals. The symlinks are a no-op for stabs debugging,
+ # so no need to conditionalize on OS version or debugging format.
+ 
+ $(SHARED_LIBRARY): $(OBJS) $(RESFILE) $(RUST_STATIC_LIB_FOR_SHARED_LIB) $(STATIC_LIBS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+ 	$(REPORT_BUILD)
+ ifndef INCREMENTAL_LINKER
+ 	$(RM) $@
+ endif
+-	$(MKSHLIB) $($@_OBJS) $(RESFILE) $(LDFLAGS) $(STATIC_LIBS) $(RUST_STATIC_LIB_FOR_SHARED_LIB) $(SHARED_LIBS) $(EXTRA_DSO_LDOPTS) $(MOZ_GLUE_LDFLAGS) $(OS_LIBS)
++	$(MKSHLIB) $($@_$(OBJS_VAR_SUFFIX)) $(RESFILE) $(LDFLAGS) $(STATIC_LIBS) $(RUST_STATIC_LIB_FOR_SHARED_LIB) $(SHARED_LIBS) $(EXTRA_DSO_LDOPTS) $(MOZ_GLUE_LDFLAGS) $(OS_LIBS)
+ 	$(call py_action,check_binary,--target $@)
+ 
+ ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
+ ifdef MSMANIFEST_TOOL
+ ifdef EMBED_MANIFEST_AT
+ 	@if test -f $@.manifest; then \
+ 		if test -f '$(srcdir)/$@.manifest'; then \
+ 			echo 'Embedding manifest from $(srcdir)/$@.manifest and $@.manifest'; \
+diff --git a/python/mozbuild/mozbuild/backend/common.py b/python/mozbuild/mozbuild/backend/common.py
+--- a/python/mozbuild/mozbuild/backend/common.py
++++ b/python/mozbuild/mozbuild/backend/common.py
+@@ -203,25 +203,31 @@ class CommonBackend(BuildBackend):
+             }
+             json.dump(d, fh, sort_keys=True, indent=4)
+ 
+     def _expand_libs(self, input_bin):
+         os_libs = []
+         shared_libs = []
+         static_libs = []
+         objs = []
++        no_pgo_objs = []
+ 
+         seen_objs = set()
+         seen_libs = set()
+ 
+         def add_objs(lib):
+             for o in lib.objs:
+                 if o not in seen_objs:
+                     seen_objs.add(o)
+                     objs.append(o)
++                    # This is slightly odd, buf for consistency with the
++                    # recursivemake backend we don't replace OBJ_SUFFIX if any
++                    # object in a library has `no_pgo` set.
++                    if lib.no_pgo_objs or lib.no_pgo:
++                        no_pgo_objs.append(o)
+ 
+         def expand(lib, recurse_objs, system_libs):
+             if isinstance(lib, StaticLibrary):
+                 if lib.no_expand_lib:
+                     static_libs.append(lib)
+                     recurse_objs = False
+                 elif recurse_objs:
+                     add_objs(lib)
+@@ -253,17 +259,17 @@ class CommonBackend(BuildBackend):
+                     seen_libs.add(lib)
+                     shared_libs.append(lib)
+ 
+         for lib in input_bin.linked_system_libs:
+             if lib not in seen_libs:
+                 seen_libs.add(lib)
+                 os_libs.append(lib)
+ 
+-        return objs, shared_libs, os_libs, static_libs
++        return objs, no_pgo_objs, shared_libs, os_libs, static_libs
+ 
+     def _make_list_file(self, objdir, objs, name):
+         if not objs:
+             return None
+         list_style = self.environment.substs.get('EXPAND_LIBS_LIST_STYLE')
+         list_file_path = mozpath.join(objdir, name)
+         objs = [os.path.relpath(o, objdir) for o in objs]
+         if list_style == 'linkerscript':
+diff --git a/python/mozbuild/mozbuild/backend/recursivemake.py b/python/mozbuild/mozbuild/backend/recursivemake.py
+--- a/python/mozbuild/mozbuild/backend/recursivemake.py
++++ b/python/mozbuild/mozbuild/backend/recursivemake.py
+@@ -1315,43 +1315,78 @@ class RecursiveMakeBackend(CommonBackend
+         def pretty_relpath(lib):
+             return '$(DEPTH)/%s' % mozpath.relpath(lib.objdir, topobjdir)
+ 
+         topobjdir = mozpath.normsep(obj.topobjdir)
+         # This will create the node even if there aren't any linked libraries.
+         build_target = self._build_target_for_obj(obj)
+         self._compile_graph[build_target]
+ 
+-        objs, shared_libs, os_libs, static_libs = self._expand_libs(obj)
++        objs, no_pgo_objs, shared_libs, os_libs, static_libs = self._expand_libs(obj)
+ 
+         if obj.KIND == 'target':
+             obj_target = obj.name
+             if isinstance(obj, Program):
+                 obj_target = self._pretty_path(obj.output_path, backend_file)
+ 
++            is_unit_test = isinstance(obj, BaseProgram) and obj.is_unit_test
++            profile_gen_objs = []
++
++            if (self.environment.substs.get('MOZ_PGO') and
++                self.environment.substs.get('GNU_CC')):
++                # We use a different OBJ_SUFFIX for the profile generate phase on
++                # linux. These get picked up via OBJS_VAR_SUFFIX in config.mk.
++                if not is_unit_test and not isinstance(obj, SimpleProgram):
++                    profile_gen_objs = [o if o in no_pgo_objs else '%s.%s' %
++                                        (mozpath.splitext(o)[0], 'i_o') for o in objs]
++
++            def write_obj_deps(target, objs_ref, pgo_objs_ref):
++                if pgo_objs_ref:
++                    backend_file.write('ifdef MOZ_PROFILE_GENERATE\n')
++                    backend_file.write('%s: %s\n' % (target, pgo_objs_ref))
++                    backend_file.write('else\n')
++                    backend_file.write('%s: %s\n' % (target, objs_ref))
++                    backend_file.write('endif\n')
++                else:
++                    backend_file.write('%s: %s\n' % (target, objs_ref))
++
+             objs_ref = ' \\\n    '.join(os.path.relpath(o, obj.objdir)
+                                         for o in objs)
++            pgo_objs_ref = ' \\\n    '.join(os.path.relpath(o, obj.objdir)
++                                            for o in profile_gen_objs)
+             # Don't bother with a list file if we're only linking objects built
+             # in this directory or building a real static library. This
+             # accommodates clang-plugin, where we would otherwise pass an
+             # incorrect list file format to the host compiler as well as when
+             # creating an archive with AR, which doesn't understand list files.
+             if (objs == obj.objs and not isinstance(obj, StaticLibrary) or
+-                isinstance(obj, StaticLibrary) and obj.no_expand_lib):
+-                backend_file.write_once('%s_OBJS := %s\n' %
+-                                        (obj.name, objs_ref))
+-                backend_file.write_once('%s: %s\n' % (obj_target, objs_ref))
++              isinstance(obj, StaticLibrary) and obj.no_expand_lib):
++                backend_file.write_once('%s_OBJS := %s\n' % (obj.name,
++                                                             objs_ref))
++                if profile_gen_objs:
++                    backend_file.write_once('%s_PGO_OBJS := %s\n' % (obj.name,
++                                                                     pgo_objs_ref))
++                write_obj_deps(obj_target, objs_ref, pgo_objs_ref)
+             elif not isinstance(obj, StaticLibrary):
+                 list_file_path = '%s.list' % obj.name.replace('.', '_')
+                 list_file_ref = self._make_list_file(obj.objdir, objs,
+                                                      list_file_path)
+                 backend_file.write_once('%s_OBJS := %s\n' %
+                                         (obj.name, list_file_ref))
+                 backend_file.write_once('%s: %s\n' % (obj_target, list_file_path))
+-                backend_file.write_once('%s: %s\n' % (obj_target, objs_ref))
++                if profile_gen_objs:
++                    pgo_list_file_path = '%s_pgo.list' % obj.name.replace('.', '_')
++                    pgo_list_file_ref = self._make_list_file(obj.objdir,
++                                                             profile_gen_objs,
++                                                             pgo_list_file_path)
++                    backend_file.write_once('%s_PGO_OBJS := %s\n' %
++                                            (obj.name, pgo_list_file_ref))
++                    backend_file.write_once('%s: %s\n' % (obj_target,
++                                                          pgo_list_file_path))
++                write_obj_deps(obj_target, objs_ref, pgo_objs_ref)
+ 
+         for lib in shared_libs:
+             backend_file.write_once('SHARED_LIBS += %s/%s\n' %
+                                     (pretty_relpath(lib), lib.import_name))
+         for lib in static_libs:
+             backend_file.write_once('STATIC_LIBS += %s/%s\n' %
+                                     (pretty_relpath(lib), lib.import_name))
+         for lib in os_libs:
+diff --git a/python/mozbuild/mozbuild/frontend/data.py b/python/mozbuild/mozbuild/frontend/data.py
+--- a/python/mozbuild/mozbuild/frontend/data.py
++++ b/python/mozbuild/mozbuild/frontend/data.py
+@@ -383,26 +383,30 @@ class LinkageMultipleRustLibrariesError(
+ 
+ class Linkable(ContextDerived):
+     """Generic context derived container object for programs and libraries"""
+     __slots__ = (
+         'cxx_link',
+         'lib_defines',
+         'linked_libraries',
+         'linked_system_libs',
++        'no_pgo_sources',
++        'no_pgo',
+         'sources',
+     )
+ 
+     def __init__(self, context):
+         ContextDerived.__init__(self, context)
+         self.cxx_link = False
+         self.linked_libraries = []
+         self.linked_system_libs = []
+         self.lib_defines = Defines(context, {})
+         self.sources = defaultdict(list)
++        self.no_pgo_sources = []
++        self.no_pgo = False
+ 
+     def link_library(self, obj):
+         assert isinstance(obj, BaseLibrary)
+         if obj.KIND != self.KIND:
+             raise LinkageWrongKindError('%s != %s' % (obj.KIND, self.KIND))
+         # Linking multiple Rust libraries into an object would result in
+         # multiple copies of the Rust standard library, as well as linking
+         # errors from duplicate symbols.
+@@ -432,26 +436,33 @@ class Linkable(ContextDerived):
+     def source_files(self):
+         all_sources = []
+         # This is ordered for reproducibility and consistently w/
+         # config/rules.mk
+         for suffix in ('.c', '.S', '.cpp', '.m', '.mm', '.s'):
+             all_sources += self.sources.get(suffix, [])
+         return all_sources
+ 
+-    @property
+-    def objs(self):
++    def _get_objs(self, sources):
+         obj_prefix = ''
+         if self.KIND == 'host':
+             obj_prefix = 'host_'
+ 
+         return [mozpath.join(self.objdir, '%s%s.%s' % (obj_prefix,
+                                                        mozpath.splitext(mozpath.basename(f))[0],
+                                                        self.config.substs.get('OBJ_SUFFIX', '')))
+-                for f in self.source_files()]
++                for f in sources]
++
++    @property
++    def no_pgo_objs(self):
++        return self._get_objs(self.no_pgo_sources)
++
++    @property
++    def objs(self):
++        return self._get_objs(self.source_files())
+ 
+ 
+ class BaseProgram(Linkable):
+     """Context derived container object for programs, which is a unicode
+     string.
+ 
+     This class handles automatically appending a binary suffix to the program
+     name.
+diff --git a/python/mozbuild/mozbuild/frontend/emitter.py b/python/mozbuild/mozbuild/frontend/emitter.py
+--- a/python/mozbuild/mozbuild/frontend/emitter.py
++++ b/python/mozbuild/mozbuild/frontend/emitter.py
+@@ -946,16 +946,20 @@ class TreeMetadataEmitter(LoggingMixin):
+                     ctxt_sources[variable][canonical_suffix] += sorted(srcs)
+                     yield obj
+ 
+         if ctxt_sources:
+             for linkable in linkables:
+                 for target_var in ('SOURCES', 'UNIFIED_SOURCES'):
+                     for suffix, srcs in ctxt_sources[target_var].items():
+                         linkable.sources[suffix] += srcs
++                if no_pgo_sources:
++                    linkable.no_pgo_sources = no_pgo_sources
++                elif no_pgo:
++                    linkable.no_pgo = True
+             for host_linkable in host_linkables:
+                 for suffix, srcs in ctxt_sources['HOST_SOURCES'].items():
+                     host_linkable.sources[suffix] += srcs
+ 
+         for f, flags in all_flags.iteritems():
+             if flags.flags:
+                 ext = mozpath.splitext(f)[1]
+                 yield PerSourceFlag(context, f, flags.flags)

+ 284 - 0
rel-257/ian/patches/1434837-60.patch

@@ -0,0 +1,284 @@
+# HG changeset patch
+# User Masayuki Nakano <masayuki@d-toybox.com>
+# Date 1518097349 -32400
+#      Thu Feb 08 22:42:29 2018 +0900
+# Branch THUNDERBIRD_60_VERBRANCH
+# Node ID a3f82738156799bf9bf3948f54f40a1b0a1fb4f2
+# Parent  a5bded5f95f0782bb92b08dc4d77b81f11dfd5c2
+Bug 1434837 - Make autocomplete and satchel listen to keypress event at the system event group. r=mak (was c0b4ca69376c, backed out in 92515b2d8a74) a=jorgk
+
+The autocomplete module listens to keypress event for both printable keys and
+non-printable keys a lot.  However, we'll stop dispatching keypress event for
+non-printable keys in the default event group of web content.  So, autocomplete
+should listen to keypress events at the system event group.
+
+Note that it's difficult to change keypress event listeners to keydown event
+listeners because if we stop keypress events at preceding keydown event in
+autocomplete or satchel module, some other modules fail to handle keydown or
+keypress event before autocomplete and it's not easy to investigate which
+module's which keypress event listener should be changed to keydown event
+listener.  Therefore, this patch doesn't do it at least for now.
+
+MozReview-Commit-ID: 7e3aklmKrXu
+
+diff --git a/toolkit/components/satchel/nsFormFillController.cpp b/toolkit/components/satchel/nsFormFillController.cpp
+--- a/toolkit/components/satchel/nsFormFillController.cpp
++++ b/toolkit/components/satchel/nsFormFillController.cpp
+@@ -3,16 +3,17 @@
+ /* This Source Code Form is subject to the terms of the Mozilla Public
+  * 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/. */
+ 
+ #include "nsFormFillController.h"
+ 
+ #include "mozilla/ClearOnShutdown.h"
+ #include "mozilla/ErrorResult.h"
++#include "mozilla/EventListenerManager.h"
+ #include "mozilla/dom/Element.h"
+ #include "mozilla/dom/Event.h"  // for nsIDOMEvent::InternalDOMEvent()
+ #include "mozilla/dom/HTMLInputElement.h"
+ #include "mozilla/dom/KeyboardEvent.h"
+ #include "mozilla/dom/KeyboardEventBinding.h"
+ #include "mozilla/dom/PageTransitionEvent.h"
+ #include "mozilla/Logging.h"
+ #include "nsIFormAutoComplete.h"
+@@ -1144,33 +1145,39 @@ void nsFormFillController::AddWindowList
+   }
+ 
+   EventTarget* target = aWindow->GetChromeEventHandler();
+ 
+   if (!target) {
+     return;
+   }
+ 
+-  target->AddEventListener(NS_LITERAL_STRING("focus"), this,
+-                           true, false);
+-  target->AddEventListener(NS_LITERAL_STRING("blur"), this,
+-                           true, false);
+-  target->AddEventListener(NS_LITERAL_STRING("pagehide"), this,
+-                           true, false);
+-  target->AddEventListener(NS_LITERAL_STRING("mousedown"), this,
+-                           true, false);
+-  target->AddEventListener(NS_LITERAL_STRING("input"), this,
+-                           true, false);
+-  target->AddEventListener(NS_LITERAL_STRING("keypress"), this, true, false);
+-  target->AddEventListener(NS_LITERAL_STRING("compositionstart"), this,
+-                           true, false);
+-  target->AddEventListener(NS_LITERAL_STRING("compositionend"), this,
+-                           true, false);
+-  target->AddEventListener(NS_LITERAL_STRING("contextmenu"), this,
+-                           true, false);
++  EventListenerManager* elm = target->GetOrCreateListenerManager();
++  if (NS_WARN_IF(!elm)) {
++    return;
++  }
++
++  elm->AddEventListenerByType(this, NS_LITERAL_STRING("focus"),
++                              TrustedEventsAtCapture());
++  elm->AddEventListenerByType(this, NS_LITERAL_STRING("blur"),
++                              TrustedEventsAtCapture());
++  elm->AddEventListenerByType(this, NS_LITERAL_STRING("pagehide"),
++                              TrustedEventsAtCapture());
++  elm->AddEventListenerByType(this, NS_LITERAL_STRING("mousedown"),
++                              TrustedEventsAtCapture());
++  elm->AddEventListenerByType(this, NS_LITERAL_STRING("input"),
++                              TrustedEventsAtCapture());
++  elm->AddEventListenerByType(this, NS_LITERAL_STRING("keypress"),
++                              TrustedEventsAtSystemGroupCapture());
++  elm->AddEventListenerByType(this, NS_LITERAL_STRING("compositionstart"),
++                              TrustedEventsAtCapture());
++  elm->AddEventListenerByType(this, NS_LITERAL_STRING("compositionend"),
++                              TrustedEventsAtCapture());
++  elm->AddEventListenerByType(this, NS_LITERAL_STRING("contextmenu"),
++                              TrustedEventsAtCapture());
+ 
+   // Note that any additional listeners added should ensure that they ignore
+   // untrusted events, which might be sent by content that's up to no good.
+ }
+ 
+ void nsFormFillController::RemoveWindowListeners(nsPIDOMWindowOuter* aWindow) {
+   MOZ_LOG(sLogger, LogLevel::Debug,
+           ("RemoveWindowListeners for window %p", aWindow));
+@@ -1184,27 +1191,39 @@ void nsFormFillController::RemoveWindowL
+   RemoveForDocument(doc);
+ 
+   EventTarget* target = aWindow->GetChromeEventHandler();
+ 
+   if (!target) {
+     return;
+   }
+ 
+-  target->RemoveEventListener(NS_LITERAL_STRING("focus"), this, true);
+-  target->RemoveEventListener(NS_LITERAL_STRING("blur"), this, true);
+-  target->RemoveEventListener(NS_LITERAL_STRING("pagehide"), this, true);
+-  target->RemoveEventListener(NS_LITERAL_STRING("mousedown"), this, true);
+-  target->RemoveEventListener(NS_LITERAL_STRING("input"), this, true);
+-  target->RemoveEventListener(NS_LITERAL_STRING("keypress"), this, true);
+-  target->RemoveEventListener(NS_LITERAL_STRING("compositionstart"), this,
+-                              true);
+-  target->RemoveEventListener(NS_LITERAL_STRING("compositionend"), this,
+-                              true);
+-  target->RemoveEventListener(NS_LITERAL_STRING("contextmenu"), this, true);
++  EventListenerManager* elm = target->GetOrCreateListenerManager();
++  if (NS_WARN_IF(!elm)) {
++    return;
++  }
++
++  elm->RemoveEventListenerByType(this, NS_LITERAL_STRING("focus"),
++                                 TrustedEventsAtCapture());
++  elm->RemoveEventListenerByType(this, NS_LITERAL_STRING("blur"),
++                                 TrustedEventsAtCapture());
++  elm->RemoveEventListenerByType(this, NS_LITERAL_STRING("pagehide"),
++                                 TrustedEventsAtCapture());
++  elm->RemoveEventListenerByType(this, NS_LITERAL_STRING("mousedown"),
++                                 TrustedEventsAtCapture());
++  elm->RemoveEventListenerByType(this, NS_LITERAL_STRING("input"),
++                                 TrustedEventsAtCapture());
++  elm->RemoveEventListenerByType(this, NS_LITERAL_STRING("keypress"),
++                                 TrustedEventsAtSystemGroupCapture());
++  elm->RemoveEventListenerByType(this, NS_LITERAL_STRING("compositionstart"),
++                                 TrustedEventsAtCapture());
++  elm->RemoveEventListenerByType(this, NS_LITERAL_STRING("compositionend"),
++                                 TrustedEventsAtCapture());
++  elm->RemoveEventListenerByType(this, NS_LITERAL_STRING("contextmenu"),
++                                 TrustedEventsAtCapture());
+ }
+ 
+ void nsFormFillController::StartControllingInput(HTMLInputElement* aInput) {
+   MOZ_LOG(sLogger, LogLevel::Verbose, ("StartControllingInput for %p", aInput));
+   // Make sure we're not still attached to an input
+   StopControllingInput();
+ 
+   if (!mController) {
+diff --git a/toolkit/components/satchel/test/test_popup_enter_event.html b/toolkit/components/satchel/test/test_popup_enter_event.html
+--- a/toolkit/components/satchel/test/test_popup_enter_event.html
++++ b/toolkit/components/satchel/test/test_popup_enter_event.html
+@@ -53,17 +53,17 @@ function handleEnter(evt) {
+ 
+ function popupShownListener(evt) {
+   synthesizeKey("KEY_ArrowDown");
+   synthesizeKey("KEY_Enter"); // select the first entry in the popup
+   synthesizeKey("KEY_Enter"); // try to submit the form with the filled value
+ }
+ 
+ function runTest() {
+-  input.addEventListener("keypress", handleEnter, true);
++  SpecialPowers.addSystemEventListener(input, "keypress", handleEnter, true);
+   form.addEventListener("submit", function submitCallback(evt) {
+     is(input.value, expectedValue, "Check input value in the submit handler");
+     evt.preventDefault();
+ 
+     input.removeEventListener("keypress", handleEnter, true);
+     form.removeEventListener("submit", submitCallback);
+ 
+     SimpleTest.finish();
+diff --git a/toolkit/content/tests/chrome/test_autocomplete_mac_caret.xul b/toolkit/content/tests/chrome/test_autocomplete_mac_caret.xul
+--- a/toolkit/content/tests/chrome/test_autocomplete_mac_caret.xul
++++ b/toolkit/content/tests/chrome/test_autocomplete_mac_caret.xul
+@@ -18,48 +18,51 @@
+ 
+ SimpleTest.waitForExplicitFinish();
+ 
+ function keyCaretTest()
+ {
+   var autocomplete = $("autocomplete");
+ 
+   autocomplete.focus();
+-  checkKeyCaretTest("VK_UP", 0, 0, false, "no value up");
+-  checkKeyCaretTest("VK_DOWN", 0, 0, false, "no value down");
++  checkKeyCaretTest("KEY_ArrowUp", 0, 0, false, "no value up");
++  checkKeyCaretTest("KEY_ArrowDown", 0, 0, false, "no value down");
+ 
+   autocomplete.value = "Sample";
+ 
+   autocomplete.selectionStart = 3;
+   autocomplete.selectionEnd = 3;
+-  checkKeyCaretTest("VK_UP", 0, 0, true, "value up with caret in middle");
+-  checkKeyCaretTest("VK_UP", 0, 0, false, "value up with caret in middle again");
++  checkKeyCaretTest("KEY_ArrowUp", 0, 0, true, "value up with caret in middle");
++  checkKeyCaretTest("KEY_ArrowUp", 0, 0, false, "value up with caret in middle again");
+ 
+   autocomplete.selectionStart = 2;
+   autocomplete.selectionEnd = 2;
+-  checkKeyCaretTest("VK_DOWN", 6, 6, true, "value down with caret in middle");
+-  checkKeyCaretTest("VK_DOWN", 6, 6, false, "value down with caret in middle again");
++  checkKeyCaretTest("KEY_ArrowDown", 6, 6, true, "value down with caret in middle");
++  checkKeyCaretTest("KEY_ArrowDown", 6, 6, false, "value down with caret in middle again");
+ 
+   autocomplete.selectionStart = 1;
+   autocomplete.selectionEnd = 4;
+-  checkKeyCaretTest("VK_UP", 0, 0, true, "value up with selection");
++  checkKeyCaretTest("KEY_ArrowUp", 0, 0, true, "value up with selection");
+ 
+   autocomplete.selectionStart = 1;
+   autocomplete.selectionEnd = 4;
+-  checkKeyCaretTest("VK_DOWN", 6, 6, true, "value down with selection");
++  checkKeyCaretTest("KEY_ArrowDown", 6, 6, true, "value down with selection");
+ 
+   SimpleTest.finish();
+ }
+ 
+ function checkKeyCaretTest(key, expectedStart, expectedEnd, result, testid)
+ {
+   var autocomplete = $("autocomplete");
+-
+-  var event = result ? "keypress" : "!keypress";
+-  synthesizeKeyExpectEvent(key, { }, autocomplete.inputField, event, testid);
++  var keypressFired = false;
++  SpecialPowers.addSystemEventListener(autocomplete.inputField, "keypress", () => {
++    keypressFired = true;
++  }, {once: true});
++  synthesizeKey(key, {});
++  is(keypressFired, result, `${testid} keypress event should${result ? "" : " not"} be fired`);
+   is(autocomplete.selectionStart, expectedStart, testid + " selectionStart");
+   is(autocomplete.selectionEnd, expectedEnd, testid + " selectionEnd");
+ }
+ 
+ ]]>
+ </script>
+ 
+ <body xmlns="http://www.w3.org/1999/xhtml">
+diff --git a/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html b/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html
+--- a/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html
++++ b/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html
+@@ -74,17 +74,17 @@ https://bugzilla.mozilla.org/show_bug.cg
+         if (evt.keyCode != KeyEvent.DOM_VK_RETURN) {
+           return;
+         }
+         info("RETURN received for phase: " + evt.eventPhase);
+         is(evt.target.value, "New value option", "Check that the correct autocomplete entry was used");
+         resolve();
+       }
+ 
+-      field.addEventListener("keypress", handleEnter, true);
++      SpecialPowers.addSystemEventListener(field, "keypress", handleEnter, true);
+     });
+ 
+     field.focus();
+ 
+     await promiseFieldFocus;
+ 
+     await promisePopupShown;
+ 
+diff --git a/toolkit/content/widgets/autocomplete.xml b/toolkit/content/widgets/autocomplete.xml
+--- a/toolkit/content/widgets/autocomplete.xml
++++ b/toolkit/content/widgets/autocomplete.xml
+@@ -608,17 +608,17 @@
+       </method>
+     </implementation>
+ 
+     <handlers>
+       <handler event="input"><![CDATA[
+         this.onInput(event);
+       ]]></handler>
+ 
+-      <handler event="keypress" phase="capturing"
++      <handler event="keypress" phase="capturing" group="system"
+                action="return this.onKeyPress(event);"/>
+ 
+       <handler event="compositionstart" phase="capturing"
+                action="if (this.mController.input == this) this.mController.handleStartComposition();"/>
+ 
+       <handler event="compositionend" phase="capturing"
+                action="if (this.mController.input == this) this.mController.handleEndComposition();"/>
+ 

+ 93 - 0
rel-257/ian/patches/1434844-61a1.patch

@@ -0,0 +1,93 @@
+# HG changeset patch
+# User Peter Dodds <peter.sa.d@hotmail.com>
+# Date 1520222191 18000
+# Node ID 0bce62afe395b03d7e6916801cf6a0788e33127e
+# Parent  43ea226dab0fad4f3534f9c32c7bc4b93f987fb1
+Bug 1434844 - Download timeLeft is now formatted according to locale, and tests updated to accomodate thousands separator; r=gandalf,rs=paolo
+
+MozReview-Commit-ID: LZjna3vDSDB
+
+diff --git a/toolkit/mozapps/downloads/DownloadUtils.jsm b/toolkit/mozapps/downloads/DownloadUtils.jsm
+--- a/toolkit/mozapps/downloads/DownloadUtils.jsm
++++ b/toolkit/mozapps/downloads/DownloadUtils.jsm
+@@ -246,16 +246,17 @@ var DownloadUtils = {
+    *
+    * @param aSeconds
+    *        Current estimate on number of seconds left for the download
+    * @param [optional] aLastSec
+    *        Last time remaining in seconds or Infinity for unknown
+    * @return A pair: [time left text, new value of "last seconds"]
+    */
+   getTimeLeft: function DU_getTimeLeft(aSeconds, aLastSec) {
++    let nf = new Services.intl.NumberFormat();
+     if (aLastSec == null)
+       aLastSec = Infinity;
+ 
+     if (aSeconds < 0)
+       return [gBundle.GetStringFromName(gStr.timeUnknown), aLastSec];
+ 
+     // Try to find a cached lastSec for the given second
+     aLastSec = gCachedLast.reduce((aResult, aItem) =>
+@@ -288,19 +289,19 @@ var DownloadUtils = {
+       // Be friendly in the last few seconds
+       timeLeft = gBundle.GetStringFromName(gStr.timeFewSeconds);
+     } else {
+       // Convert the seconds into its two largest units to display
+       let [time1, unit1, time2, unit2] =
+         DownloadUtils.convertTimeUnits(aSeconds);
+ 
+       let pair1 =
+-        gBundle.formatStringFromName(gStr.timePair, [time1, unit1], 2);
++        gBundle.formatStringFromName(gStr.timePair, [nf.format(time1), unit1], 2);
+       let pair2 =
+-        gBundle.formatStringFromName(gStr.timePair, [time2, unit2], 2);
++        gBundle.formatStringFromName(gStr.timePair, [nf.format(time2), unit2], 2);
+ 
+       // Only show minutes for under 1 hour unless there's a few minutes left;
+       // or the second pair is 0.
+       if ((aSeconds < 3600 && time1 >= 4) || time2 == 0) {
+         timeLeft = gBundle.formatStringFromName(gStr.timeLeftSingle,
+                                                 [pair1], 1);
+       } else {
+         // We've got 2 pairs of times to display
+diff --git a/toolkit/mozapps/downloads/tests/unit/test_DownloadUtils.js b/toolkit/mozapps/downloads/tests/unit/test_DownloadUtils.js
+--- a/toolkit/mozapps/downloads/tests/unit/test_DownloadUtils.js
++++ b/toolkit/mozapps/downloads/tests/unit/test_DownloadUtils.js
+@@ -150,17 +150,17 @@ function run_test() {
+   testStatus(statusFunc, 1, 9, 2, ["1h 35m left -- 100 bytes of 12.9 MB (2.3 KB/sec)", 5756.133]);
+   testStatus(statusFunc, 2, 9, 6, ["2h 31m left -- 2.3 KB of 12.9 MB (1.4 KB/sec)", 9108.051]);
+   testStatus(statusFunc, 2, 4, 1, ["2h 43m left -- 2.3 of 962 KB (100 bytes/sec)", 9823.410]);
+   testStatus(statusFunc, 6, 4, 7, ["4h 42m left -- 1.4 of 961 KB (58 bytes/sec)", 16936.914]);
+ 
+   testStatus(statusFunc, 6, 9, 1, ["1d 13h left -- 1.4 KB of 12.9 MB (100 bytes/sec)", 134981.320]);
+   testStatus(statusFunc, 3, 8, 3, ["2d 1h left -- 54.3 KB of 9.2 GB (54.3 KB/sec)", 178596.872]);
+   testStatus(statusFunc, 1, 8, 6, ["77d 11h left -- 100 bytes of 9.2 GB (1.4 KB/sec)", 6694972.470]);
+-  testStatus(statusFunc, 6, 8, 7, ["1979d 22h left -- 1.4 KB of 9.2 GB (58 bytes/sec)", 171068089.672]);
++  testStatus(statusFunc, 6, 8, 7, ["1,979d 22h left -- 1.4 KB of 9.2 GB (58 bytes/sec)", 171068089.672]);
+ 
+   testStatus(statusFunc, 0, 0, 5, ["Unknown time left -- 0 of 0 bytes (22.1 MB/sec)", Infinity]);
+   testStatus(statusFunc, 0, 6, 0, ["Unknown time left -- 0 bytes of 1.4 KB (0 bytes/sec)", Infinity]);
+   testStatus(statusFunc, 6, 6, 0, ["Unknown time left -- 1.4 of 2.9 KB (0 bytes/sec)", Infinity]);
+   testStatus(statusFunc, 8, 5, 0, ["Unknown time left -- 9.2 of 9.3 GB (0 bytes/sec)", Infinity]);
+ 
+   // With rate equal to Infinity
+   testStatus(statusFunc, 0, 0, 10, ["Unknown time left -- 0 of 0 bytes (Really fast)", Infinity]);
+@@ -187,17 +187,17 @@ function run_test() {
+   testStatus(statusFunc, 1, 9, 2, ["1h 35m left -- 100 bytes of 12.9 MB", 5756.133]);
+   testStatus(statusFunc, 2, 9, 6, ["2h 31m left -- 2.3 KB of 12.9 MB", 9108.051]);
+   testStatus(statusFunc, 2, 4, 1, ["2h 43m left -- 2.3 of 962 KB", 9823.410]);
+   testStatus(statusFunc, 6, 4, 7, ["4h 42m left -- 1.4 of 961 KB", 16936.914]);
+ 
+   testStatus(statusFunc, 6, 9, 1, ["1d 13h left -- 1.4 KB of 12.9 MB", 134981.320]);
+   testStatus(statusFunc, 3, 8, 3, ["2d 1h left -- 54.3 KB of 9.2 GB", 178596.872]);
+   testStatus(statusFunc, 1, 8, 6, ["77d 11h left -- 100 bytes of 9.2 GB", 6694972.470]);
+-  testStatus(statusFunc, 6, 8, 7, ["1979d 22h left -- 1.4 KB of 9.2 GB", 171068089.672]);
++  testStatus(statusFunc, 6, 8, 7, ["1,979d 22h left -- 1.4 KB of 9.2 GB", 171068089.672]);
+ 
+   testStatus(statusFunc, 0, 0, 5, ["Unknown time left -- 0 of 0 bytes", Infinity]);
+   testStatus(statusFunc, 0, 6, 0, ["Unknown time left -- 0 bytes of 1.4 KB", Infinity]);
+   testStatus(statusFunc, 6, 6, 0, ["Unknown time left -- 1.4 of 2.9 KB", Infinity]);
+   testStatus(statusFunc, 8, 5, 0, ["Unknown time left -- 9.2 of 9.3 GB", Infinity]);
+ 
+   testURI("http://www.mozilla.org/", "mozilla.org", "www.mozilla.org");
+   testURI("http://www.city.mikasa.hokkaido.jp/", "city.mikasa.hokkaido.jp", "www.city.mikasa.hokkaido.jp");

+ 44 - 0
rel-257/ian/patches/1437128-61a1.patch

@@ -0,0 +1,44 @@
+# HG changeset patch
+# User David Keeler <dkeeler@mozilla.com>
+# Date 1518207075 28800
+# Node ID faa9d965f89eca4a2fe8727149e6fa8d7a699604
+# Parent  b02b1b474565f8e2793e932be8abcf45d2405ac9
+bug 1437128 - enforce that NSS_Shutdown succeeds on debug, non-android platforms (to prevent NSS resource leaks) r=erahm
+
+diff --git a/xpcom/build/XPCOMInit.cpp b/xpcom/build/XPCOMInit.cpp
+--- a/xpcom/build/XPCOMInit.cpp
++++ b/xpcom/build/XPCOMInit.cpp
+@@ -985,26 +985,24 @@ nsresult ShutdownXPCOM(nsIServiceManager
+     sInitializedJS = false;
+   }
+ 
+   // After all threads have been joined and the component manager has been shut
+   // down, any remaining objects that could be holding NSS resources (should)
+   // have been released, so we can safely shut down NSS.
+   if (NSS_IsInitialized()) {
+     SSL_ClearSessionCache();
+-    // It would be nice to enforce that this succeeds, at least on debug builds.
+-    // This would alert us to NSS resource leaks. Unfortunately there are some
+-    // architectural roadblocks in the way. Some tests (e.g. pkix gtests) need
+-    // to be re-worked to release their NSS resources when they're done. In the
+-    // meantime, just emit a warning. Chasing down these leaks is tracked in
+-    // bug 1230312.
+     if (NSS_Shutdown() != SECSuccess) {
+-      NS_WARNING(
+-          "NSS_Shutdown failed - some NSS resources are still in use "
+-          "(see bugs 1417680 and 1230312)");
++      // If you're seeing this crash and/or warning, some NSS resources are
++      // still in use (see bugs 1417680 and 1230312).
++#if defined(DEBUG) && !defined(ANDROID)
++      MOZ_CRASH("NSS_Shutdown failed");
++#else
++      NS_WARNING("NSS_Shutdown failed");
++#endif
+     }
+   }
+ 
+   // Release our own singletons
+   // Do this _after_ shutting down the component manager, because the
+   // JS component loader will use XPConnect to call nsIModule::canUnload,
+   // and that will spin up the InterfaceInfoManager again -- bad mojo
+   XPTInterfaceInfoManager::FreeInterfaceInfoManager();

+ 65 - 0
rel-257/ian/patches/1437661-67a1.patch

@@ -0,0 +1,65 @@
+# HG changeset patch
+# User Valentin Gosu <valentin.gosu@gmail.com>
+# Date 1551979415 0
+# Node ID a451c5f914c4c1fa9e20baaa569a3c54fe04d7b5
+# Parent  868c8eb48eeb9dccf062c4430c91cfd3d7cf6916
+Bug 1437661 - Use fallible AppendUTF16toUTF8 to avoid OOM crash r=JuniorHsu
+
+Differential Revision: https://phabricator.services.mozilla.com/D22412
+
+diff --git a/netwerk/base/nsNetUtil.cpp b/netwerk/base/nsNetUtil.cpp
+--- a/netwerk/base/nsNetUtil.cpp
++++ b/netwerk/base/nsNetUtil.cpp
+@@ -1616,33 +1616,39 @@ nsresult NS_NewURI(
+         *ioService /* = nullptr */)  // pass in nsIIOService to optimize callers
+ {
+   nsAutoCString charset;
+   encoding->Name(charset);
+   return NS_NewURI(result, spec, charset.get(), baseURI, ioService);
+ }
+ 
+ nsresult NS_NewURI(
+-    nsIURI **result, const nsAString &spec, const char *charset /* = nullptr */,
++    nsIURI **result, const nsAString &aSpec,
++    const char *charset /* = nullptr */, nsIURI *baseURI /* = nullptr */,
++    nsIIOService
++        *ioService /* = nullptr */)  // pass in nsIIOService to optimize callers
++{
++  nsAutoCString spec;
++  if (!AppendUTF16toUTF8(aSpec, spec, mozilla::fallible)) {
++    return NS_ERROR_OUT_OF_MEMORY;
++  }
++  return NS_NewURI(result, spec, charset, baseURI, ioService);
++}
++
++nsresult NS_NewURI(
++    nsIURI **result, const nsAString &aSpec, NotNull<const Encoding *> encoding,
+     nsIURI *baseURI /* = nullptr */,
+     nsIIOService
+         *ioService /* = nullptr */)  // pass in nsIIOService to optimize callers
+ {
+-  return NS_NewURI(result, NS_ConvertUTF16toUTF8(spec), charset, baseURI,
+-                   ioService);
+-}
+-
+-nsresult NS_NewURI(
+-    nsIURI **result, const nsAString &spec, NotNull<const Encoding *> encoding,
+-    nsIURI *baseURI /* = nullptr */,
+-    nsIIOService
+-        *ioService /* = nullptr */)  // pass in nsIIOService to optimize callers
+-{
+-  return NS_NewURI(result, NS_ConvertUTF16toUTF8(spec), encoding, baseURI,
+-                   ioService);
++  nsAutoCString spec;
++  if (!AppendUTF16toUTF8(aSpec, spec, mozilla::fallible)) {
++    return NS_ERROR_OUT_OF_MEMORY;
++  }
++  return NS_NewURI(result, spec, encoding, baseURI, ioService);
+ }
+ 
+ nsresult NS_NewURI(
+     nsIURI **result, const char *spec, nsIURI *baseURI /* = nullptr */,
+     nsIIOService
+         *ioService /* = nullptr */)  // pass in nsIIOService to optimize callers
+ {
+   return NS_NewURI(result, nsDependentCString(spec), nullptr, baseURI,

+ 33 - 0
rel-257/ian/patches/1439323-BACKOUT-1429125-60.patch

@@ -0,0 +1,33 @@
+# HG changeset patch
+# User Jorg K <jorgk@jorgk.com>
+# Date 1524775365 -7200
+#      Thu Apr 26 22:42:45 2018 +0200
+# Branch THUNDERBIRD_60_VERBRANCH
+# Node ID a86e665e8e8e7a4ece2d6cbc6f24c45c99ccf0db
+# Parent  1bc8bd79ccb771389d73c89743422b8884ba5acb
+Bug 1439323 - Backed out bug 1429125 (changeset 2e705f777acd) to build Thunderbird 60. a=jorgk
+
+diff --git a/layout/base/nsCSSFrameConstructor.cpp b/layout/base/nsCSSFrameConstructor.cpp
+--- a/layout/base/nsCSSFrameConstructor.cpp
++++ b/layout/base/nsCSSFrameConstructor.cpp
+@@ -6869,18 +6869,18 @@ void nsCSSFrameConstructor::CheckBitsFor
+ // that, too.
+ //
+ // NOTE(emilio): The IsXULElement check is pretty unfortunate, but there's tons
+ // of browser chrome code that rely on XBL bindings getting synchronously loaded
+ // as soon as the elements get inserted in the DOM.
+ bool nsCSSFrameConstructor::MaybeConstructLazily(Operation aOperation,
+                                                  nsIContent* aContainer,
+                                                  nsIContent* aChild) {
+-  if (!aContainer || aContainer->IsInNativeAnonymousSubtree() ||
+-      aContainer->IsXULElement()) {
++  if (mPresShell->GetPresContext()->IsChrome() || !aContainer ||
++      aContainer->IsInNativeAnonymousSubtree() || aContainer->IsXULElement()) {
+     return false;
+   }
+ 
+   if (aOperation == CONTENTINSERT) {
+     if (aChild->IsRootOfAnonymousSubtree() || aChild->IsXULElement()) {
+       return false;
+     }
+   } else {  // CONTENTAPPEND

+ 94 - 0
rel-257/ian/patches/1439450-64a1.patch

@@ -0,0 +1,94 @@
+# HG changeset patch
+# User Dimi Lee <dlee@mozilla.com>
+# Date 1539686161 0
+# Node ID 37d138b1e58b9c45ee3baef530bb133597b14eb3
+# Parent  69de195e182f2774b0d8d393c852e7cf8d8df8ff
+Bug 1439450 - Ignore has_first_value() check in ProtocolParser. r=francois
+
+Sometimes the protocol buffer data (RiceEncodingData) sent by Google's Safe Browsing server has the following properties:
+
+1. |has_first_value| is false
+2. |num_entries| > 0
+
+In this case, we can still parse the data and apply partial update correctly by assuming that the first value is equal to 0.
+
+Differential Revision: https://phabricator.services.mozilla.com/D6393
+
+diff --git a/toolkit/components/url-classifier/ProtocolParser.cpp b/toolkit/components/url-classifier/ProtocolParser.cpp
+--- a/toolkit/components/url-classifier/ProtocolParser.cpp
++++ b/toolkit/components/url-classifier/ProtocolParser.cpp
+@@ -921,28 +921,29 @@ nsresult ProtocolParserProtobuf::Process
+     return rv;
+   }
+ 
+   return NS_OK;
+ }
+ 
+ static nsresult DoRiceDeltaDecode(const RiceDeltaEncoding& aEncoding,
+                                   nsTArray<uint32_t>& aDecoded) {
+-  if (!aEncoding.has_first_value()) {
+-    PARSER_LOG(("The encoding info is incomplete."));
+-    return NS_ERROR_UC_PARSER_MISSING_PARAM;
+-  }
+   if (aEncoding.num_entries() > 0 &&
+       (!aEncoding.has_rice_parameter() || !aEncoding.has_encoded_data())) {
+     PARSER_LOG(("Rice parameter or encoded data is missing."));
+     return NS_ERROR_UC_PARSER_MISSING_PARAM;
++  } else if (aEncoding.num_entries() == 0 && !aEncoding.has_first_value()) {
++    PARSER_LOG(("Missing first_value for an single-integer Rice encoding."));
++    return NS_ERROR_UC_PARSER_MISSING_VALUE;
+   }
+ 
++  auto first_value = aEncoding.has_first_value() ? aEncoding.first_value() : 0;
++
+   PARSER_LOG(("* Encoding info:"));
+-  PARSER_LOG(("  - First value: %" PRId64, aEncoding.first_value()));
++  PARSER_LOG(("  - First value: %" PRId64, first_value));
+   PARSER_LOG(("  - Num of entries: %d", aEncoding.num_entries()));
+   PARSER_LOG(("  - Rice parameter: %d", aEncoding.rice_parameter()));
+ 
+   // Set up the input buffer. Note that the bits should be read
+   // from LSB to MSB so that we in-place reverse the bits before
+   // feeding to the decoder.
+   auto encoded =
+       const_cast<RiceDeltaEncoding&>(aEncoding).mutable_encoded_data();
+@@ -953,17 +954,17 @@ static nsresult DoRiceDeltaDecode(const 
+   if (!aDecoded.SetLength(aEncoding.num_entries() + 1, mozilla::fallible)) {
+     NS_WARNING("Not enough memory to decode the RiceDelta input.");
+     return NS_ERROR_OUT_OF_MEMORY;
+   }
+ 
+   // Decode!
+   bool rv = decoder.Decode(
+       aEncoding.rice_parameter(),
+-      aEncoding.first_value(),  // first value.
++      first_value,
+       aEncoding.num_entries(),  // # of entries (first value not included).
+       &aDecoded[0]);
+ 
+   NS_ENSURE_TRUE(rv, NS_ERROR_UC_PARSER_DECODE_FAILURE);
+ 
+   return NS_OK;
+ }
+ 
+diff --git a/xpcom/base/ErrorList.py b/xpcom/base/ErrorList.py
+--- a/xpcom/base/ErrorList.py
++++ b/xpcom/base/ErrorList.py
+@@ -1104,16 +1104,17 @@ with modules["URL_CLASSIFIER"]:
+     errors["NS_ERROR_UC_UPDATE_TABLE_NOT_FOUND"] = FAILURE(8)
+     errors["NS_ERROR_UC_UPDATE_BUILD_PREFIX_FAILURE"] = FAILURE(9)
+     errors["NS_ERROR_UC_UPDATE_FAIL_TO_WRITE_DISK"] = FAILURE(10)
+ 
+     # Specific errors while parsing pver2/pver4 responses
+     errors["NS_ERROR_UC_PARSER_MISSING_PARAM"] = FAILURE(12)
+     errors["NS_ERROR_UC_PARSER_DECODE_FAILURE"] = FAILURE(13)
+     errors["NS_ERROR_UC_PARSER_UNKNOWN_THREAT"] = FAILURE(14)
++    errors["NS_ERROR_UC_PARSER_MISSING_VALUE"] = FAILURE(15)
+ 
+ 
+ # =======================================================================
+ # 43: NS_ERROR_MODULE_ERRORRESULT
+ # =======================================================================
+ with modules["ERRORRESULT"]:
+     # Represents a JS Value being thrown as an exception.
+     errors["NS_ERROR_INTERNAL_ERRORRESULT_JS_EXCEPTION"] = FAILURE(1)

+ 339 - 0
rel-257/ian/patches/1443706-61a1.patch

@@ -0,0 +1,339 @@
+# HG changeset patch
+# User Nicholas Nethercote <nnethercote@mozilla.com>
+# Date 1520465234 -39600
+# Node ID 545fb6e48c79d2704b5e5506a667b72d97a3d949
+# Parent  098988e8fe62d9266542e24e618c1cd3b2d94660
+Bug 1443706 - Introduce ConstExprHashString(const char16_t*). r=jwalden
+
+This is a `constexpr` alternative to HashString(const char16_t*). We can't make
+HashString(const char16_t*) itself `constexpr` because HashUntilZero(const T*)
+isn't in a form that older compilers (like GCC 4.9) allow to be made
+`constexpr`. (The trick to satisfying those compilers is to use recursion
+instead of iteration, to get the function into a single `return` statement.)
+
+This requires making a bunch of other functions `constexpr` as well. It also
+requires adding MOZ_{PUSH,POP}_DISABLE_INTEGRAL_CONSTANT_OVERFLOW_WARNING
+macros to avoid some MSVC weirdness.
+
+The introduction of RotateLeft5() partly undoes one of the patches from bug
+1443342, but that's unavoidable.
+
+This change will help with static allocation of static atoms (bug 1411469).
+
+MozReview-Commit-ID: 7r3PnrQXb29
+
+diff --git a/mfbt/HashFunctions.h b/mfbt/HashFunctions.h
+--- a/mfbt/HashFunctions.h
++++ b/mfbt/HashFunctions.h
+@@ -60,17 +60,22 @@ namespace mozilla {
+ 
+ /**
+  * The golden ratio as a 32-bit fixed-point value.
+  */
+ static const uint32_t kGoldenRatioU32 = 0x9E3779B9U;
+ 
+ namespace detail {
+ 
+-inline uint32_t AddU32ToHash(uint32_t aHash, uint32_t aValue) {
++MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
++constexpr uint32_t RotateLeft5(uint32_t aValue) {
++  return (aValue << 5) | (aValue >> 27);
++}
++
++constexpr uint32_t AddU32ToHash(uint32_t aHash, uint32_t aValue) {
+   /*
+    * This is the meat of all our hash routines.  This hash function is not
+    * particularly sophisticated, but it seems to work well for our mostly
+    * plain-text inputs.  Implementation notes follow.
+    *
+    * Our use of the golden ratio here is arbitrary; we could pick almost any
+    * number which:
+    *
+@@ -82,17 +87,17 @@ inline uint32_t AddU32ToHash(uint32_t aH
+    *
+    * The rotation length of 5 is also arbitrary, although an odd number is again
+    * preferable so our hash explores the whole universe of possible rotations.
+    *
+    * Finally, we multiply by the golden ratio *after* xor'ing, not before.
+    * Otherwise, if |aHash| is 0 (as it often is for the beginning of a
+    * message), the expression
+    *
+-   *   mozilla::WrappingMultiply(kGoldenRatioU32, RotateBitsLeft(aHash, 5))
++   *   mozilla::WrappingMultiply(kGoldenRatioU32, RotateLeft5(aHash))
+    *   |xor|
+    *   aValue
+    *
+    * evaluates to |aValue|.
+    *
+    * (Number-theoretic aside: Because any odd number |m| is relatively prime to
+    * our modulus (2**32), the list
+    *
+@@ -103,24 +108,24 @@ inline uint32_t AddU32ToHash(uint32_t aH
+    *
+    * It's also nice if |m| has large-ish order mod 2**32 -- that is, if the
+    * smallest k such that m**k == 1 (mod 2**32) is large -- so we can safely
+    * multiply our hash value by |m| a few times without negating the
+    * multiplicative effect.  Our golden ratio constant has order 2**29, which is
+    * more than enough for our purposes.)
+    */
+   return mozilla::WrappingMultiply(kGoldenRatioU32,
+-                                   RotateLeft(aHash, 5) ^ aValue);
++                                   RotateLeft5(aHash) ^ aValue);
+ }
+ 
+ /**
+  * AddUintptrToHash takes sizeof(uintptr_t) as a template parameter.
+  */
+ template <size_t PtrSize>
+-inline uint32_t AddUintptrToHash(uint32_t aHash, uintptr_t aValue) {
++constexpr uint32_t AddUintptrToHash(uint32_t aHash, uintptr_t aValue) {
+   return AddU32ToHash(aHash, static_cast<uint32_t>(aValue));
+ }
+ 
+ template <>
+ inline uint32_t AddUintptrToHash<8>(uint32_t aHash, uintptr_t aValue) {
+   uint32_t v1 = static_cast<uint32_t>(aValue);
+   uint32_t v2 = static_cast<uint32_t>(static_cast<uint64_t>(aValue) >> 32);
+   return AddU32ToHash(AddU32ToHash(aHash, v1), v2);
+@@ -132,17 +137,17 @@ inline uint32_t AddUintptrToHash<8>(uint
+  * AddToHash takes a hash and some values and returns a new hash based on the
+  * inputs.
+  *
+  * Currently, we support hashing uint32_t's, values which we can implicitly
+  * convert to uint32_t, data pointers, and function pointers.
+  */
+ template <typename T, bool TypeIsNotIntegral = !mozilla::IsIntegral<T>::value,
+           typename U = typename mozilla::EnableIf<TypeIsNotIntegral>::Type>
+-MOZ_MUST_USE inline uint32_t AddToHash(uint32_t aHash, T aA) {
++MOZ_MUST_USE constexpr uint32_t AddToHash(uint32_t aHash, T aA) {
+   /*
+    * Try to convert |A| to uint32_t implicitly.  If this works, great.  If not,
+    * we'll error out.
+    */
+   return detail::AddU32ToHash(aHash, aA);
+ }
+ 
+ template <typename A>
+@@ -190,16 +195,27 @@ template <typename T>
+ uint32_t HashUntilZero(const T* aStr) {
+   uint32_t hash = 0;
+   for (T c; (c = *aStr); aStr++) {
+     hash = AddToHash(hash, c);
+   }
+   return hash;
+ }
+ 
++// This is a `constexpr` alternative to HashUntilZero(const T*). It should
++// only be used for compile-time computation because it uses recursion.
++// XXX: once support for GCC 4.9 is dropped, this function should be removed
++// and HashUntilZero(const T*) should be made `constexpr`.
++template <typename T>
++constexpr uint32_t ConstExprHashUntilZero(const T* aStr, uint32_t aHash) {
++  return !*aStr
++       ? aHash
++       : ConstExprHashUntilZero(aStr + 1, AddToHash(aHash, *aStr));
++}
++
+ template <typename T>
+ uint32_t HashKnownLength(const T* aStr, size_t aLength) {
+   uint32_t hash = 0;
+   for (size_t i = 0; i < aLength; i++) {
+     hash = AddToHash(hash, aStr[i]);
+   }
+   return hash;
+ }
+@@ -225,16 +241,29 @@ MOZ_MUST_USE
+ inline uint32_t HashString(const unsigned char* aStr, size_t aLength) {
+   return detail::HashKnownLength(aStr, aLength);
+ }
+ 
+ MOZ_MUST_USE inline uint32_t HashString(const char16_t* aStr) {
+   return detail::HashUntilZero(aStr);
+ }
+ 
++// This is a `constexpr` alternative to HashString(const char16_t*). It should
++// only be used for compile-time computation because it uses recursion.
++//
++// You may need to use the
++// MOZ_{PUSH,POP}_DISABLE_INTEGRAL_CONSTANT_OVERFLOW_WARNING macros if you use
++// this function. See the comment on those macros' definitions for more detail.
++//
++// XXX: once support for GCC 4.9 is dropped, this function should be removed
++// and HashString(const char16_t*) should be made `constexpr`.
++MOZ_MUST_USE constexpr uint32_t ConstExprHashString(const char16_t* aStr) {
++  return detail::ConstExprHashUntilZero(aStr, 0);
++}
++
+ MOZ_MUST_USE inline uint32_t HashString(const char16_t* aStr, size_t aLength) {
+   return detail::HashKnownLength(aStr, aLength);
+ }
+ 
+ /*
+  * On Windows, wchar_t is not the same as char16_t, even though it's
+  * the same width!
+  */
+diff --git a/mfbt/WrappingOperations.h b/mfbt/WrappingOperations.h
+--- a/mfbt/WrappingOperations.h
++++ b/mfbt/WrappingOperations.h
+@@ -88,51 +88,38 @@ struct WrapToSignedHelper {
+ /**
+  * Convert an unsigned value to signed, if necessary wrapping around.
+  *
+  * This is the behavior normal C++ casting will perform in most implementations
+  * these days -- but this function makes explicit that such conversion is
+  * happening.
+  */
+ template <typename UnsignedType>
+-inline constexpr typename detail::WrapToSignedHelper<UnsignedType>::SignedType
++constexpr typename detail::WrapToSignedHelper<UnsignedType>::SignedType
+ WrapToSigned(UnsignedType aValue) {
+   return detail::WrapToSignedHelper<UnsignedType>::compute(aValue);
+ }
+ 
+-// The |mozilla::Wrapping*| functions aren't constexpr because MSVC warns about
+-// well-defined unsigned integer overflows that may occur within the constexpr
+-// math.  If/when MSVC fix this bug, we should make them all constexpr.
+-//
+-//   https://msdn.microsoft.com/en-us/library/4kze989h.aspx (C4307)
+-//   https://developercommunity.visualstudio.com/content/problem/211134/unsigned-integer-overflows-in-constexpr-functionsa.html (bug report)
+-//
+-// For now there's no practical, readable way to avoid such overflows in pure
+-// C++.  And we can't add narrow #pragmas where overflow can occur to disable
+-// the warnings, because constexpr apparently causes the warning to be emitted
+-// at the outermost call *sites* (so every user of |mozilla::Wrapping*| would
+-// have to add them).
+-
+ namespace detail {
+ 
+ template <typename T>
+-inline constexpr T ToResult(typename MakeUnsigned<T>::Type aUnsigned) {
++constexpr T ToResult(typename MakeUnsigned<T>::Type aUnsigned) {
+   // We could *always* return WrapToSigned and rely on unsigned conversion to
+   // undo the wrapping when |T| is unsigned, but this seems clearer.
+   return IsSigned<T>::value ? WrapToSigned(aUnsigned) : aUnsigned;
+ }
+ 
+ template <typename T>
+ struct WrappingAddHelper {
+ private:
+   using UnsignedT = typename MakeUnsigned<T>::Type;
+ 
+ public:
+   MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
+-  static T compute(T aX, T aY) {
++  static constexpr T compute(T aX, T aY) {
+     return ToResult<T>(static_cast<UnsignedT>(aX) + static_cast<UnsignedT>(aY));
+   }
+ };
+ 
+ } // namespace detail
+ 
+ /**
+  * Add two integers of the same type and return the result converted to that
+@@ -154,30 +141,30 @@ public:
+  *   WrappingAdd(int32_t(-42), int32_t(-17)) is -59 ((8589934533 mod 2**32) - 2**32).
+  *
+  * There's no equivalent to this operation in C++, as C++ signed addition that
+  * overflows has undefined behavior.  But it's how such addition *tends* to
+  * behave with most compilers, unless an optimization or similar -- quite
+  * permissibly -- triggers different behavior.
+  */
+ template <typename T>
+-inline T WrappingAdd(T aX, T aY) {
++constexpr T WrappingAdd(T aX, T aY) {
+   return detail::WrappingAddHelper<T>::compute(aX, aY);
+ }
+ 
+ namespace detail {
+ 
+ template <typename T>
+ struct WrappingSubtractHelper {
+ private:
+   using UnsignedT = typename MakeUnsigned<T>::Type;
+ 
+ public:
+   MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
+-  static T compute(T aX, T aY) {
++  static constexpr T compute(T aX, T aY) {
+     return ToResult<T>(static_cast<UnsignedT>(aX) - static_cast<UnsignedT>(aY));
+   }
+ };
+ 
+ } // namespace detail
+ 
+ /**
+  * Subtract two integers of the same type and return the result converted to
+@@ -200,30 +187,30 @@ public:
+  *   WrappingSubtract(int32_t(-17), int32_t(-42)) is 25 (25 mod 2**32).
+  *
+  * There's no equivalent to this operation in C++, as C++ signed subtraction
+  * that overflows has undefined behavior.  But it's how such subtraction *tends*
+  * to behave with most compilers, unless an optimization or similar -- quite
+  * permissibly -- triggers different behavior.
+  */
+ template <typename T>
+-inline T WrappingSubtract(T aX, T aY) {
++constexpr T WrappingSubtract(T aX, T aY) {
+   return detail::WrappingSubtractHelper<T>::compute(aX, aY);
+ }
+ 
+ namespace detail {
+ 
+ template <typename T>
+ struct WrappingMultiplyHelper {
+  private:
+   using UnsignedT = typename MakeUnsigned<T>::Type;
+ 
+  public:
+   MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
+-  static T compute(T aX, T aY) {
++  static constexpr T compute(T aX, T aY) {
+     // Begin with |1U| to ensure the overall operation chain is never promoted
+     // to signed integer operations that might have *signed* integer overflow.
+     return ToResult<T>(static_cast<UnsignedT>(1U *
+                                               static_cast<UnsignedT>(aX) *
+                                               static_cast<UnsignedT>(aY)));
+   }
+ };
+ 
+@@ -259,15 +246,39 @@ struct WrappingMultiplyHelper {
+  *   WrappingMultiply(int8_t(16), int8_t(255)) is -16 ((4080 mod 2**8) - 2**8).
+  *
+  * There's no equivalent to this operation in C++, as C++ signed
+  * multiplication that overflows has undefined behavior.  But it's how such
+  * multiplication *tends* to behave with most compilers, unless an optimization
+  * or similar -- quite permissibly -- triggers different behavior.
+  */
+ template <typename T>
+-inline T WrappingMultiply(T aX, T aY) {
++constexpr T WrappingMultiply(T aX, T aY) {
+   return detail::WrappingMultiplyHelper<T>::compute(aX, aY);
+ }
+ 
++// The |mozilla::Wrapping*| functions are constexpr. Unfortunately, MSVC warns
++// about well-defined unsigned integer overflows that may occur within the
++// constexpr math.
++//
++//   https://msdn.microsoft.com/en-us/library/4kze989h.aspx (C4307)
++//   https://developercommunity.visualstudio.com/content/problem/211134/unsigned-integer-overflows-in-constexpr-functionsa.html (bug report)
++//
++// So we need a way to suppress these warnings. Unfortunately, the warnings are
++// issued at the very top of the `constexpr` chain, which is often some
++// distance from the triggering Wrapping*() operation. So we can't suppress
++// them within this file. Instead, callers have to do it with these macros.
++//
++// If/when MSVC fix this bug, we should remove these macros.
++#ifdef _MSC_VER
++#define MOZ_PUSH_DISABLE_INTEGRAL_CONSTANT_OVERFLOW_WARNING \
++  __pragma(warning(push)) \
++  __pragma(warning(disable:4307))
++#define MOZ_POP_DISABLE_INTEGRAL_CONSTANT_OVERFLOW_WARNING \
++  __pragma(warning(pop))
++#else
++#define MOZ_PUSH_DISABLE_INTEGRAL_CONSTANT_OVERFLOW_WARNING
++#define MOZ_POP_DISABLE_INTEGRAL_CONSTANT_OVERFLOW_WARNING
++#endif
++
+ } /* namespace mozilla */
+ 
+ #endif /* mozilla_WrappingOperations_h */

+ 1215 - 0
rel-257/ian/patches/1444274-61a1.patch

@@ -0,0 +1,1215 @@
+# HG changeset patch
+# User Jeff Gilbert <jgilbert@mozilla.com>
+# Date 1521758932 25200
+# Node ID f080a35baf6a137d8c9ad4655cc0092d50099e24
+# Parent  2101f6255d3aac561088cade7828e484a5a03fb2
+Bug 1444274 - Require GCC 6.1+. - r=glandium
+
+MozReview-Commit-ID: 7alNSIhhbLI
+
+diff --git a/build/moz.configure/toolchain.configure b/build/moz.configure/toolchain.configure
+--- a/build/moz.configure/toolchain.configure
++++ b/build/moz.configure/toolchain.configure
+@@ -486,31 +486,24 @@ def check_compiler(compiler, language, t
+     # example)
+     if info.language == 'C' and info.language_version != 199901:
+         if info.type in ('clang-cl', 'clang', 'gcc'):
+             append_flag('-std=gnu99')
+ 
+     # Note: MSVC, while supporting C++14, still reports 199711L for __cplusplus.
+     # Note: this is a strict version check because we used to always add
+     # -std=gnu++14.
+-    draft_cxx14_version = 201300
+     cxx14_version = 201402
+     if info.language == 'C++':
+         if info.type == 'clang' and info.language_version != cxx14_version:
+             append_flag('-std=gnu++14')
+         # MSVC 2015 headers include C++14 features, but don't guard them
+         # with appropriate checks.
+         elif info.type == 'clang-cl' and info.language_version != cxx14_version:
+             append_flag('-std=c++14')
+-        # GCC 4.9 indicates that it implements draft C++14 features
+-        # instead of the full language.
+-        elif info.type == 'gcc' and \
+-                info.language_version not in (draft_cxx14_version,
+-                                              cxx14_version):
+-            append_flag('-std=gnu++14')
+ 
+     # We force clang-cl to emulate Visual C++ 2017 version 15.6.0
+     msvc_version = '19.13.26128'
+     if info.type == 'clang-cl' and info.version != msvc_version:
+         # This flag is a direct clang-cl flag that doesn't need -Xclang,
+         # add it directly.
+         flags.append('-fms-compatibility-version=%s' % msvc_version)
+ 
+@@ -899,24 +892,24 @@ def compiler(language, host_or_target, c
+                    info.target_endianness or 'unknown', host_or_target_str,
+                    host_or_target.endianness))
+ 
+         # Compiler version checks
+         # ===================================================
+         # Check the compiler version here instead of in `compiler_version` so
+         # that the `checking` message doesn't pretend the compiler can be used
+         # to then bail out one line later.
+-        if info.type == 'gcc' and info.version < '4.9.0':
+-            raise FatalCheckError(
+-                'Only GCC 4.9 or newer is supported (found version %s).'
+-                % info.version)
+-
+-        if info.type == 'gcc' and host_or_target.os == 'Android':
+-            raise FatalCheckError('GCC is not supported on Android.\n'
+-                                  'Please use clang from the Android NDK instead.')
++        if info.type == 'gcc':
++            if host_or_target.os == 'Android':
++                raise FatalCheckError('GCC is not supported on Android.\n'
++                                      'Please use clang from the Android NDK instead.')
++            if info.version < '6.1.0':
++                raise FatalCheckError(
++                    'Only GCC 6.1 or newer is supported (found version %s).'
++                    % info.version)
+ 
+         # If you want to bump the version check here search for
+         # cxx_alignof above, and see the associated comment.
+         if info.type == 'clang' and not info.version:
+             raise FatalCheckError(
+                 'Only clang/llvm 3.6 or newer is supported.')
+ 
+         if info.type == 'msvc':
+@@ -1136,17 +1129,17 @@ def color_cflags(info):
+     # version?
+ 
+     # Code for auto-adding this flag to compiler invocations needs to
+     # determine if an existing flag isn't already present. That is likely
+     # using exact string matching on the returned value. So if the return
+     # value changes to e.g. "<x>=always", exact string match may fail and
+     # multiple color flags could be added. So examine downstream consumers
+     # before adding flags to return values.
+-    if info.type == 'gcc' and info.version >= '4.9.0':
++    if info.type == 'gcc':
+         return '-fdiagnostics-color'
+     elif info.type == 'clang':
+         return '-fcolor-diagnostics'
+     else:
+         return ''
+ 
+ 
+ set_config('COLOR_CFLAGS', color_cflags)
+diff --git a/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py b/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
+--- a/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
++++ b/python/mozbuild/mozbuild/test/configure/test_toolchain_configure.py
+@@ -79,30 +79,32 @@ def GCC_BASE(version):
+ def GCC(version):
+     return GCC_BASE(version) + SUPPORTS_GNU99
+ 
+ 
+ @memoize
+ def GXX(version):
+     return GCC_BASE(version) + DEFAULT_CXX_97 + SUPPORTS_GNUXX11
+ 
+-SUPPORTS_DRAFT_CXX14_VERSION = {
+-    '-std=gnu++14': DRAFT_CXX_14,
+-}
+ 
+ SUPPORTS_DRAFT_CXX14_VERSION = {
+     '-std=gnu++14': DRAFT_CXX_14,
+ }
+ 
+-GCC_4_7 = GCC('4.7.3')
+-GXX_4_7 = GXX('4.7.3')
+ GCC_4_9 = GCC('4.9.3')
+ GXX_4_9 = GXX('4.9.3') + SUPPORTS_DRAFT_CXX14_VERSION
+ GCC_5 = GCC('5.2.1') + DEFAULT_C11
+ GXX_5 = GXX('5.2.1') + SUPPORTS_GNUXX14
++GCC_6 = GCC('6.4.0') + DEFAULT_C11
++GXX_6 = GXX('6.4.0') + DEFAULT_CXX_14
++GCC_7 = GCC('7.3.0') + DEFAULT_C11
++GXX_7 = GXX('7.3.0') + DEFAULT_CXX_14
++
++DEFAULT_GCC = GCC_6
++DEFAULT_GXX = GXX_6
+ 
+ GCC_PLATFORM_LITTLE_ENDIAN = {
+     '__BYTE_ORDER__': 1234,
+ }
+ 
+ GCC_PLATFORM_BIG_ENDIAN = {
+     '__BYTE_ORDER__': 4321,
+ }
+@@ -187,16 +189,18 @@ CLANG_3_6 = CLANG('3.6.2') + DEFAULT_C11
+ CLANGXX_3_6 = CLANGXX('3.6.2') + {
+     '-std=gnu++11': {
+         '__has_feature(cxx_alignof)': '1',
+     },
+     '-std=gnu++14': {
+         '__has_feature(cxx_alignof)': '1',
+     },
+ }
++DEFAULT_CLANG = CLANG_3_6
++DEFAULT_CLANGXX = CLANGXX_3_6
+ 
+ 
+ def CLANG_PLATFORM(gcc_platform):
+     base = {
+         '--target=x86_64-linux-gnu': GCC_PLATFORM_X86_64_LINUX[None],
+         '--target=x86_64-darwin11.2.0': GCC_PLATFORM_X86_64_OSX[None],
+         '--target=i686-linux-gnu': GCC_PLATFORM_X86_LINUX[None],
+         '--target=i686-darwin11.2.0': GCC_PLATFORM_X86_OSX[None],
+@@ -408,206 +412,219 @@ class BaseToolchainTest(BaseConfigureTes
+             'RUST_LIB_PREFIX',
+             'RUST_LIB_SUFFIX',
+             'OBJ_SUFFIX',
+         ):
+             self.assertEquals('%s=%s' % (k, sandbox.get_config(k)),
+                               '%s=%s' % (k, library_name_info[k]))
+ 
+ 
++def old_gcc_message(old_ver):
++    return 'Only GCC 6.1 or newer is supported (found version {}).'.format(old_ver)
++
++
+ class LinuxToolchainTest(BaseToolchainTest):
+     PATHS = {
+-        '/usr/bin/gcc': GCC_4_9 + GCC_PLATFORM_X86_64_LINUX,
+-        '/usr/bin/g++': GXX_4_9 + GCC_PLATFORM_X86_64_LINUX,
+-        '/usr/bin/gcc-4.7': GCC_4_7 + GCC_PLATFORM_X86_64_LINUX,
+-        '/usr/bin/g++-4.7': GXX_4_7 + GCC_PLATFORM_X86_64_LINUX,
++        '/usr/bin/gcc': DEFAULT_GCC + GCC_PLATFORM_X86_64_LINUX,
++        '/usr/bin/g++': DEFAULT_GXX + GCC_PLATFORM_X86_64_LINUX,
++        '/usr/bin/gcc-4.9': GCC_4_9 + GCC_PLATFORM_X86_64_LINUX,
++        '/usr/bin/g++-4.9': GXX_4_9 + GCC_PLATFORM_X86_64_LINUX,
+         '/usr/bin/gcc-5': GCC_5 + GCC_PLATFORM_X86_64_LINUX,
+         '/usr/bin/g++-5': GXX_5 + GCC_PLATFORM_X86_64_LINUX,
+-        '/usr/bin/clang': CLANG_3_6 + CLANG_PLATFORM_X86_64_LINUX,
+-        '/usr/bin/clang++': CLANGXX_3_6 + CLANG_PLATFORM_X86_64_LINUX,
++        '/usr/bin/gcc-6': GCC_6 + GCC_PLATFORM_X86_64_LINUX,
++        '/usr/bin/g++-6': GXX_6 + GCC_PLATFORM_X86_64_LINUX,
++        '/usr/bin/gcc-7': GCC_7 + GCC_PLATFORM_X86_64_LINUX,
++        '/usr/bin/g++-7': GXX_7 + GCC_PLATFORM_X86_64_LINUX,
++        '/usr/bin/clang': DEFAULT_CLANG + CLANG_PLATFORM_X86_64_LINUX,
++        '/usr/bin/clang++': DEFAULT_CLANGXX + CLANG_PLATFORM_X86_64_LINUX,
+         '/usr/bin/clang-3.6': CLANG_3_6 + CLANG_PLATFORM_X86_64_LINUX,
+         '/usr/bin/clang++-3.6': CLANGXX_3_6 + CLANG_PLATFORM_X86_64_LINUX,
+         '/usr/bin/clang-3.3': CLANG_3_3 + CLANG_PLATFORM_X86_64_LINUX,
+         '/usr/bin/clang++-3.3': CLANGXX_3_3 + CLANG_PLATFORM_X86_64_LINUX,
+     }
+-    GCC_4_7_RESULT = ('Only GCC 4.9 or newer is supported '
+-                      '(found version 4.7.3).')
++
++    GCC_4_7_RESULT = old_gcc_message('4.7.3')
+     GXX_4_7_RESULT = GCC_4_7_RESULT
+-    GCC_4_9_RESULT = CompilerResult(
++    GCC_4_9_RESULT = old_gcc_message('4.9.3')
++    GXX_4_9_RESULT = GCC_4_9_RESULT
++    GCC_5_RESULT = old_gcc_message('5.2.1')
++    GXX_5_RESULT = GCC_5_RESULT
++    GCC_6_RESULT = CompilerResult(
+         flags=['-std=gnu99'],
+-        version='4.9.3',
++        version='6.4.0',
+         type='gcc',
+-        compiler='/usr/bin/gcc',
++        compiler='/usr/bin/gcc-6',
+         language='C',
+     )
+-    GXX_4_9_RESULT = CompilerResult(
+-        flags=['-std=gnu++14'],
+-        version='4.9.3',
++    GXX_6_RESULT = CompilerResult(
++        flags=[],
++        version='6.4.0',
+         type='gcc',
+-        compiler='/usr/bin/g++',
++        compiler='/usr/bin/g++-6',
+         language='C++',
+     )
+-    GCC_5_RESULT = CompilerResult(
++    GCC_7_RESULT = CompilerResult(
+         flags=['-std=gnu99'],
+-        version='5.2.1',
++        version='7.3.0',
+         type='gcc',
+-        compiler='/usr/bin/gcc-5',
++        compiler='/usr/bin/gcc-7',
+         language='C',
+     )
+-    GXX_5_RESULT = CompilerResult(
+-        flags=['-std=gnu++14'],
+-        version='5.2.1',
++    GXX_7_RESULT = CompilerResult(
++        flags=[],
++        version='7.3.0',
+         type='gcc',
+-        compiler='/usr/bin/g++-5',
++        compiler='/usr/bin/g++-7',
+         language='C++',
+     )
++    DEFAULT_GCC_RESULT = GCC_6_RESULT + {'compiler': '/usr/bin/gcc'}
++    DEFAULT_GXX_RESULT = GXX_6_RESULT + {'compiler': '/usr/bin/g++'}
++
+     CLANG_3_3_RESULT = CompilerResult(
+         flags=[],
+         version='3.3.0',
+         type='clang',
+         compiler='/usr/bin/clang-3.3',
+         language='C',
+     )
+     CLANGXX_3_3_RESULT = 'Only clang/llvm 3.6 or newer is supported.'
+     CLANG_3_6_RESULT = CompilerResult(
+         flags=['-std=gnu99'],
+         version='3.6.2',
+         type='clang',
+-        compiler='/usr/bin/clang',
++        compiler='/usr/bin/clang-3.6',
+         language='C',
+     )
+     CLANGXX_3_6_RESULT = CompilerResult(
+         flags=['-std=gnu++14'],
+         version='3.6.2',
+         type='clang',
+-        compiler='/usr/bin/clang++',
++        compiler='/usr/bin/clang++-3.6',
+         language='C++',
+     )
++    DEFAULT_CLANG_RESULT = CLANG_3_6_RESULT + {'compiler': '/usr/bin/clang'}
++    DEFAULT_CLANGXX_RESULT = CLANGXX_3_6_RESULT + {'compiler': '/usr/bin/clang++'}
+ 
+     def test_gcc(self):
+         # We'll try gcc and clang, and find gcc first.
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_9_RESULT,
+-            'cxx_compiler': self.GXX_4_9_RESULT,
++            'c_compiler': self.DEFAULT_GCC_RESULT,
++            'cxx_compiler': self.DEFAULT_GXX_RESULT,
+         })
+ 
+     def test_unsupported_gcc(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_7_RESULT,
++            'c_compiler': self.GCC_4_9_RESULT,
+         }, environ={
+-            'CC': 'gcc-4.7',
+-            'CXX': 'g++-4.7',
++            'CC': 'gcc-4.9',
++            'CXX': 'g++-4.9',
+         })
+ 
+         # Maybe this should be reporting the mismatched version instead.
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_9_RESULT,
+-            'cxx_compiler': self.GXX_4_7_RESULT,
++            'c_compiler': self.DEFAULT_GCC_RESULT,
++            'cxx_compiler': self.GXX_4_9_RESULT,
+         }, environ={
+-            'CXX': 'g++-4.7',
++            'CXX': 'g++-4.9',
+         })
+ 
+     def test_overridden_gcc(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_5_RESULT,
+-            'cxx_compiler': self.GXX_5_RESULT,
++            'c_compiler': self.GCC_7_RESULT,
++            'cxx_compiler': self.GXX_7_RESULT,
+         }, environ={
+-            'CC': 'gcc-5',
+-            'CXX': 'g++-5',
++            'CC': 'gcc-7',
++            'CXX': 'g++-7',
+         })
+ 
+     def test_guess_cxx(self):
+         # When CXX is not set, we guess it from CC.
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_5_RESULT,
+-            'cxx_compiler': self.GXX_5_RESULT,
++            'c_compiler': self.GCC_7_RESULT,
++            'cxx_compiler': self.GXX_7_RESULT,
+         }, environ={
+-            'CC': 'gcc-5',
++            'CC': 'gcc-7',
+         })
+ 
+     def test_mismatched_gcc(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_9_RESULT,
++            'c_compiler': self.DEFAULT_GCC_RESULT,
+             'cxx_compiler': (
+-                'The target C compiler is version 4.9.3, while the target '
+-                'C++ compiler is version 5.2.1. Need to use the same compiler '
++                'The target C compiler is version 6.4.0, while the target '
++                'C++ compiler is version 7.3.0. Need to use the same compiler '
+                 'version.'),
+         }, environ={
+-            'CXX': 'g++-5',
++            'CXX': 'g++-7',
+         })
+ 
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_9_RESULT,
+-            'cxx_compiler': self.GXX_4_9_RESULT,
+-            'host_c_compiler': self.GCC_4_9_RESULT,
++            'c_compiler': self.DEFAULT_GCC_RESULT,
++            'cxx_compiler': self.DEFAULT_GXX_RESULT,
++            'host_c_compiler': self.DEFAULT_GCC_RESULT,
+             'host_cxx_compiler': (
+-                'The host C compiler is version 4.9.3, while the host '
+-                'C++ compiler is version 5.2.1. Need to use the same compiler '
++                'The host C compiler is version 6.4.0, while the host '
++                'C++ compiler is version 7.3.0. Need to use the same compiler '
+                 'version.'),
+         }, environ={
+-            'HOST_CXX': 'g++-5',
++            'HOST_CXX': 'g++-7',
+         })
+ 
+     def test_mismatched_compiler(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_9_RESULT,
++            'c_compiler': self.DEFAULT_GCC_RESULT,
+             'cxx_compiler': (
+                 'The target C compiler is gcc, while the target C++ compiler '
+                 'is clang. Need to use the same compiler suite.'),
+         }, environ={
+             'CXX': 'clang++',
+         })
+ 
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_9_RESULT,
+-            'cxx_compiler': self.GXX_4_9_RESULT,
+-            'host_c_compiler': self.GCC_4_9_RESULT,
++            'c_compiler': self.DEFAULT_GCC_RESULT,
++            'cxx_compiler': self.DEFAULT_GXX_RESULT,
++            'host_c_compiler': self.DEFAULT_GCC_RESULT,
+             'host_cxx_compiler': (
+                 'The host C compiler is gcc, while the host C++ compiler '
+                 'is clang. Need to use the same compiler suite.'),
+         }, environ={
+             'HOST_CXX': 'clang++',
+         })
+ 
+         self.do_toolchain_test(self.PATHS, {
+             'c_compiler': '`%s` is not a C compiler.'
+             % mozpath.abspath('/usr/bin/g++'),
+         }, environ={
+             'CC': 'g++',
+         })
+ 
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_9_RESULT,
++            'c_compiler': self.DEFAULT_GCC_RESULT,
+             'cxx_compiler': '`%s` is not a C++ compiler.'
+             % mozpath.abspath('/usr/bin/gcc'),
+         }, environ={
+             'CXX': 'gcc',
+         })
+ 
+     def test_clang(self):
+         # We'll try gcc and clang, but since there is no gcc (gcc-x.y doesn't
+         # count), find clang.
+         paths = {
+             k: v for k, v in self.PATHS.iteritems()
+             if os.path.basename(k) not in ('gcc', 'g++')
+         }
+         self.do_toolchain_test(paths, {
+-            'c_compiler': self.CLANG_3_6_RESULT,
+-            'cxx_compiler': self.CLANGXX_3_6_RESULT,
++            'c_compiler': self.DEFAULT_CLANG_RESULT,
++            'cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
+         })
+ 
+     def test_guess_cxx_clang(self):
+         # When CXX is not set, we guess it from CC.
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.CLANG_3_6_RESULT + {
+-                'compiler': '/usr/bin/clang-3.6',
+-            },
+-            'cxx_compiler': self.CLANGXX_3_6_RESULT + {
+-                'compiler': '/usr/bin/clang++-3.6',
+-            },
++            'c_compiler': self.CLANG_3_6_RESULT,
++            'cxx_compiler': self.CLANGXX_3_6_RESULT,
+         }, environ={
+             'CC': 'clang-3.6',
+         })
+ 
+     def test_unsupported_clang(self):
+         # clang 3.3 C compiler is perfectly fine, but we need more for C++.
+         self.do_toolchain_test(self.PATHS, {
+             'c_compiler': self.CLANG_3_3_RESULT,
+@@ -630,21 +647,21 @@ class LinuxToolchainTest(BaseToolchainTe
+ 
+     def test_absolute_path(self):
+         paths = dict(self.PATHS)
+         paths.update({
+             '/opt/clang/bin/clang': paths['/usr/bin/clang'],
+             '/opt/clang/bin/clang++': paths['/usr/bin/clang++'],
+         })
+         result = {
+-            'c_compiler': self.CLANG_3_6_RESULT + {
++            'c_compiler': self.DEFAULT_CLANG_RESULT + {
+                 'compiler': '/opt/clang/bin/clang',
+             },
+-            'cxx_compiler': self.CLANGXX_3_6_RESULT + {
+-                'compiler': '/opt/clang/bin/clang++'
++            'cxx_compiler': self.DEFAULT_CLANGXX_RESULT + {
++                'compiler': '/opt/clang/bin/clang++',
+             },
+         }
+         self.do_toolchain_test(paths, result, environ={
+             'CC': '/opt/clang/bin/clang',
+             'CXX': '/opt/clang/bin/clang++',
+         })
+         # With CXX guess too.
+         self.do_toolchain_test(paths, result, environ={
+@@ -653,155 +670,154 @@ class LinuxToolchainTest(BaseToolchainTe
+ 
+     def test_atypical_name(self):
+         paths = dict(self.PATHS)
+         paths.update({
+             '/usr/bin/afl-clang-fast': paths['/usr/bin/clang'],
+             '/usr/bin/afl-clang-fast++': paths['/usr/bin/clang++'],
+         })
+         self.do_toolchain_test(paths, {
+-            'c_compiler': self.CLANG_3_6_RESULT + {
++            'c_compiler': self.DEFAULT_CLANG_RESULT + {
+                 'compiler': '/usr/bin/afl-clang-fast',
+             },
+-            'cxx_compiler': self.CLANGXX_3_6_RESULT + {
++            'cxx_compiler': self.DEFAULT_CLANGXX_RESULT + {
+                 'compiler': '/usr/bin/afl-clang-fast++',
+             },
+         }, environ={
+             'CC': 'afl-clang-fast',
+             'CXX': 'afl-clang-fast++',
+         })
+ 
+     def test_mixed_compilers(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.CLANG_3_6_RESULT,
+-            'cxx_compiler': self.CLANGXX_3_6_RESULT,
+-            'host_c_compiler': self.GCC_4_9_RESULT,
+-            'host_cxx_compiler': self.GXX_4_9_RESULT,
++            'c_compiler': self.DEFAULT_CLANG_RESULT,
++            'cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
++            'host_c_compiler': self.DEFAULT_GCC_RESULT,
++            'host_cxx_compiler': self.DEFAULT_GXX_RESULT,
+         }, environ={
+             'CC': 'clang',
+             'HOST_CC': 'gcc',
+         })
+ 
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.CLANG_3_6_RESULT,
+-            'cxx_compiler': self.CLANGXX_3_6_RESULT,
+-            'host_c_compiler': self.GCC_4_9_RESULT,
+-            'host_cxx_compiler': self.GXX_4_9_RESULT,
++            'c_compiler': self.DEFAULT_CLANG_RESULT,
++            'cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
++            'host_c_compiler': self.DEFAULT_GCC_RESULT,
++            'host_cxx_compiler': self.DEFAULT_GXX_RESULT,
+         }, environ={
+             'CC': 'clang',
+             'CXX': 'clang++',
+             'HOST_CC': 'gcc',
+         })
+ 
+ 
+ class LinuxSimpleCrossToolchainTest(BaseToolchainTest):
+     TARGET = 'i686-pc-linux-gnu'
+     PATHS = LinuxToolchainTest.PATHS
+-    GCC_4_9_RESULT = LinuxToolchainTest.GCC_4_9_RESULT
+-    GXX_4_9_RESULT = LinuxToolchainTest.GXX_4_9_RESULT
+-    CLANG_3_6_RESULT = LinuxToolchainTest.CLANG_3_6_RESULT
+-    CLANGXX_3_6_RESULT = LinuxToolchainTest.CLANGXX_3_6_RESULT
++    DEFAULT_GCC_RESULT = LinuxToolchainTest.DEFAULT_GCC_RESULT
++    DEFAULT_GXX_RESULT = LinuxToolchainTest.DEFAULT_GXX_RESULT
++    DEFAULT_CLANG_RESULT = LinuxToolchainTest.DEFAULT_CLANG_RESULT
++    DEFAULT_CLANGXX_RESULT = LinuxToolchainTest.DEFAULT_CLANGXX_RESULT
+ 
+     def test_cross_gcc(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_9_RESULT + {
++            'c_compiler': self.DEFAULT_GCC_RESULT + {
+                 'flags': ['-m32']
+             },
+-            'cxx_compiler': self.GXX_4_9_RESULT + {
++            'cxx_compiler': self.DEFAULT_GXX_RESULT + {
+                 'flags': ['-m32']
+             },
+-            'host_c_compiler': self.GCC_4_9_RESULT,
+-            'host_cxx_compiler': self.GXX_4_9_RESULT,
++            'host_c_compiler': self.DEFAULT_GCC_RESULT,
++            'host_cxx_compiler': self.DEFAULT_GXX_RESULT,
+         })
+ 
+     def test_cross_clang(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.CLANG_3_6_RESULT + {
++            'c_compiler': self.DEFAULT_CLANG_RESULT + {
+                 'flags': ['--target=i686-linux-gnu'],
+             },
+-            'cxx_compiler': self.CLANGXX_3_6_RESULT + {
++            'cxx_compiler': self.DEFAULT_CLANGXX_RESULT + {
+                 'flags': ['--target=i686-linux-gnu'],
+             },
+-            'host_c_compiler': self.CLANG_3_6_RESULT,
+-            'host_cxx_compiler': self.CLANGXX_3_6_RESULT,
++            'host_c_compiler': self.DEFAULT_CLANG_RESULT,
++            'host_cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
+         }, environ={
+             'CC': 'clang',
+         })
+ 
+ 
+ class LinuxX86_64CrossToolchainTest(BaseToolchainTest):
+     HOST = 'i686-pc-linux-gnu'
+     TARGET = 'x86_64-pc-linux-gnu'
+     PATHS = {
+-        '/usr/bin/gcc': GCC_4_9 + GCC_PLATFORM_X86_LINUX,
+-        '/usr/bin/g++': GXX_4_9 + GCC_PLATFORM_X86_LINUX,
+-        '/usr/bin/clang': CLANG_3_6 + CLANG_PLATFORM_X86_LINUX,
+-        '/usr/bin/clang++': CLANGXX_3_6 + CLANG_PLATFORM_X86_LINUX,
++        '/usr/bin/gcc': DEFAULT_GCC + GCC_PLATFORM_X86_LINUX,
++        '/usr/bin/g++': DEFAULT_GXX + GCC_PLATFORM_X86_LINUX,
++        '/usr/bin/clang': DEFAULT_CLANG + CLANG_PLATFORM_X86_LINUX,
++        '/usr/bin/clang++': DEFAULT_CLANGXX + CLANG_PLATFORM_X86_LINUX,
+     }
+-    GCC_4_9_RESULT = LinuxToolchainTest.GCC_4_9_RESULT
+-    GXX_4_9_RESULT = LinuxToolchainTest.GXX_4_9_RESULT
+-    CLANG_3_6_RESULT = LinuxToolchainTest.CLANG_3_6_RESULT
+-    CLANGXX_3_6_RESULT = LinuxToolchainTest.CLANGXX_3_6_RESULT
++    DEFAULT_GCC_RESULT = LinuxToolchainTest.DEFAULT_GCC_RESULT
++    DEFAULT_GXX_RESULT = LinuxToolchainTest.DEFAULT_GXX_RESULT
++    DEFAULT_CLANG_RESULT = LinuxToolchainTest.DEFAULT_CLANG_RESULT
++    DEFAULT_CLANGXX_RESULT = LinuxToolchainTest.DEFAULT_CLANGXX_RESULT
+ 
+     def test_cross_gcc(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_9_RESULT + {
++            'c_compiler': self.DEFAULT_GCC_RESULT + {
+                 'flags': ['-m64']
+             },
+-            'cxx_compiler': self.GXX_4_9_RESULT + {
++            'cxx_compiler': self.DEFAULT_GXX_RESULT + {
+                 'flags': ['-m64']
+             },
+-            'host_c_compiler': self.GCC_4_9_RESULT,
+-            'host_cxx_compiler': self.GXX_4_9_RESULT,
++            'host_c_compiler': self.DEFAULT_GCC_RESULT,
++            'host_cxx_compiler': self.DEFAULT_GXX_RESULT,
+         })
+ 
+     def test_cross_clang(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.CLANG_3_6_RESULT + {
++            'c_compiler': self.DEFAULT_CLANG_RESULT + {
+                 'flags': ['--target=x86_64-linux-gnu'],
+             },
+-            'cxx_compiler': self.CLANGXX_3_6_RESULT + {
++            'cxx_compiler': self.DEFAULT_CLANGXX_RESULT + {
+                 'flags': ['--target=x86_64-linux-gnu'],
+             },
+-            'host_c_compiler': self.CLANG_3_6_RESULT,
+-            'host_cxx_compiler': self.CLANGXX_3_6_RESULT,
++            'host_c_compiler': self.DEFAULT_CLANG_RESULT,
++            'host_cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
+         }, environ={
+             'CC': 'clang',
+         })
+ 
+ 
+ class OSXToolchainTest(BaseToolchainTest):
+     HOST = 'x86_64-apple-darwin11.2.0'
+     PATHS = {
+-        '/usr/bin/gcc': GCC_4_9 + GCC_PLATFORM_X86_64_OSX,
+-        '/usr/bin/g++': GXX_4_9 + GCC_PLATFORM_X86_64_OSX,
+-        '/usr/bin/gcc-4.7': GCC_4_7 + GCC_PLATFORM_X86_64_OSX,
+-        '/usr/bin/g++-4.7': GXX_4_7 + GCC_PLATFORM_X86_64_OSX,
+         '/usr/bin/gcc-5': GCC_5 + GCC_PLATFORM_X86_64_OSX,
+         '/usr/bin/g++-5': GXX_5 + GCC_PLATFORM_X86_64_OSX,
+-        '/usr/bin/clang': CLANG_3_6 + CLANG_PLATFORM_X86_64_OSX,
+-        '/usr/bin/clang++': CLANGXX_3_6 + CLANG_PLATFORM_X86_64_OSX,
++        '/usr/bin/gcc-7': GCC_7 + GCC_PLATFORM_X86_64_OSX,
++        '/usr/bin/g++-7': GXX_7 + GCC_PLATFORM_X86_64_OSX,
++        '/usr/bin/clang': DEFAULT_CLANG + CLANG_PLATFORM_X86_64_OSX,
++        '/usr/bin/clang++': DEFAULT_CLANGXX + CLANG_PLATFORM_X86_64_OSX,
+         '/usr/bin/clang-3.6': CLANG_3_6 + CLANG_PLATFORM_X86_64_OSX,
+         '/usr/bin/clang++-3.6': CLANGXX_3_6 + CLANG_PLATFORM_X86_64_OSX,
+         '/usr/bin/clang-3.3': CLANG_3_3 + CLANG_PLATFORM_X86_64_OSX,
+         '/usr/bin/clang++-3.3': CLANGXX_3_3 + CLANG_PLATFORM_X86_64_OSX,
+     }
+     CLANG_3_3_RESULT = LinuxToolchainTest.CLANG_3_3_RESULT
+     CLANGXX_3_3_RESULT = LinuxToolchainTest.CLANGXX_3_3_RESULT
+-    CLANG_3_6_RESULT = LinuxToolchainTest.CLANG_3_6_RESULT
+-    CLANGXX_3_6_RESULT = LinuxToolchainTest.CLANGXX_3_6_RESULT
+-    GCC_4_7_RESULT = LinuxToolchainTest.GCC_4_7_RESULT
++    DEFAULT_CLANG_RESULT = LinuxToolchainTest.DEFAULT_CLANG_RESULT
++    DEFAULT_CLANGXX_RESULT = LinuxToolchainTest.DEFAULT_CLANGXX_RESULT
+     GCC_5_RESULT = LinuxToolchainTest.GCC_5_RESULT
+     GXX_5_RESULT = LinuxToolchainTest.GXX_5_RESULT
++    GCC_7_RESULT = LinuxToolchainTest.GCC_7_RESULT
++    GXX_7_RESULT = LinuxToolchainTest.GXX_7_RESULT
+ 
+     def test_clang(self):
+         # We only try clang because gcc is known not to work.
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.CLANG_3_6_RESULT,
+-            'cxx_compiler': self.CLANGXX_3_6_RESULT,
++            'c_compiler': self.DEFAULT_CLANG_RESULT,
++            'cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
+         })
+ 
+     def test_not_gcc(self):
+         # We won't pick GCC if it's the only thing available.
+         paths = {
+             k: v for k, v in self.PATHS.iteritems()
+             if os.path.basename(k) not in ('clang', 'clang++')
+         }
+@@ -817,29 +833,29 @@ class OSXToolchainTest(BaseToolchainTest
+         }, environ={
+             'CC': 'clang-3.3',
+             'CXX': 'clang++-3.3',
+         })
+ 
+     def test_forced_gcc(self):
+         # GCC can still be forced if the user really wants it.
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_5_RESULT,
+-            'cxx_compiler': self.GXX_5_RESULT,
++            'c_compiler': self.GCC_7_RESULT,
++            'cxx_compiler': self.GXX_7_RESULT,
+         }, environ={
+-            'CC': 'gcc-5',
+-            'CXX': 'g++-5',
++            'CC': 'gcc-7',
++            'CXX': 'g++-7',
+         })
+ 
+     def test_forced_unsupported_gcc(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_7_RESULT,
++            'c_compiler': self.GCC_5_RESULT,
+         }, environ={
+-            'CC': 'gcc-4.7',
+-            'CXX': 'g++-4.7',
++            'CC': 'gcc-5',
++            'CXX': 'g++-5',
+         })
+ 
+ 
+ class WindowsToolchainTest(BaseToolchainTest):
+     HOST = 'i686-pc-mingw32'
+ 
+     # For the purpose of this test, it doesn't matter that the paths are not
+     # real Windows paths.
+@@ -848,24 +864,26 @@ class WindowsToolchainTest(BaseToolchain
+         '/opt/VS_2013u3/bin/cl': VS_2013u3 + VS_PLATFORM_X86,
+         '/opt/VS_2015/bin/cl': VS_2015 + VS_PLATFORM_X86,
+         '/opt/VS_2015u1/bin/cl': VS_2015u1 + VS_PLATFORM_X86,
+         '/opt/VS_2015u2/bin/cl': VS_2015u2 + VS_PLATFORM_X86,
+         '/opt/VS_2015u3/bin/cl': VS_2015u3 + VS_PLATFORM_X86,
+         '/opt/VS_2017u4/bin/cl': VS_2017u4 + VS_PLATFORM_X86,
+         '/usr/bin/cl': VS_2017u6 + VS_PLATFORM_X86,
+         '/usr/bin/clang-cl': CLANG_CL_3_9 + CLANG_CL_PLATFORM_X86,
+-        '/usr/bin/gcc': GCC_4_9 + GCC_PLATFORM_X86_WIN,
+-        '/usr/bin/g++': GXX_4_9 + GCC_PLATFORM_X86_WIN,
+-        '/usr/bin/gcc-4.7': GCC_4_7 + GCC_PLATFORM_X86_WIN,
+-        '/usr/bin/g++-4.7': GXX_4_7 + GCC_PLATFORM_X86_WIN,
++        '/usr/bin/gcc': DEFAULT_GCC + GCC_PLATFORM_X86_WIN,
++        '/usr/bin/g++': DEFAULT_GXX + GCC_PLATFORM_X86_WIN,
++        '/usr/bin/gcc-4.9': GCC_4_9 + GCC_PLATFORM_X86_WIN,
++        '/usr/bin/g++-4.9': GXX_4_9 + GCC_PLATFORM_X86_WIN,
+         '/usr/bin/gcc-5': GCC_5 + GCC_PLATFORM_X86_WIN,
+         '/usr/bin/g++-5': GXX_5 + GCC_PLATFORM_X86_WIN,
+-        '/usr/bin/clang': CLANG_3_6 + CLANG_PLATFORM_X86_WIN,
+-        '/usr/bin/clang++': CLANGXX_3_6 + CLANG_PLATFORM_X86_WIN,
++        '/usr/bin/gcc-6': GCC_6 + GCC_PLATFORM_X86_WIN,
++        '/usr/bin/g++-6': GXX_6 + GCC_PLATFORM_X86_WIN,
++        '/usr/bin/clang': DEFAULT_CLANG + CLANG_PLATFORM_X86_WIN,
++        '/usr/bin/clang++': DEFAULT_CLANGXX + CLANG_PLATFORM_X86_WIN,
+         '/usr/bin/clang-3.6': CLANG_3_6 + CLANG_PLATFORM_X86_WIN,
+         '/usr/bin/clang++-3.6': CLANGXX_3_6 + CLANG_PLATFORM_X86_WIN,
+         '/usr/bin/clang-3.3': CLANG_3_3 + CLANG_PLATFORM_X86_WIN,
+         '/usr/bin/clang++-3.3': CLANGXX_3_3 + CLANG_PLATFORM_X86_WIN,
+     }
+ 
+     VS_2013u2_RESULT = (
+         'This version (18.00.30501) of the MSVC compiler is not supported.\n'
+@@ -922,35 +940,26 @@ class WindowsToolchainTest(BaseToolchain
+                '-fms-compatibility-version=19.13.26128'],
+         version='19.13.26128',
+         type='clang-cl',
+         compiler='/usr/bin/clang-cl',
+         language='C++',
+     )
+     CLANG_3_3_RESULT = LinuxToolchainTest.CLANG_3_3_RESULT
+     CLANGXX_3_3_RESULT = LinuxToolchainTest.CLANGXX_3_3_RESULT
+-    CLANG_3_6_RESULT = LinuxToolchainTest.CLANG_3_6_RESULT
+-    CLANGXX_3_6_RESULT = LinuxToolchainTest.CLANGXX_3_6_RESULT
+-    GCC_4_7_RESULT = LinuxToolchainTest.GCC_4_7_RESULT
++    DEFAULT_CLANG_RESULT = LinuxToolchainTest.DEFAULT_CLANG_RESULT
++    DEFAULT_CLANGXX_RESULT = LinuxToolchainTest.DEFAULT_CLANGXX_RESULT
+     GCC_4_9_RESULT = LinuxToolchainTest.GCC_4_9_RESULT
+-    GXX_4_9_RESULT = CompilerResult(
+-        flags=['-std=gnu++14'],
+-        version='4.9.3',
+-        type='gcc',
+-        compiler='/usr/bin/g++',
+-        language='C++',
+-    )
++    GXX_4_9_RESULT = LinuxToolchainTest.GXX_4_9_RESULT
+     GCC_5_RESULT = LinuxToolchainTest.GCC_5_RESULT
+-    GXX_5_RESULT = CompilerResult(
+-        flags=['-std=gnu++14'],
+-        version='5.2.1',
+-        type='gcc',
+-        compiler='/usr/bin/g++-5',
+-        language='C++',
+-    )
++    GXX_5_RESULT = LinuxToolchainTest.GXX_5_RESULT
++    GCC_6_RESULT = LinuxToolchainTest.GCC_6_RESULT
++    GXX_6_RESULT = LinuxToolchainTest.GXX_6_RESULT
++    DEFAULT_GCC_RESULT = LinuxToolchainTest.DEFAULT_GCC_RESULT
++    DEFAULT_GXX_RESULT = LinuxToolchainTest.DEFAULT_GXX_RESULT
+ 
+     # VS2017u6 or greater is required.
+     def test_msvc(self):
+         self.do_toolchain_test(self.PATHS, {
+             'c_compiler': self.VS_2017u6_RESULT,
+             'cxx_compiler': self.VSXX_2017u6_RESULT,
+         })
+ 
+@@ -1010,37 +1019,37 @@ class WindowsToolchainTest(BaseToolchain
+ 
+     def test_gcc(self):
+         # We'll pick GCC if msvc and clang-cl can't be found.
+         paths = {
+             k: v for k, v in self.PATHS.iteritems()
+             if os.path.basename(k) not in ('cl', 'clang-cl')
+         }
+         self.do_toolchain_test(paths, {
+-            'c_compiler': self.GCC_4_9_RESULT,
+-            'cxx_compiler': self.GXX_4_9_RESULT,
++            'c_compiler': self.DEFAULT_GCC_RESULT,
++            'cxx_compiler': self.DEFAULT_GXX_RESULT,
+         })
+ 
+     def test_overridden_unsupported_gcc(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_7_RESULT,
++            'c_compiler': self.GCC_5_RESULT,
+         }, environ={
+-            'CC': 'gcc-4.7',
+-            'CXX': 'g++-4.7',
++            'CC': 'gcc-5',
++            'CXX': 'g++-5',
+         })
+ 
+     def test_clang(self):
+         # We'll pick clang if nothing else is found.
+         paths = {
+             k: v for k, v in self.PATHS.iteritems()
+             if os.path.basename(k) not in ('cl', 'clang-cl', 'gcc')
+         }
+         self.do_toolchain_test(paths, {
+-            'c_compiler': self.CLANG_3_6_RESULT,
+-            'cxx_compiler': self.CLANGXX_3_6_RESULT,
++            'c_compiler': self.DEFAULT_CLANG_RESULT,
++            'cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
+         })
+ 
+     def test_overridden_unsupported_clang(self):
+         # clang 3.3 C compiler is perfectly fine, but we need more for C++.
+         self.do_toolchain_test(self.PATHS, {
+             'c_compiler': self.CLANG_3_3_RESULT,
+             'cxx_compiler': self.CLANGXX_3_3_RESULT,
+         }, environ={
+@@ -1068,24 +1077,28 @@ class Windows64ToolchainTest(WindowsTool
+         '/opt/VS_2013u3/bin/cl': VS_2013u3 + VS_PLATFORM_X86_64,
+         '/opt/VS_2015/bin/cl': VS_2015 + VS_PLATFORM_X86_64,
+         '/opt/VS_2015u1/bin/cl': VS_2015u1 + VS_PLATFORM_X86_64,
+         '/opt/VS_2015u2/bin/cl': VS_2015u2 + VS_PLATFORM_X86_64,
+         '/opt/VS_2015u3/bin/cl': VS_2015u3 + VS_PLATFORM_X86_64,
+         '/opt/VS_2017u4/bin/cl': VS_2017u4 + VS_PLATFORM_X86_64,
+         '/usr/bin/cl': VS_2017u6 + VS_PLATFORM_X86_64,
+         '/usr/bin/clang-cl': CLANG_CL_3_9 + CLANG_CL_PLATFORM_X86_64,
+-        '/usr/bin/gcc': GCC_4_9 + GCC_PLATFORM_X86_64_WIN,
+-        '/usr/bin/g++': GXX_4_9 + GCC_PLATFORM_X86_64_WIN,
+-        '/usr/bin/gcc-4.7': GCC_4_7 + GCC_PLATFORM_X86_64_WIN,
+-        '/usr/bin/g++-4.7': GXX_4_7 + GCC_PLATFORM_X86_64_WIN,
++        '/usr/bin/gcc': DEFAULT_GCC + GCC_PLATFORM_X86_64_WIN,
++        '/usr/bin/g++': DEFAULT_GXX + GCC_PLATFORM_X86_64_WIN,
++        '/usr/bin/gcc-4.9': GCC_4_9 + GCC_PLATFORM_X86_64_WIN,
++        '/usr/bin/g++-4.9': GXX_4_9 + GCC_PLATFORM_X86_64_WIN,
+         '/usr/bin/gcc-5': GCC_5 + GCC_PLATFORM_X86_64_WIN,
+         '/usr/bin/g++-5': GXX_5 + GCC_PLATFORM_X86_64_WIN,
+-        '/usr/bin/clang': CLANG_3_6 + CLANG_PLATFORM_X86_64_WIN,
+-        '/usr/bin/clang++': CLANGXX_3_6 + CLANG_PLATFORM_X86_64_WIN,
++        '/usr/bin/gcc-6': GCC_6 + GCC_PLATFORM_X86_64_WIN,
++        '/usr/bin/g++-6': GXX_6 + GCC_PLATFORM_X86_64_WIN,
++        '/usr/bin/gcc-7': GCC_7 + GCC_PLATFORM_X86_64_WIN,
++        '/usr/bin/g++-7': GXX_7 + GCC_PLATFORM_X86_64_WIN,
++        '/usr/bin/clang': DEFAULT_CLANG + CLANG_PLATFORM_X86_64_WIN,
++        '/usr/bin/clang++': DEFAULT_CLANGXX + CLANG_PLATFORM_X86_64_WIN,
+         '/usr/bin/clang-3.6': CLANG_3_6 + CLANG_PLATFORM_X86_64_WIN,
+         '/usr/bin/clang++-3.6': CLANGXX_3_6 + CLANG_PLATFORM_X86_64_WIN,
+         '/usr/bin/clang-3.3': CLANG_3_3 + CLANG_PLATFORM_X86_64_WIN,
+         '/usr/bin/clang++-3.3': CLANGXX_3_3 + CLANG_PLATFORM_X86_64_WIN,
+     }
+ 
+     def test_cannot_cross(self):
+         paths = {
+@@ -1095,35 +1108,46 @@ class Windows64ToolchainTest(WindowsTool
+             'c_compiler': ('Target C compiler target CPU (x86) '
+                            'does not match --target CPU (x86_64)'),
+         })
+ 
+ 
+ class LinuxCrossCompileToolchainTest(BaseToolchainTest):
+     TARGET = 'arm-unknown-linux-gnu'
+     PATHS = {
+-        '/usr/bin/arm-linux-gnu-gcc': GCC_4_9 + GCC_PLATFORM_ARM_LINUX,
+-        '/usr/bin/arm-linux-gnu-g++': GXX_4_9 + GCC_PLATFORM_ARM_LINUX,
+-        '/usr/bin/arm-linux-gnu-gcc-4.7': GCC_4_7 + GCC_PLATFORM_ARM_LINUX,
+-        '/usr/bin/arm-linux-gnu-g++-4.7': GXX_4_7 + GCC_PLATFORM_ARM_LINUX,
++        '/usr/bin/arm-linux-gnu-gcc-4.9': GCC_4_9 + GCC_PLATFORM_ARM_LINUX,
++        '/usr/bin/arm-linux-gnu-g++-4.9': GXX_4_9 + GCC_PLATFORM_ARM_LINUX,
+         '/usr/bin/arm-linux-gnu-gcc-5': GCC_5 + GCC_PLATFORM_ARM_LINUX,
+         '/usr/bin/arm-linux-gnu-g++-5': GXX_5 + GCC_PLATFORM_ARM_LINUX,
++        '/usr/bin/arm-linux-gnu-gcc': DEFAULT_GCC + GCC_PLATFORM_ARM_LINUX,
++        '/usr/bin/arm-linux-gnu-g++': DEFAULT_GXX + GCC_PLATFORM_ARM_LINUX,
++        '/usr/bin/arm-linux-gnu-gcc-7': GCC_7 + GCC_PLATFORM_ARM_LINUX,
++        '/usr/bin/arm-linux-gnu-g++-7': GXX_7 + GCC_PLATFORM_ARM_LINUX,
+     }
+     PATHS.update(LinuxToolchainTest.PATHS)
+-    ARM_GCC_4_7_RESULT = LinuxToolchainTest.GXX_4_7_RESULT
+-    ARM_GCC_5_RESULT = LinuxToolchainTest.GCC_5_RESULT + {
+-        'compiler': '/usr/bin/arm-linux-gnu-gcc-5',
++    ARM_GCC_4_9_RESULT = LinuxToolchainTest.GCC_4_9_RESULT
++    ARM_GXX_4_9_RESULT = LinuxToolchainTest.GXX_4_9_RESULT
++    ARM_GCC_5_RESULT = LinuxToolchainTest.GCC_5_RESULT
++    ARM_GXX_5_RESULT = LinuxToolchainTest.GXX_5_RESULT
++    ARM_DEFAULT_GCC_RESULT = LinuxToolchainTest.DEFAULT_GCC_RESULT + {
++        'compiler': '/usr/bin/arm-linux-gnu-gcc',
++    }
++    ARM_DEFAULT_GXX_RESULT = LinuxToolchainTest.DEFAULT_GXX_RESULT + {
++        'compiler': '/usr/bin/arm-linux-gnu-g++',
+     }
+-    ARM_GXX_5_RESULT = LinuxToolchainTest.GXX_5_RESULT + {
+-        'compiler': '/usr/bin/arm-linux-gnu-g++-5',
++    ARM_GCC_7_RESULT = LinuxToolchainTest.GCC_7_RESULT + {
++        'compiler': '/usr/bin/arm-linux-gnu-gcc-7',
+     }
+-    CLANG_3_6_RESULT = LinuxToolchainTest.CLANG_3_6_RESULT
+-    CLANGXX_3_6_RESULT = LinuxToolchainTest.CLANGXX_3_6_RESULT
+-    GCC_4_9_RESULT = LinuxToolchainTest.GCC_4_9_RESULT
+-    GXX_4_9_RESULT = LinuxToolchainTest.GXX_4_9_RESULT
++    ARM_GXX_7_RESULT = LinuxToolchainTest.GXX_7_RESULT + {
++        'compiler': '/usr/bin/arm-linux-gnu-g++-7',
++    }
++    DEFAULT_CLANG_RESULT = LinuxToolchainTest.DEFAULT_CLANG_RESULT
++    DEFAULT_CLANGXX_RESULT = LinuxToolchainTest.DEFAULT_CLANGXX_RESULT
++    DEFAULT_GCC_RESULT = LinuxToolchainTest.DEFAULT_GCC_RESULT
++    DEFAULT_GXX_RESULT = LinuxToolchainTest.DEFAULT_GXX_RESULT
+ 
+     little_endian = FakeCompiler(GCC_PLATFORM_LINUX,
+                                  GCC_PLATFORM_LITTLE_ENDIAN)
+     big_endian = FakeCompiler(GCC_PLATFORM_LINUX, GCC_PLATFORM_BIG_ENDIAN)
+ 
+     PLATFORMS = {
+         'i686-pc-linux-gnu': GCC_PLATFORM_X86_LINUX,
+         'x86_64-pc-linux-gnu': GCC_PLATFORM_X86_64_LINUX,
+@@ -1199,27 +1223,27 @@ class LinuxCrossCompileToolchainTest(Bas
+         PLATFORMS['mips64-unknown-linux-gnuabi64'] + GCC_PLATFORM_LITTLE_ENDIAN
+     PLATFORMS['mipsel-unknown-linux-gnu'] = \
+         PLATFORMS['mips-unknown-linux-gnu'] + GCC_PLATFORM_LITTLE_ENDIAN
+ 
+     def do_test_cross_gcc_32_64(self, host, target):
+         self.HOST = host
+         self.TARGET = target
+         paths = {
+-            '/usr/bin/gcc': GCC_4_9 + self.PLATFORMS[host],
+-            '/usr/bin/g++': GXX_4_9 + self.PLATFORMS[host],
++            '/usr/bin/gcc': DEFAULT_GCC + self.PLATFORMS[host],
++            '/usr/bin/g++': DEFAULT_GXX + self.PLATFORMS[host],
+         }
+         cross_flags = {
+             'flags': ['-m64' if '64' in target else '-m32']
+         }
+         self.do_toolchain_test(paths, {
+-            'c_compiler': self.GCC_4_9_RESULT + cross_flags,
+-            'cxx_compiler': self.GXX_4_9_RESULT + cross_flags,
+-            'host_c_compiler': self.GCC_4_9_RESULT,
+-            'host_cxx_compiler': self.GXX_4_9_RESULT,
++            'c_compiler': self.DEFAULT_GCC_RESULT + cross_flags,
++            'cxx_compiler': self.DEFAULT_GXX_RESULT + cross_flags,
++            'host_c_compiler': self.DEFAULT_GCC_RESULT,
++            'host_cxx_compiler': self.DEFAULT_GXX_RESULT,
+         })
+         self.HOST = LinuxCrossCompileToolchainTest.HOST
+         self.TARGET = LinuxCrossCompileToolchainTest.TARGET
+ 
+     def test_cross_x86_x64(self):
+         self.do_test_cross_gcc_32_64(
+             'i686-pc-linux-gnu', 'x86_64-pc-linux-gnu')
+         self.do_test_cross_gcc_32_64(
+@@ -1239,147 +1263,147 @@ class LinuxCrossCompileToolchainTest(Bas
+ 
+     def do_test_cross_gcc(self, host, target):
+         self.HOST = host
+         self.TARGET = target
+         host_cpu = host.split('-')[0]
+         cpu, manufacturer, os = target.split('-', 2)
+         toolchain_prefix = '/usr/bin/%s-%s' % (cpu, os)
+         paths = {
+-            '/usr/bin/gcc': GCC_4_9 + self.PLATFORMS[host],
+-            '/usr/bin/g++': GXX_4_9 + self.PLATFORMS[host],
++            '/usr/bin/gcc': DEFAULT_GCC + self.PLATFORMS[host],
++            '/usr/bin/g++': DEFAULT_GXX + self.PLATFORMS[host],
+         }
+         self.do_toolchain_test(paths, {
+             'c_compiler': ('Target C compiler target CPU (%s) '
+                            'does not match --target CPU (%s)'
+                            % (host_cpu, cpu)),
+         })
+ 
+         paths.update({
+-            '%s-gcc' % toolchain_prefix: GCC_4_9 + self.PLATFORMS[target],
+-            '%s-g++' % toolchain_prefix: GXX_4_9 + self.PLATFORMS[target],
++            '%s-gcc' % toolchain_prefix: DEFAULT_GCC + self.PLATFORMS[target],
++            '%s-g++' % toolchain_prefix: DEFAULT_GXX + self.PLATFORMS[target],
+         })
+         self.do_toolchain_test(paths, {
+-            'c_compiler': self.GCC_4_9_RESULT + {
++            'c_compiler': self.DEFAULT_GCC_RESULT + {
+                 'compiler': '%s-gcc' % toolchain_prefix,
+             },
+-            'cxx_compiler': self.GXX_4_9_RESULT + {
++            'cxx_compiler': self.DEFAULT_GXX_RESULT + {
+                 'compiler': '%s-g++' % toolchain_prefix,
+             },
+-            'host_c_compiler': self.GCC_4_9_RESULT,
+-            'host_cxx_compiler': self.GXX_4_9_RESULT,
++            'host_c_compiler': self.DEFAULT_GCC_RESULT,
++            'host_cxx_compiler': self.DEFAULT_GXX_RESULT,
+         })
+         self.HOST = LinuxCrossCompileToolchainTest.HOST
+         self.TARGET = LinuxCrossCompileToolchainTest.TARGET
+ 
+     def test_cross_gcc_misc(self):
+         for target in self.PLATFORMS:
+             if not target.endswith('-pc-linux-gnu'):
+                 self.do_test_cross_gcc('x86_64-pc-linux-gnu', target)
+ 
+     def test_cannot_cross(self):
+         self.TARGET = 'mipsel-unknown-linux-gnu'
+ 
+         paths = {
+-            '/usr/bin/gcc': GCC_4_9 + self.PLATFORMS['mips-unknown-linux-gnu'],
+-            '/usr/bin/g++': GXX_4_9 + self.PLATFORMS['mips-unknown-linux-gnu'],
++            '/usr/bin/gcc': DEFAULT_GCC + self.PLATFORMS['mips-unknown-linux-gnu'],
++            '/usr/bin/g++': DEFAULT_GXX + self.PLATFORMS['mips-unknown-linux-gnu'],
+         }
+         self.do_toolchain_test(paths, {
+             'c_compiler': ('Target C compiler target endianness (big) '
+                            'does not match --target endianness (little)'),
+         })
+         self.TARGET = LinuxCrossCompileToolchainTest.TARGET
+ 
+     def test_overridden_cross_gcc(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.ARM_GCC_5_RESULT,
+-            'cxx_compiler': self.ARM_GXX_5_RESULT,
+-            'host_c_compiler': self.GCC_4_9_RESULT,
+-            'host_cxx_compiler': self.GXX_4_9_RESULT,
++            'c_compiler': self.ARM_GCC_7_RESULT,
++            'cxx_compiler': self.ARM_GXX_7_RESULT,
++            'host_c_compiler': self.DEFAULT_GCC_RESULT,
++            'host_cxx_compiler': self.DEFAULT_GXX_RESULT,
+         }, environ={
+-            'CC': 'arm-linux-gnu-gcc-5',
+-            'CXX': 'arm-linux-gnu-g++-5',
++            'CC': 'arm-linux-gnu-gcc-7',
++            'CXX': 'arm-linux-gnu-g++-7',
+         })
+ 
+     def test_overridden_unsupported_cross_gcc(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.ARM_GCC_4_7_RESULT,
++            'c_compiler': self.ARM_GCC_4_9_RESULT,
+         }, environ={
+-            'CC': 'arm-linux-gnu-gcc-4.7',
+-            'CXX': 'arm-linux-gnu-g++-4.7',
++            'CC': 'arm-linux-gnu-gcc-4.9',
++            'CXX': 'arm-linux-gnu-g++-4.9',
+         })
+ 
+     def test_guess_cross_cxx(self):
+         # When CXX is not set, we guess it from CC.
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.ARM_GCC_5_RESULT,
+-            'cxx_compiler': self.ARM_GXX_5_RESULT,
+-            'host_c_compiler': self.GCC_4_9_RESULT,
+-            'host_cxx_compiler': self.GXX_4_9_RESULT,
++            'c_compiler': self.ARM_GCC_7_RESULT,
++            'cxx_compiler': self.ARM_GXX_7_RESULT,
++            'host_c_compiler': self.DEFAULT_GCC_RESULT,
++            'host_cxx_compiler': self.DEFAULT_GXX_RESULT,
+         }, environ={
+-            'CC': 'arm-linux-gnu-gcc-5',
++            'CC': 'arm-linux-gnu-gcc-7',
+         })
+ 
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.ARM_GCC_5_RESULT,
+-            'cxx_compiler': self.ARM_GXX_5_RESULT,
+-            'host_c_compiler': self.CLANG_3_6_RESULT,
+-            'host_cxx_compiler': self.CLANGXX_3_6_RESULT,
++            'c_compiler': self.ARM_DEFAULT_GCC_RESULT,
++            'cxx_compiler': self.ARM_DEFAULT_GXX_RESULT,
++            'host_c_compiler': self.DEFAULT_CLANG_RESULT,
++            'host_cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
+         }, environ={
+-            'CC': 'arm-linux-gnu-gcc-5',
++            'CC': 'arm-linux-gnu-gcc',
+             'HOST_CC': 'clang',
+         })
+ 
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.ARM_GCC_5_RESULT,
+-            'cxx_compiler': self.ARM_GXX_5_RESULT,
+-            'host_c_compiler': self.CLANG_3_6_RESULT,
+-            'host_cxx_compiler': self.CLANGXX_3_6_RESULT,
++            'c_compiler': self.ARM_DEFAULT_GCC_RESULT,
++            'cxx_compiler': self.ARM_DEFAULT_GXX_RESULT,
++            'host_c_compiler': self.DEFAULT_CLANG_RESULT,
++            'host_cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
+         }, environ={
+-            'CC': 'arm-linux-gnu-gcc-5',
+-            'CXX': 'arm-linux-gnu-g++-5',
++            'CC': 'arm-linux-gnu-gcc',
++            'CXX': 'arm-linux-gnu-g++',
+             'HOST_CC': 'clang',
+         })
+ 
+     def test_cross_clang(self):
+-        cross_clang_result = self.CLANG_3_6_RESULT + {
++        cross_clang_result = self.DEFAULT_CLANG_RESULT + {
+             'flags': ['--target=arm-linux-gnu'],
+         }
+-        cross_clangxx_result = self.CLANGXX_3_6_RESULT + {
++        cross_clangxx_result = self.DEFAULT_CLANGXX_RESULT + {
+             'flags': ['--target=arm-linux-gnu'],
+         }
+         self.do_toolchain_test(self.PATHS, {
+             'c_compiler': cross_clang_result,
+             'cxx_compiler': cross_clangxx_result,
+-            'host_c_compiler': self.CLANG_3_6_RESULT,
+-            'host_cxx_compiler': self.CLANGXX_3_6_RESULT,
++            'host_c_compiler': self.DEFAULT_CLANG_RESULT,
++            'host_cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
+         }, environ={
+             'CC': 'clang',
+             'HOST_CC': 'clang',
+         })
+ 
+         self.do_toolchain_test(self.PATHS, {
+             'c_compiler': cross_clang_result,
+             'cxx_compiler': cross_clangxx_result,
+-            'host_c_compiler': self.CLANG_3_6_RESULT,
+-            'host_cxx_compiler': self.CLANGXX_3_6_RESULT,
++            'host_c_compiler': self.DEFAULT_CLANG_RESULT,
++            'host_cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
+         }, environ={
+             'CC': 'clang',
+         })
+ 
+     def test_cross_atypical_clang(self):
+         paths = dict(self.PATHS)
+         paths.update({
+             '/usr/bin/afl-clang-fast': paths['/usr/bin/clang'],
+             '/usr/bin/afl-clang-fast++': paths['/usr/bin/clang++'],
+         })
+-        afl_clang_result = self.CLANG_3_6_RESULT + {
++        afl_clang_result = self.DEFAULT_CLANG_RESULT + {
+             'compiler': '/usr/bin/afl-clang-fast',
+         }
+-        afl_clangxx_result = self.CLANGXX_3_6_RESULT + {
++        afl_clangxx_result = self.DEFAULT_CLANGXX_RESULT + {
+             'compiler': '/usr/bin/afl-clang-fast++',
+         }
+         self.do_toolchain_test(paths, {
+             'c_compiler': afl_clang_result + {
+                 'flags': ['--target=arm-linux-gnu'],
+             },
+             'cxx_compiler': afl_clangxx_result + {
+                 'flags': ['--target=arm-linux-gnu'],
+@@ -1390,29 +1414,29 @@ class LinuxCrossCompileToolchainTest(Bas
+             'CC': 'afl-clang-fast',
+             'CXX': 'afl-clang-fast++',
+         })
+ 
+ 
+ class OSXCrossToolchainTest(BaseToolchainTest):
+     TARGET = 'i686-apple-darwin11.2.0'
+     PATHS = LinuxToolchainTest.PATHS
+-    CLANG_3_6_RESULT = LinuxToolchainTest.CLANG_3_6_RESULT
+-    CLANGXX_3_6_RESULT = LinuxToolchainTest.CLANGXX_3_6_RESULT
++    DEFAULT_CLANG_RESULT = LinuxToolchainTest.DEFAULT_CLANG_RESULT
++    DEFAULT_CLANGXX_RESULT = LinuxToolchainTest.DEFAULT_CLANGXX_RESULT
+ 
+     def test_osx_cross(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.CLANG_3_6_RESULT + {
++            'c_compiler': self.DEFAULT_CLANG_RESULT + {
+                 'flags': ['--target=i686-darwin11.2.0'],
+             },
+-            'cxx_compiler': self.CLANGXX_3_6_RESULT + {
++            'cxx_compiler': self.DEFAULT_CLANGXX_RESULT + {
+                 'flags': ['--target=i686-darwin11.2.0'],
+             },
+-            'host_c_compiler': self.CLANG_3_6_RESULT,
+-            'host_cxx_compiler': self.CLANGXX_3_6_RESULT,
++            'host_c_compiler': self.DEFAULT_CLANG_RESULT,
++            'host_cxx_compiler': self.DEFAULT_CLANGXX_RESULT,
+         }, environ={
+             'CC': 'clang',
+         })
+ 
+     def test_cannot_osx_cross(self):
+         self.do_toolchain_test(self.PATHS, {
+             'c_compiler': 'Target C compiler target kernel (Linux) does not '
+                           'match --target kernel (Darwin)',
+@@ -1420,26 +1444,26 @@ class OSXCrossToolchainTest(BaseToolchai
+             'CC': 'gcc',
+         })
+ 
+ 
+ class OpenBSDToolchainTest(BaseToolchainTest):
+     HOST = 'x86_64-unknown-openbsd6.1'
+     TARGET = 'x86_64-unknown-openbsd6.1'
+     PATHS = {
+-        '/usr/bin/gcc': GCC_4_9 + GCC_PLATFORM_X86_64 + GCC_PLATFORM_OPENBSD,
+-        '/usr/bin/g++': GXX_4_9 + GCC_PLATFORM_X86_64 + GCC_PLATFORM_OPENBSD,
++        '/usr/bin/gcc': DEFAULT_GCC + GCC_PLATFORM_X86_64 + GCC_PLATFORM_OPENBSD,
++        '/usr/bin/g++': DEFAULT_GXX + GCC_PLATFORM_X86_64 + GCC_PLATFORM_OPENBSD,
+     }
+-    GCC_4_9_RESULT = LinuxToolchainTest.GCC_4_9_RESULT
+-    GXX_4_9_RESULT = LinuxToolchainTest.GXX_4_9_RESULT
++    DEFAULT_GCC_RESULT = LinuxToolchainTest.DEFAULT_GCC_RESULT
++    DEFAULT_GXX_RESULT = LinuxToolchainTest.DEFAULT_GXX_RESULT
+ 
+     def test_gcc(self):
+         self.do_toolchain_test(self.PATHS, {
+-            'c_compiler': self.GCC_4_9_RESULT,
+-            'cxx_compiler': self.GXX_4_9_RESULT,
++            'c_compiler': self.DEFAULT_GCC_RESULT,
++            'cxx_compiler': self.DEFAULT_GXX_RESULT,
+         })
+ 
+ 
+ class RustTest(BaseConfigureTest):
+     def invoke_cargo(self, stdin, args):
+         if args == ('--version', '--verbose'):
+             return 0, 'cargo 2.0\nrelease: 2.0', ''
+         raise NotImplementedError('unsupported arguments')

+ 354 - 0
rel-257/ian/patches/1445024-1-61a1.patch

@@ -0,0 +1,354 @@
+# HG changeset patch
+# User Jeff Walden <jwalden@mit.edu>
+# Date 1520392918 28800
+# Node ID 491149fb04c71c625176a9769d142181f95bdf5d
+# Parent  d1b9f0cb574703ca7168e12d38722e82c69a8ae9
+Bug 1445024 - Implement mozilla::WrappingAdd.  r=froydnj
+
+diff --git a/mfbt/HashFunctions.h b/mfbt/HashFunctions.h
+--- a/mfbt/HashFunctions.h
++++ b/mfbt/HashFunctions.h
+@@ -309,29 +309,28 @@ class HashCodeScrambler {
+       mV0 ^= aM;
+ 
+       // 3. Finalization.
+       mV2 ^= 0xff;
+       for (int i = 0; i < 3; i++) sipRound();
+       return mV0 ^ mV1 ^ mV2 ^ mV3;
+     }
+ 
+-    MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
+     void sipRound() {
+-      mV0 += mV1;
++      mV0 = WrappingAdd(mV0, mV1);
+       mV1 = RotateLeft(mV1, 13);
+       mV1 ^= mV0;
+       mV0 = RotateLeft(mV0, 32);
+-      mV2 += mV3;
++      mV2 = WrappingAdd(mV2, mV3);
+       mV3 = RotateLeft(mV3, 16);
+       mV3 ^= mV2;
+-      mV0 += mV3;
++      mV0 = WrappingAdd(mV0, mV3);
+       mV3 = RotateLeft(mV3, 21);
+       mV3 ^= mV0;
+-      mV2 += mV1;
++      mV2 = WrappingAdd(mV2, mV1);
+       mV1 = RotateLeft(mV1, 17);
+       mV1 ^= mV2;
+       mV2 = RotateLeft(mV2, 32);
+     }
+ 
+     uint64_t mV0, mV1, mV2, mV3;
+   };
+ };
+diff --git a/mfbt/WrappingOperations.h b/mfbt/WrappingOperations.h
+--- a/mfbt/WrappingOperations.h
++++ b/mfbt/WrappingOperations.h
+@@ -85,16 +85,87 @@ template <typename UnsignedType>
+ inline constexpr typename detail::WrapToSignedHelper<UnsignedType>::SignedType
+ WrapToSigned(UnsignedType aValue) {
+   return detail::WrapToSignedHelper<UnsignedType>::compute(aValue);
+ }
+ 
+ namespace detail {
+ 
+ template <typename T>
++struct WrappingAddHelper {
++private:
++  using UnsignedT = typename MakeUnsigned<T>::Type;
++
++  static T toResult(UnsignedT aSum) {
++    // We could always return WrapToSigned and rely on unsigned conversion
++    // undoing the wrapping when |T| is unsigned, but this seems clearer.
++    return IsSigned<T>::value
++           ? WrapToSigned(aSum)
++           : aSum;
++  }
++
++public:
++  MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
++  static T compute(T aX, T aY) {
++    // |mozilla::WrappingAdd| isn't constexpr because MSVC warns about well-
++    // defined unsigned integer overflows that may happen here.
++    // https://msdn.microsoft.com/en-us/library/4kze989h.aspx  And constexpr
++    // seems to cause the warning to be emitted at |WrappingAdd| call *sites*
++    // instead of here, so #pragmas are ineffective.
++    //
++    // https://stackoverflow.com/questions/37658794/integer-constant-overflow-warning-in-constexpr
++    //
++    // If/when MSVC fix this bug, we should make these functions constexpr.
++    return toResult(static_cast<UnsignedT>(aX) + static_cast<UnsignedT>(aY));
++  }
++};
++
++} // namespace detail
++
++/**
++ * Add two integers of the same type, and return the result converted to
++ * that type using wraparound semantics.  This function:
++ *
++ *   1) makes explicit the desire for and dependence upon wraparound semantics,
++ *   2) provides wraparound semantics *safely* with no signed integer overflow
++ *      that would have undefined behavior, and
++ *   3) won't trip up {,un}signed-integer overflow sanitizers (see
++ *      build/autoconf/sanitize.m4) at runtime.
++ *
++ * For N-bit unsigned integer types, this is equivalent to adding the two
++ * numbers, then taking the result mod 2**N:
++ *
++ *   WrappingAdd(uint32_t(42), uint32_t(17)) is 59 (59 mod 2**32);
++ *   WrappingAdd(uint8_t(240), uint8_t(20)) is 4 (260 mod 2**8).
++ *
++ * Use this function for any unsigned addition that can wrap (instead of normal
++ * C++ addition) to play nice with the sanitizers.  WrappingAdd on unsigned
++ * types is otherwise the same as C++ addition.
++ *
++ * For N-bit signed integer types, this is equivalent to adding the two numbers
++ * wrapped to unsigned, taking the sum mod 2**N, then wrapping that number to
++ * the signed range:
++ *
++ *   WrappingAdd(int16_t(32767), int16_t(3)) is -32766 ((32770 mod 2**16) - 2**16);
++ *   WrappingAdd(int8_t(-128), int8_t(-128)) is 0 (256 mod 2**8);
++ *   WrappingAdd(int32_t(-42), int32_t(-17)) is -59 ((8589934533 mod 2**32) - 2**32).
++ *
++ * There is no ready equivalent to this operation in C++, as C++ addition of
++ * signed integers that triggers overflow has undefined behavior.  But it's how
++ * addition *tends* to behave with most compilers, unless an optimization or
++ * similar happens to -- quite permissibly -- trigger different behavior.
++ */
++template <typename T>
++inline T WrappingAdd(T aX, T aY) {
++  return detail::WrappingAddHelper<T>::compute(aX, aY);
++}
++
++namespace detail {
++
++template <typename T>
+ struct WrappingMultiplyHelper {
+  private:
+   using UnsignedT = typename MakeUnsigned<T>::Type;
+ 
+   MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
+   static UnsignedT multiply(UnsignedT aX, UnsignedT aY) {
+     // |mozilla::WrappingMultiply| isn't constexpr because MSVC warns about
+     // well- defined unsigned integer overflows that may happen here.
+diff --git a/mfbt/tests/TestWrappingOperations.cpp b/mfbt/tests/TestWrappingOperations.cpp
+--- a/mfbt/tests/TestWrappingOperations.cpp
++++ b/mfbt/tests/TestWrappingOperations.cpp
+@@ -4,16 +4,17 @@
+  * 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/. */
+ 
+ #include "mozilla/Assertions.h"
+ #include "mozilla/WrappingOperations.h"
+ 
+ #include <stdint.h>
+ 
++using mozilla::WrappingAdd;
+ using mozilla::WrappingMultiply;
+ using mozilla::WrapToSigned;
+ 
+ // NOTE: In places below |-FOO_MAX - 1| is used instead of |-FOO_MIN| because
+ //       in C++ numeric literals are full expressions -- the |-| in a negative
+ //       number is technically separate.  So with most compilers that limit
+ //       |int| to the signed 32-bit range, something like |-2147483648| is
+ //       operator-() applied to an *unsigned* expression.  And MSVC, at least,
+@@ -64,16 +65,170 @@ static_assert(WrapToSigned(uint64_t(9223
+ template<typename T>
+ inline constexpr bool
+ TestEqual(T aX, T aY)
+ {
+   return aX == aY;
+ }
+ 
+ static void
++TestWrappingAdd8()
++{
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint8_t(0), uint8_t(128)),
++                               uint8_t(128)),
++                     "zero plus anything is anything");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint8_t(17), uint8_t(42)),
++                               uint8_t(59)),
++                     "17 + 42 == 59");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint8_t(255), uint8_t(1)),
++                               uint8_t(0)),
++                     "all bits plus one overflows to zero");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint8_t(128), uint8_t(127)),
++                               uint8_t(255)),
++                     "high bit plus all lower bits is all bits");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint8_t(128), uint8_t(193)),
++                               uint8_t(65)),
++                     "128 + 193 is 256 + 65");
++
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int8_t(0), int8_t(-128)),
++                               int8_t(-128)),
++                     "zero plus anything is anything");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int8_t(123), int8_t(8)),
++                               int8_t(-125)),
++                     "overflow to negative");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int8_t(5), int8_t(-123)),
++                               int8_t(-118)),
++                     "5 - 123 is -118");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int8_t(-85), int8_t(-73)),
++                               int8_t(98)),
++                     "underflow to positive");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int8_t(-128), int8_t(127)),
++                               int8_t(-1)),
++                     "high bit plus all lower bits is -1");
++}
++
++static void
++TestWrappingAdd16()
++{
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint16_t(0), uint16_t(32768)),
++                               uint16_t(32768)),
++                     "zero plus anything is anything");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint16_t(24389), uint16_t(2682)),
++                               uint16_t(27071)),
++                     "24389 + 2682 == 27071");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint16_t(65535), uint16_t(1)),
++                               uint16_t(0)),
++                     "all bits plus one overflows to zero");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint16_t(32768), uint16_t(32767)),
++                               uint16_t(65535)),
++                     "high bit plus all lower bits is all bits");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint16_t(32768), uint16_t(47582)),
++                               uint16_t(14814)),
++                     "32768 + 47582 is 65536 + 14814");
++
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int16_t(0), int16_t(-32768)),
++                               int16_t(-32768)),
++                     "zero plus anything is anything");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int16_t(32765), int16_t(8)),
++                               int16_t(-32763)),
++                     "overflow to negative");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int16_t(5), int16_t(-28933)),
++                               int16_t(-28928)),
++                     "5 - 28933 is -28928");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int16_t(-23892), int16_t(-12893)),
++                               int16_t(28751)),
++                     "underflow to positive");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int16_t(-32768), int16_t(32767)),
++                               int16_t(-1)),
++                     "high bit plus all lower bits is -1");
++}
++
++static void
++TestWrappingAdd32()
++{
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint32_t(0), uint32_t(2147483648)),
++                               uint32_t(2147483648)),
++                     "zero plus anything is anything");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint32_t(1398742328), uint32_t(714192829)),
++                               uint32_t(2112935157)),
++                     "1398742328 + 714192829 == 2112935157");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint32_t(4294967295), uint32_t(1)),
++                               uint32_t(0)),
++                     "all bits plus one overflows to zero");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint32_t(2147483648), uint32_t(2147483647)),
++                               uint32_t(4294967295)),
++                     "high bit plus all lower bits is all bits");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint32_t(2147483648), uint32_t(3146492712)),
++                               uint32_t(999009064)),
++                     "2147483648 + 3146492712 is 4294967296 + 999009064");
++
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int32_t(0), int32_t(-2147483647 - 1)),
++                               int32_t(-2147483647 - 1)),
++                     "zero plus anything is anything");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int32_t(2147483645), int32_t(8)),
++                               int32_t(-2147483643)),
++                     "overflow to negative");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int32_t(257), int32_t(-23947248)),
++                               int32_t(-23946991)),
++                     "257 - 23947248 is -23946991");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int32_t(-2147483220), int32_t(-12893)),
++                               int32_t(2147471183)),
++                     "underflow to positive");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int32_t(-32768), int32_t(32767)),
++                               int32_t(-1)),
++                     "high bit plus all lower bits is -1");
++}
++
++static void
++TestWrappingAdd64()
++{
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint64_t(0), uint64_t(9223372036854775808ULL)),
++                               uint64_t(9223372036854775808ULL)),
++                     "zero plus anything is anything");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint64_t(70368744177664), uint64_t(3740873592)),
++                               uint64_t(70372485051256)),
++                     "70368744177664 + 3740873592 == 70372485051256");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint64_t(18446744073709551615ULL), uint64_t(1)),
++                               uint64_t(0)),
++                     "all bits plus one overflows to zero");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint64_t(9223372036854775808ULL),
++                                           uint64_t(9223372036854775807ULL)),
++                               uint64_t(18446744073709551615ULL)),
++                     "high bit plus all lower bits is all bits");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(uint64_t(14552598638644786479ULL), uint64_t(3894174382537247221ULL)),
++                               uint64_t(28947472482084)),
++                     "9223372036854775808 + 3146492712 is 18446744073709551616 + 28947472482084");
++
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int64_t(0), int64_t(-9223372036854775807LL - 1)),
++                               int64_t(-9223372036854775807LL - 1)),
++                     "zero plus anything is anything");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int64_t(9223372036854775802LL), int64_t(8)),
++                               int64_t(-9223372036854775806LL)),
++                     "overflow to negative");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int64_t(37482739294298742LL), int64_t(-437843573929483498LL)),
++                               int64_t(-400360834635184756LL)),
++                     "37482739294298742 - 437843573929483498 is -400360834635184756");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int64_t(-9127837934058953374LL), int64_t(-4173572032144775807LL)),
++                               int64_t(5145334107505822435L)),
++                     "underflow to positive");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingAdd(int64_t(-9223372036854775807LL - 1), int64_t(9223372036854775807LL)),
++                               int64_t(-1)),
++                     "high bit plus all lower bits is -1");
++}
++
++static void
++TestWrappingAdd()
++{
++  TestWrappingAdd8();
++  TestWrappingAdd16();
++  TestWrappingAdd32();
++  TestWrappingAdd64();
++}
++
++static void
+ TestWrappingMultiply8()
+ {
+   MOZ_RELEASE_ASSERT(TestEqual(WrappingMultiply(uint8_t(0), uint8_t(128)),
+                                uint8_t(0)),
+                      "zero times anything is zero");
+   MOZ_RELEASE_ASSERT(TestEqual(WrappingMultiply(uint8_t(128), uint8_t(1)),
+                                uint8_t(128)),
+                      "1 times anything is anything");
+@@ -232,17 +387,24 @@ TestWrappingMultiply64()
+                                int64_t(-9223372036854775807 - 1)),
+                      "multiply that populates the sign bit produces minval");
+   MOZ_RELEASE_ASSERT(TestEqual(WrappingMultiply(int64_t(9223372036854775807),
+                                                 int64_t(9223372036854775807)),
+                                int64_t(1)),
+                      "multiplying maxvals overflows all the way to 1");
+ }
+ 
+-int
+-main()
++static void
++TestWrappingMultiply()
+ {
+   TestWrappingMultiply8();
+   TestWrappingMultiply16();
+   TestWrappingMultiply32();
+   TestWrappingMultiply64();
++}
++
++int
++main()
++{
++  TestWrappingAdd();
++  TestWrappingMultiply();
+   return 0;
+ }

+ 260 - 0
rel-257/ian/patches/1445024-2-61a1.patch

@@ -0,0 +1,260 @@
+# HG changeset patch
+# User Jeff Walden <jwalden@mit.edu>
+# Date 1520884599 25200
+# Node ID 99f24cb57f64dde82d9bcf357a5dfbbfc7761e0c
+# Parent  dbef1d3c2e3ae18da353c8834d4bd64a627feac3
+Bug 1445024 - Consolidate some WrappingOperations.h comments and implementation bits.  r=froydnj
+
+diff --git a/mfbt/WrappingOperations.h b/mfbt/WrappingOperations.h
+--- a/mfbt/WrappingOperations.h
++++ b/mfbt/WrappingOperations.h
+@@ -1,18 +1,29 @@
+ /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+ /* vim: set ts=8 sts=2 et sw=2 tw=80: */
+ /* This Source Code Form is subject to the terms of the Mozilla Public
+  * 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/. */
+ 
+ /*
+- * Math operations that implement wraparound semantics on overflow or underflow
+- * without performing C++ undefined behavior or tripping up compiler-based
+- * integer-overflow sanitizers.
++ * Math operations that implement wraparound semantics on overflow or underflow.
++ *
++ * While in some cases (but not all of them!) plain old C++ operators and casts
++ * will behave just like these functions, there are three reasons you should use
++ * these functions:
++ *
++ *   1) These functions make *explicit* the desire for and dependence upon
++ *      wraparound semantics, just as Rust's i32::wrapping_add and similar
++ *      functions explicitly produce wraparound in Rust.
++ *   2) They implement this functionality *safely*, without invoking signed
++ *      integer overflow that has undefined behavior in C++.
++ *   3) They play nice with compiler-based integer-overflow sanitizers (see
++ *      build/autoconf/sanitize.m4), that in appropriately configured builds
++ *      verify at runtime that integral arithmetic doesn't overflow.
+  */
+ 
+ #ifndef mozilla_WrappingOperations_h
+ #define mozilla_WrappingOperations_h
+ 
+ #include "mozilla/Attributes.h"
+ #include "mozilla/TypeTraits.h"
+ 
+@@ -82,167 +93,134 @@ struct WrapToSignedHelper {
+  * happening.
+  */
+ template <typename UnsignedType>
+ inline constexpr typename detail::WrapToSignedHelper<UnsignedType>::SignedType
+ WrapToSigned(UnsignedType aValue) {
+   return detail::WrapToSignedHelper<UnsignedType>::compute(aValue);
+ }
+ 
++// The |mozilla::Wrapping*| functions aren't constexpr because MSVC warns about
++// well-defined unsigned integer overflows that may occur within the constexpr
++// math.  If/when MSVC fix this bug, we should make them all constexpr.
++//
++//   https://msdn.microsoft.com/en-us/library/4kze989h.aspx (C4307)
++//   https://developercommunity.visualstudio.com/content/problem/211134/unsigned-integer-overflows-in-constexpr-functionsa.html (bug report)
++//
++// For now there's no practical, readable way to avoid such overflows in pure
++// C++.  And we can't add narrow #pragmas where overflow can occur to disable
++// the warnings, because constexpr apparently causes the warning to be emitted
++// at the outermost call *sites* (so every user of |mozilla::Wrapping*| would
++// have to add them).
++
+ namespace detail {
+ 
+ template <typename T>
++inline constexpr T ToResult(typename MakeUnsigned<T>::Type aUnsigned) {
++  // We could *always* return WrapToSigned and rely on unsigned conversion to
++  // undo the wrapping when |T| is unsigned, but this seems clearer.
++  return IsSigned<T>::value ? WrapToSigned(aUnsigned) : aUnsigned;
++}
++
++template <typename T>
+ struct WrappingAddHelper {
+ private:
+   using UnsignedT = typename MakeUnsigned<T>::Type;
+ 
+-  static T toResult(UnsignedT aSum) {
+-    // We could always return WrapToSigned and rely on unsigned conversion
+-    // undoing the wrapping when |T| is unsigned, but this seems clearer.
+-    return IsSigned<T>::value
+-           ? WrapToSigned(aSum)
+-           : aSum;
+-  }
+-
+ public:
+   MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
+   static T compute(T aX, T aY) {
+-    // |mozilla::WrappingAdd| isn't constexpr because MSVC warns about well-
+-    // defined unsigned integer overflows that may happen here.
+-    // https://msdn.microsoft.com/en-us/library/4kze989h.aspx  And constexpr
+-    // seems to cause the warning to be emitted at |WrappingAdd| call *sites*
+-    // instead of here, so #pragmas are ineffective.
+-    //
+-    // https://stackoverflow.com/questions/37658794/integer-constant-overflow-warning-in-constexpr
+-    //
+-    // If/when MSVC fix this bug, we should make these functions constexpr.
+-    return toResult(static_cast<UnsignedT>(aX) + static_cast<UnsignedT>(aY));
++    return ToResult<T>(static_cast<UnsignedT>(aX) + static_cast<UnsignedT>(aY));
+   }
+ };
+ 
+ } // namespace detail
+ 
+ /**
+- * Add two integers of the same type, and return the result converted to
+- * that type using wraparound semantics.  This function:
+- *
+- *   1) makes explicit the desire for and dependence upon wraparound semantics,
+- *   2) provides wraparound semantics *safely* with no signed integer overflow
+- *      that would have undefined behavior, and
+- *   3) won't trip up {,un}signed-integer overflow sanitizers (see
+- *      build/autoconf/sanitize.m4) at runtime.
++ * Add two integers of the same type and return the result converted to that
++ * type using wraparound semantics, without triggering overflow sanitizers.
+  *
+  * For N-bit unsigned integer types, this is equivalent to adding the two
+  * numbers, then taking the result mod 2**N:
+  *
+  *   WrappingAdd(uint32_t(42), uint32_t(17)) is 59 (59 mod 2**32);
+  *   WrappingAdd(uint8_t(240), uint8_t(20)) is 4 (260 mod 2**8).
+  *
+- * Use this function for any unsigned addition that can wrap (instead of normal
+- * C++ addition) to play nice with the sanitizers.  WrappingAdd on unsigned
+- * types is otherwise the same as C++ addition.
++ * Unsigned WrappingAdd acts exactly like C++ unsigned addition.
+  *
+  * For N-bit signed integer types, this is equivalent to adding the two numbers
+- * wrapped to unsigned, taking the sum mod 2**N, then wrapping that number to
+- * the signed range:
++ * wrapped to unsigned, then wrapping the sum mod 2**N to the signed range:
+  *
+  *   WrappingAdd(int16_t(32767), int16_t(3)) is -32766 ((32770 mod 2**16) - 2**16);
+  *   WrappingAdd(int8_t(-128), int8_t(-128)) is 0 (256 mod 2**8);
+  *   WrappingAdd(int32_t(-42), int32_t(-17)) is -59 ((8589934533 mod 2**32) - 2**32).
+  *
+- * There is no ready equivalent to this operation in C++, as C++ addition of
+- * signed integers that triggers overflow has undefined behavior.  But it's how
+- * addition *tends* to behave with most compilers, unless an optimization or
+- * similar happens to -- quite permissibly -- trigger different behavior.
++ * There's no equivalent to this operation in C++, as C++ signed addition that
++ * overflows has undefined behavior.  But it's how such addition *tends* to
++ * behave with most compilers, unless an optimization or similar -- quite
++ * permissibly -- triggers different behavior.
+  */
+ template <typename T>
+ inline T WrappingAdd(T aX, T aY) {
+   return detail::WrappingAddHelper<T>::compute(aX, aY);
+ }
+ 
+ namespace detail {
+ 
+ template <typename T>
+ struct WrappingMultiplyHelper {
+  private:
+   using UnsignedT = typename MakeUnsigned<T>::Type;
+ 
+-  MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
+-  static UnsignedT multiply(UnsignedT aX, UnsignedT aY) {
+-    // |mozilla::WrappingMultiply| isn't constexpr because MSVC warns about
+-    // well- defined unsigned integer overflows that may happen here.
+-    // https://msdn.microsoft.com/en-us/library/4kze989h.aspx  And constexpr
+-    // seems to cause the warning to be emitted at |WrappingMultiply| call
+-    // *sites* instead of here, so these #pragmas are ineffective.
+-    //
+-    // https://stackoverflow.com/questions/37658794/integer-constant-overflow-warning-in-constexpr
+-    //
+-    // If/when MSVC fix this bug, we should make these functions constexpr.
+-
+-    // Begin with |1U| to ensure the overall operation chain is never promoted
+-    // to signed integer operations that might have *signed* integer overflow.
+-    return static_cast<UnsignedT>(1U * aX * aY);
+-  }
+-
+-  static T toResult(UnsignedT aX, UnsignedT aY) {
+-    // We could always return WrapToSigned and rely on unsigned conversion
+-    // undoing the wrapping when |T| is unsigned, but this seems clearer.
+-    return IsSigned<T>::value ? WrapToSigned(multiply(aX, aY))
+-                              : multiply(aX, aY);
+-  }
+-
+  public:
+   MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
+   static T compute(T aX, T aY) {
+-    return toResult(static_cast<UnsignedT>(aX), static_cast<UnsignedT>(aY));
++    // Begin with |1U| to ensure the overall operation chain is never promoted
++    // to signed integer operations that might have *signed* integer overflow.
++    return ToResult<T>(static_cast<UnsignedT>(1U *
++                                              static_cast<UnsignedT>(aX) *
++                                              static_cast<UnsignedT>(aY)));
+   }
+ };
+ 
+ }  // namespace detail
+ 
+ /**
+- * Multiply two integers of the same type, and return the result converted to
+- * that type using wraparound semantics.  This function:
+- *
+- *   1) makes explicit the desire for and dependence upon wraparound semantics,
+- *   2) provides wraparound semantics *safely* with no signed integer overflow
+- *      that would have undefined behavior, and
+- *   3) won't trip up {,un}signed-integer overflow sanitizers (see
+- *      build/autoconf/sanitize.m4) at runtime.
++ * Multiply two integers of the same type and return the result converted to
++ * that type using wraparound semantics, without triggering overflow sanitizers.
+  *
+  * For N-bit unsigned integer types, this is equivalent to multiplying the two
+  * numbers, then taking the result mod 2**N:
+  *
+  *   WrappingMultiply(uint32_t(42), uint32_t(17)) is 714 (714 mod 2**32);
+  *   WrappingMultiply(uint8_t(16), uint8_t(24)) is 128 (384 mod 2**8);
+  *   WrappingMultiply(uint16_t(3), uint16_t(32768)) is 32768 (98304 mod 2*16).
+  *
+- * Use this function for any unsigned multiplication that can wrap (instead of
+- * normal C++ multiplication) to play nice with the sanitizers.  But it's
+- * especially important to use it for uint16_t multiplication: in most compilers
+- * for uint16_t*uint16_t some operand values will trigger signed integer
+- * overflow with undefined behavior!  http://kqueue.org/blog/2013/09/17/cltq/
+- * has the grody details.  Other than that one weird case, WrappingMultiply on
+- * unsigned types is the same as C++ multiplication.
++ * Unsigned WrappingMultiply is *not* identical to C++ multiplication: with most
++ * compilers, in rare cases uint16_t*uint16_t can invoke *signed* integer
++ * overflow having undefined behavior!  http://kqueue.org/blog/2013/09/17/cltq/
++ * has the grody details.  (Some compilers do this for uint32_t, not uint16_t.)
++ * So it's especially important to use WrappingMultiply for wraparound math with
++ * uint16_t.  That quirk aside, this function acts like you *thought* C++
++ * unsigned multiplication always worked.
+  *
+  * For N-bit signed integer types, this is equivalent to multiplying the two
+- * numbers wrapped to unsigned, taking the product mod 2**N, then wrapping that
+- * number to the signed range:
++ * numbers wrapped to unsigned, then wrapping the product mod 2**N to the signed
++ * range:
+  *
+  *   WrappingMultiply(int16_t(-456), int16_t(123)) is
+  *     9448 ((-56088 mod 2**16) + 2**16);
+  *   WrappingMultiply(int32_t(-7), int32_t(-9)) is 63 (63 mod 2**32);
+  *   WrappingMultiply(int8_t(16), int8_t(24)) is -128 ((384 mod 2**8) - 2**8);
+  *   WrappingMultiply(int8_t(16), int8_t(255)) is -16 ((4080 mod 2**8) - 2**8).
+  *
+- * There is no ready equivalent to this operation in C++, as applying C++
+- * multiplication to signed integer types in ways that trigger overflow has
+- * undefined behavior.  However, it's how multiplication *tends* to behave with
+- * most compilers in most situations, even though it's emphatically not required
+- * to do so.
++ * There's no equivalent to this operation in C++, as C++ signed
++ * multiplication that overflows has undefined behavior.  But it's how such
++ * multiplication *tends* to behave with most compilers, unless an optimization
++ * or similar -- quite permissibly -- triggers different behavior.
+  */
+ template <typename T>
+ inline T WrappingMultiply(T aX, T aY) {
+   return detail::WrappingMultiplyHelper<T>::compute(aX, aY);
+ }
+ 
+ } /* namespace mozilla */
+ 

+ 278 - 0
rel-257/ian/patches/1445024-3-61a1.patch

@@ -0,0 +1,278 @@
+# HG changeset patch
+# User Jeff Walden <jwalden@mit.edu>
+# Date 1520392940 28800
+# Node ID 82c94b9264508498233e68f85d27fd8388e66e17
+# Parent  dc341d616796e43da884dc70815eec4a67c96dc4
+Bug 1445024 - Implement mozilla::WrappingSubtract.  r=froydnj
+
+diff --git a/mfbt/WrappingOperations.h b/mfbt/WrappingOperations.h
+--- a/mfbt/WrappingOperations.h
++++ b/mfbt/WrappingOperations.h
+@@ -161,16 +161,62 @@ public:
+ template <typename T>
+ inline T WrappingAdd(T aX, T aY) {
+   return detail::WrappingAddHelper<T>::compute(aX, aY);
+ }
+ 
+ namespace detail {
+ 
+ template <typename T>
++struct WrappingSubtractHelper {
++private:
++  using UnsignedT = typename MakeUnsigned<T>::Type;
++
++public:
++  MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
++  static T compute(T aX, T aY) {
++    return ToResult<T>(static_cast<UnsignedT>(aX) - static_cast<UnsignedT>(aY));
++  }
++};
++
++} // namespace detail
++
++/**
++ * Subtract two integers of the same type and return the result converted to
++ * that type using wraparound semantics, without triggering overflow sanitizers.
++ *
++ * For N-bit unsigned integer types, this is equivalent to subtracting the two
++ * numbers, then taking the result mod 2**N:
++ *
++ *   WrappingSubtract(uint32_t(42), uint32_t(17)) is 29 (29 mod 2**32);
++ *   WrappingSubtract(uint8_t(5), uint8_t(20)) is 241 (-15 mod 2**8).
++ *
++ * Unsigned WrappingSubtract acts exactly like C++ unsigned subtraction.
++ *
++ * For N-bit signed integer types, this is equivalent to subtracting the two
++ * numbers wrapped to unsigned, then wrapping the difference mod 2**N to the
++ * signed range:
++ *
++ *   WrappingSubtract(int16_t(32767), int16_t(-5)) is -32764 ((32772 mod 2**16) - 2**16);
++ *   WrappingSubtract(int8_t(-128), int8_t(127)) is 1 (-255 mod 2**8);
++ *   WrappingSubtract(int32_t(-17), int32_t(-42)) is 25 (25 mod 2**32).
++ *
++ * There's no equivalent to this operation in C++, as C++ signed subtraction
++ * that overflows has undefined behavior.  But it's how such subtraction *tends*
++ * to behave with most compilers, unless an optimization or similar -- quite
++ * permissibly -- triggers different behavior.
++ */
++template <typename T>
++inline T WrappingSubtract(T aX, T aY) {
++  return detail::WrappingSubtractHelper<T>::compute(aX, aY);
++}
++
++namespace detail {
++
++template <typename T>
+ struct WrappingMultiplyHelper {
+  private:
+   using UnsignedT = typename MakeUnsigned<T>::Type;
+ 
+  public:
+   MOZ_NO_SANITIZE_UNSIGNED_OVERFLOW
+   static T compute(T aX, T aY) {
+     // Begin with |1U| to ensure the overall operation chain is never promoted
+diff --git a/mfbt/tests/TestWrappingOperations.cpp b/mfbt/tests/TestWrappingOperations.cpp
+--- a/mfbt/tests/TestWrappingOperations.cpp
++++ b/mfbt/tests/TestWrappingOperations.cpp
+@@ -7,16 +7,17 @@
+ #include "mozilla/Assertions.h"
+ #include "mozilla/WrappingOperations.h"
+ 
+ #include <stdint.h>
+ 
+ using mozilla::WrappingAdd;
+ using mozilla::WrappingMultiply;
+ using mozilla::WrapToSigned;
++using mozilla::WrappingSubtract;
+ 
+ // NOTE: In places below |-FOO_MAX - 1| is used instead of |-FOO_MIN| because
+ //       in C++ numeric literals are full expressions -- the |-| in a negative
+ //       number is technically separate.  So with most compilers that limit
+ //       |int| to the signed 32-bit range, something like |-2147483648| is
+ //       operator-() applied to an *unsigned* expression.  And MSVC, at least,
+ //       warns when you do that.  (The operation is well-defined, but it likely
+ //       doesn't do what was intended.)  So we do the usual workaround for this
+@@ -219,16 +220,170 @@ TestWrappingAdd()
+ {
+   TestWrappingAdd8();
+   TestWrappingAdd16();
+   TestWrappingAdd32();
+   TestWrappingAdd64();
+ }
+ 
+ static void
++TestWrappingSubtract8()
++{
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint8_t(0), uint8_t(128)),
++                               uint8_t(128)),
++                     "zero minus half is half");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint8_t(17), uint8_t(42)),
++                               uint8_t(231)),
++                     "17 - 42 == -25 added to 256 is 231");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint8_t(0), uint8_t(1)),
++                               uint8_t(255)),
++                     "zero underflows to all bits");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint8_t(128), uint8_t(127)),
++                               uint8_t(1)),
++                     "128 - 127 == 1");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint8_t(128), uint8_t(193)),
++                               uint8_t(191)),
++                     "128 - 193 is -65 so -65 + 256 == 191");
++
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int8_t(0), int8_t(-128)),
++                               int8_t(-128)),
++                     "zero minus high bit wraps to high bit");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int8_t(-126), int8_t(4)),
++                               int8_t(126)),
++                     "underflow to positive");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int8_t(5), int8_t(-123)),
++                               int8_t(-128)),
++                     "overflow to negative");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int8_t(-85), int8_t(-73)),
++                               int8_t(-12)),
++                     "negative minus smaller negative");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int8_t(-128), int8_t(127)),
++                               int8_t(1)),
++                     "underflow to 1");
++}
++
++static void
++TestWrappingSubtract16()
++{
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint16_t(0), uint16_t(32768)),
++                               uint16_t(32768)),
++                     "zero minus half is half");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint16_t(24389), uint16_t(2682)),
++                               uint16_t(21707)),
++                     "24389 - 2682 == 21707");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint16_t(0), uint16_t(1)),
++                               uint16_t(65535)),
++                     "zero underflows to all bits");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint16_t(32768), uint16_t(32767)),
++                               uint16_t(1)),
++                     "high bit minus all lower bits is one");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint16_t(32768), uint16_t(47582)),
++                               uint16_t(50722)),
++                     "32768 - 47582 + 65536 is 50722");
++
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int16_t(0), int16_t(-32768)),
++                               int16_t(-32768)),
++                     "zero minus high bit wraps to high bit");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int16_t(-32766), int16_t(4)),
++                               int16_t(32766)),
++                     "underflow to positive");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int16_t(5), int16_t(-28933)),
++                               int16_t(28938)),
++                     "5 - -28933 is 28938");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int16_t(-23892), int16_t(-12893)),
++                               int16_t(-10999)),
++                     "negative minus smaller negative");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int16_t(-32768), int16_t(32767)),
++                               int16_t(1)),
++                     "underflow to 1");
++}
++
++static void
++TestWrappingSubtract32()
++{
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint32_t(0), uint32_t(2147483648)),
++                               uint32_t(2147483648)),
++                     "zero minus half is half");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint32_t(1398742328), uint32_t(714192829)),
++                               uint32_t(684549499)),
++                     "1398742328 - 714192829 == 684549499");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint32_t(0), uint32_t(1)),
++                               uint32_t(4294967295)),
++                     "zero underflows to all bits");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint32_t(2147483648), uint32_t(2147483647)),
++                               uint32_t(1)),
++                     "high bit minus all lower bits is one");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint32_t(2147483648), uint32_t(3146492712)),
++                               uint32_t(3295958232)),
++                     "2147483648 - 3146492712 + 4294967296 is 3295958232");
++
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int32_t(0), int32_t(-2147483647 - 1)),
++                               int32_t(-2147483647 - 1)),
++                     "zero minus high bit wraps to high bit");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int32_t(-2147483646), int32_t(4)),
++                               int32_t(2147483646)),
++                     "underflow to positive");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int32_t(257), int32_t(-23947248)),
++                               int32_t(23947505)),
++                     "257 - -23947248 is 23947505");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int32_t(-2147483220), int32_t(-12893)),
++                               int32_t(-2147470327)),
++                     "negative minus smaller negative");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int32_t(-2147483647 - 1), int32_t(2147483647)),
++                               int32_t(1)),
++                     "underflow to 1");
++}
++
++static void
++TestWrappingSubtract64()
++{
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint64_t(0), uint64_t(9223372036854775808ULL)),
++                               uint64_t(9223372036854775808ULL)),
++                     "zero minus half is half");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint64_t(70368744177664), uint64_t(3740873592)),
++                               uint64_t(70365003304072)),
++                     "70368744177664 - 3740873592 == 70365003304072");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint64_t(0), uint64_t(1)),
++                               uint64_t(18446744073709551615ULL)),
++                     "zero underflows to all bits");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint64_t(9223372036854775808ULL),
++                                                uint64_t(9223372036854775807ULL)),
++                               uint64_t(1)),
++                     "high bit minus all lower bits is one");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(uint64_t(14552598638644786479ULL), uint64_t(3894174382537247221ULL)),
++                               uint64_t(10658424256107539258ULL)),
++                     "14552598638644786479 - 39763621533397112216 is 10658424256107539258L");
++
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int64_t(0), int64_t(-9223372036854775807LL - 1)),
++                               int64_t(-9223372036854775807LL - 1)),
++                     "zero minus high bit wraps to high bit");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int64_t(-9223372036854775802LL), int64_t(8)),
++                               int64_t(9223372036854775806LL)),
++                     "overflow to negative");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int64_t(37482739294298742LL), int64_t(-437843573929483498LL)),
++                               int64_t(475326313223782240)),
++                     "37482739294298742 - -437843573929483498 is 475326313223782240");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int64_t(-9127837934058953374LL), int64_t(-4173572032144775807LL)),
++                               int64_t(-4954265901914177567LL)),
++                     "negative minus smaller negative");
++  MOZ_RELEASE_ASSERT(TestEqual(WrappingSubtract(int64_t(-9223372036854775807LL - 1), int64_t(9223372036854775807LL)),
++                               int64_t(1)),
++                     "underflow to 1");
++}
++
++static void
++TestWrappingSubtract()
++{
++  TestWrappingSubtract8();
++  TestWrappingSubtract16();
++  TestWrappingSubtract32();
++  TestWrappingSubtract64();
++}
++
++static void
+ TestWrappingMultiply8()
+ {
+   MOZ_RELEASE_ASSERT(TestEqual(WrappingMultiply(uint8_t(0), uint8_t(128)),
+                                uint8_t(0)),
+                      "zero times anything is zero");
+   MOZ_RELEASE_ASSERT(TestEqual(WrappingMultiply(uint8_t(128), uint8_t(1)),
+                                uint8_t(128)),
+                      "1 times anything is anything");
+@@ -400,11 +555,12 @@ TestWrappingMultiply()
+   TestWrappingMultiply32();
+   TestWrappingMultiply64();
+ }
+ 
+ int
+ main()
+ {
+   TestWrappingAdd();
++  TestWrappingSubtract();
+   TestWrappingMultiply();
+   return 0;
+ }

+ 236 - 0
rel-257/ian/patches/1445105-61a1.patch

@@ -0,0 +1,236 @@
+# HG changeset patch
+# User Ryan VanderMeulen <ryanvm@gmail.com>
+# Date 1521477721 14400
+# Node ID 34a7d2c7e73e01dd81323c90348a98bd37e259f7
+# Parent  098c774b3b7e1ea42e8d6365fe0881b1fc86dd04
+Bug 1445105 - Remove various MSVC de-optimizations used to work around compiler bugs which are no longer needed. r=dmajor
+
+This reverts the following bugs: 703135, 977538, 1274450, 1403220
+
+diff --git a/js/public/Value.h b/js/public/Value.h
+--- a/js/public/Value.h
++++ b/js/public/Value.h
+@@ -258,27 +258,20 @@ constexpr uint64_t CanonicalizedNaNBits 
+  * Among other properties, this NaN's bit pattern conforms to JS::Value's
+  * bit pattern restrictions.
+  */
+ static MOZ_ALWAYS_INLINE double GenericNaN() {
+   return mozilla::SpecificNaN<double>(detail::CanonicalizedNaNSignBit,
+                                       detail::CanonicalizedNaNSignificand);
+ }
+ 
+-/* MSVC with PGO miscompiles this function. */
+-#if defined(_MSC_VER)
+-#pragma optimize("g", off)
+-#endif
+ static inline double CanonicalizeNaN(double d) {
+   if (MOZ_UNLIKELY(mozilla::IsNaN(d))) return GenericNaN();
+   return d;
+ }
+-#if defined(_MSC_VER)
+-#pragma optimize("", on)
+-#endif
+ 
+ /**
+  * JS::Value is the interface for a single JavaScript Engine value.  A few
+  * general notes on JS::Value:
+  *
+  * - JS::Value has setX() and isX() members for X in
+  *
+  *     { Int32, Double, String, Symbol, Boolean, Undefined, Null,
+diff --git a/layout/generic/nsTextFrame.cpp b/layout/generic/nsTextFrame.cpp
+--- a/layout/generic/nsTextFrame.cpp
++++ b/layout/generic/nsTextFrame.cpp
+@@ -1946,20 +1946,16 @@ void BuildTextRunsScanner::ScanFrame(nsI
+ 
+ nsTextFrame* BuildTextRunsScanner::GetNextBreakBeforeFrame(uint32_t* aIndex) {
+   uint32_t index = *aIndex;
+   if (index >= mLineBreakBeforeFrames.Length()) return nullptr;
+   *aIndex = index + 1;
+   return static_cast<nsTextFrame*>(mLineBreakBeforeFrames.ElementAt(index));
+ }
+ 
+-// Bug 1403220: Suspected MSVC PGO miscompilation
+-#if defined(_MSC_VER) && defined(_M_IX86)
+-#pragma optimize("", off)
+-#endif
+ static gfxFontGroup* GetFontGroupForFrame(
+     const nsIFrame* aFrame, float aFontSizeInflation,
+     nsFontMetrics** aOutFontMetrics = nullptr) {
+   RefPtr<nsFontMetrics> metrics =
+       nsLayoutUtils::GetFontMetricsForFrame(aFrame, aFontSizeInflation);
+   gfxFontGroup* fontGroup = metrics->GetThebesFontGroup();
+ 
+   // Populate outparam before we return:
+@@ -1967,19 +1963,16 @@ static gfxFontGroup* GetFontGroupForFram
+     metrics.forget(aOutFontMetrics);
+   }
+   // XXX this is a bit bogus, we're releasing 'metrics' so the
+   // returned font-group might actually be torn down, although because
+   // of the way the device context caches font metrics, this seems to
+   // not actually happen. But we should fix this.
+   return fontGroup;
+ }
+-#if defined(_MSC_VER) && defined(_M_IX86)
+-#pragma optimize("", on)
+-#endif
+ 
+ static already_AddRefed<DrawTarget> CreateReferenceDrawTarget(
+     const nsTextFrame* aTextFrame) {
+   RefPtr<gfxContext> ctx =
+       aTextFrame->PresShell()->CreateReferenceRenderingContext();
+   RefPtr<DrawTarget> dt = ctx->GetDrawTarget();
+   return dt.forget();
+ }
+diff --git a/layout/xul/tree/nsTreeBodyFrame.cpp b/layout/xul/tree/nsTreeBodyFrame.cpp
+--- a/layout/xul/tree/nsTreeBodyFrame.cpp
++++ b/layout/xul/tree/nsTreeBodyFrame.cpp
+@@ -3478,23 +3478,16 @@ ImgDrawResult nsTreeBodyFrame::PaintImag
+   aRemainingWidth -= imageRect.width;
+   if (!isRTL) {
+     aCurrX += imageRect.width;
+   }
+ 
+   return result;
+ }
+ 
+-// Disable PGO for PaintText because MSVC 2015 seems to have decided
+-// that it can null out the alreadyAddRefed<nsFontMetrics> used to
+-// initialize fontMet after storing fontMet on the stack in the same
+-// space, overwriting fontMet's stack storage with null.
+-#ifdef _MSC_VER
+-#pragma optimize("g", off)
+-#endif
+ ImgDrawResult nsTreeBodyFrame::PaintText(
+     int32_t aRowIndex, nsTreeColumn* aColumn, const nsRect& aTextRect,
+     nsPresContext* aPresContext, gfxContext& aRenderingContext,
+     const nsRect& aDirtyRect, nscoord& aCurrX) {
+   NS_PRECONDITION(aColumn && aColumn->GetFrame(), "invalid column passed");
+ 
+   bool isRTL = StyleVisibility()->mDirection == NS_STYLE_DIRECTION_RTL;
+ 
+@@ -3612,19 +3605,16 @@ ImgDrawResult nsTreeBodyFrame::PaintText
+       textRect.TopLeft() + nsPoint(0, baseline), cellContext);
+ 
+   if (opacity != 1.0f) {
+     aRenderingContext.PopGroupAndBlend();
+   }
+ 
+   return result;
+ }
+-#ifdef _MSC_VER
+-#pragma optimize("", on)
+-#endif
+ 
+ ImgDrawResult nsTreeBodyFrame::PaintCheckbox(int32_t aRowIndex,
+                                              nsTreeColumn* aColumn,
+                                              const nsRect& aCheckboxRect,
+                                              nsPresContext* aPresContext,
+                                              gfxContext& aRenderingContext,
+                                              const nsRect& aDirtyRect) {
+   NS_PRECONDITION(aColumn && aColumn->GetFrame(), "invalid column passed");
+diff --git a/media/libtheora/bug703135.patch b/media/libtheora/bug703135.patch
+deleted file mode 100644
+--- a/media/libtheora/bug703135.patch
++++ /dev/null
+@@ -1,43 +0,0 @@
+-diff --git a/media/libtheora/lib/huffdec.c b/media/libtheora/lib/huffdec.c
+---- a/media/libtheora/lib/huffdec.c
+-+++ b/media/libtheora/lib/huffdec.c
+-@@ -320,16 +320,19 @@ static size_t oc_huff_node_size(int _nbi
+- /*Produces a collapsed-tree representation of the given token list.
+-   _tree: The storage for the collapsed Huffman tree.
+-          This may be NULL to compute the required storage size instead of
+-           constructing the tree.
+-   _tokens:  A list of internal tokens, in the order they are found in the
+-              codebook, and the lengths of their corresponding codewords.
+-   _ntokens: The number of tokens corresponding to this tree node.
+-   Return: The number of words required to store the tree.*/
+-+#if defined(_MSC_VER) && _MSC_VER >= 1700
+-+#pragma optimize( "", off )
+-+#endif
+- static size_t oc_huff_tree_collapse(ogg_int16_t *_tree,
+-  unsigned char _tokens[][2],int _ntokens){
+-   ogg_int16_t   node[34];
+-   unsigned char depth[34];
+-   unsigned char last[34];
+-   size_t        ntree;
+-   int           ti;
+-   int           l;
+-@@ -367,16 +370,19 @@ static size_t oc_huff_tree_collapse(ogg_
+-       /*Pop back up a level of recursion.*/
+-       else if(l-->0)nbits=depth[l+1]-depth[l];
+-     }
+-     while(l>=0);
+-   }
+-   while(l>=0);
+-   return ntree;
+- }
+-+#if defined(_MSC_VER) && _MSC_VER >= 1700
+-+#pragma optimize( "", on )
+-+#endif
+- 
+- /*Unpacks a set of Huffman trees, and reduces them to a collapsed
+-    representation.
+-   _opb:   The buffer to unpack the trees from.
+-   _nodes: The table to fill with the Huffman trees.
+-   Return: 0 on success, or a negative value on error.
+-           The caller is responsible for cleaning up any partially initialized
+-            _nodes on failure.*/
+diff --git a/media/libtheora/lib/huffdec.c b/media/libtheora/lib/huffdec.c
+--- a/media/libtheora/lib/huffdec.c
++++ b/media/libtheora/lib/huffdec.c
+@@ -320,19 +320,16 @@ static size_t oc_huff_node_size(int _nbi
+ /*Produces a collapsed-tree representation of the given token list.
+   _tree: The storage for the collapsed Huffman tree.
+          This may be NULL to compute the required storage size instead of
+           constructing the tree.
+   _tokens:  A list of internal tokens, in the order they are found in the
+              codebook, and the lengths of their corresponding codewords.
+   _ntokens: The number of tokens corresponding to this tree node.
+   Return: The number of words required to store the tree.*/
+-#if defined(_MSC_VER) && _MSC_VER >= 1700
+-#pragma optimize( "", off )
+-#endif
+ static size_t oc_huff_tree_collapse(ogg_int16_t *_tree,
+  unsigned char _tokens[][2],int _ntokens){
+   ogg_int16_t   node[34];
+   unsigned char depth[34];
+   unsigned char last[34];
+   size_t        ntree;
+   int           ti;
+   int           l;
+@@ -370,19 +367,16 @@ static size_t oc_huff_tree_collapse(ogg_
+       /*Pop back up a level of recursion.*/
+       else if(l-->0)nbits=depth[l+1]-depth[l];
+     }
+     while(l>=0);
+   }
+   while(l>=0);
+   return ntree;
+ }
+-#if defined(_MSC_VER) && _MSC_VER >= 1700
+-#pragma optimize( "", on )
+-#endif
+ 
+ /*Unpacks a set of Huffman trees, and reduces them to a collapsed
+    representation.
+   _opb:   The buffer to unpack the trees from.
+   _nodes: The table to fill with the Huffman trees.
+   Return: 0 on success, or a negative value on error.
+           The caller is responsible for cleaning up any partially initialized
+            _nodes on failure.*/
+diff --git a/media/libtheora/update.sh b/media/libtheora/update.sh
+--- a/media/libtheora/update.sh
++++ b/media/libtheora/update.sh
+@@ -77,10 +77,9 @@ cp $1/lib/x86_vc/x86state.c ./lib/x86_vc
+ cp $1/include/theora/theora.h ./include/theora/theora.h
+ cp $1/include/theora/theoradec.h ./include/theora/theoradec.h
+ cp $1/include/theora/theoraenc.h ./include/theora/theoraenc.h
+ cp $1/include/theora/codec.h ./include/theora/codec.h
+ patch -p3 < ./bug625773-r17780.patch
+ patch -p3 < ./bug468275-r18219.patch
+ patch -p3 < ./bug752139-r18031.patch
+ patch -p3 < ./bug752668-r18268.patch
+-patch -p3 < ./bug703135.patch
+ patch -p3 < ./bug920992.patch

+ 154 - 0
rel-257/ian/patches/1445398-61a1.patch

@@ -0,0 +1,154 @@
+# HG changeset patch
+# User Chris Manchester <cmanchester@mozilla.com>
+# Date 1521759792 25200
+# Node ID d2fdb62d06d0f42a412204e0f098d232fe5d8c68
+# Parent  7e6847a36676408c57f5163b663ddd1f814037ba
+Bug 1445398 - Do not re-generate buildid.h for every Tup build. r=mshal
+
+MozReview-Commit-ID: ErkTDOU8lYH
+
+diff --git a/Makefile.in b/Makefile.in
+--- a/Makefile.in
++++ b/Makefile.in
+@@ -141,25 +141,22 @@ ifneq (,$(filter FasterMake+RecursiveMak
+ install-manifests: faster
+ .PHONY: faster
+ faster: install-dist/idl
+ 	$(MAKE) -C faster FASTER_RECURSIVE_MAKE=1
+ endif
+ 
+ .PHONY: tup
+ tup:
+-	$(call BUILDSTATUS,TIERS $(if $(MOZ_ARTIFACT_BUILDS),artifact )make tup)
++	$(call BUILDSTATUS,TIERS $(if $(MOZ_ARTIFACT_BUILDS),artifact )tup)
+ ifdef MOZ_ARTIFACT_BUILDS
+ 	$(call BUILDSTATUS,TIER_START artifact)
+ 	$(MAKE) recurse_artifact
+ 	$(call BUILDSTATUS,TIER_FINISH artifact)
+ endif
+-	$(call BUILDSTATUS,TIER_START make)
+-	$(MAKE) buildid.h source-repo.h
+-	$(call BUILDSTATUS,TIER_FINISH make)
+ 	$(call BUILDSTATUS,TIER_START tup)
+ 	@$(TUP) $(if $(findstring s,$(filter-out --%,$(MAKEFLAGS))),,--verbose)
+ 	$(call BUILDSTATUS,TIER_FINISH tup)
+ 
+ .PHONY: $(addprefix install-,$(install_manifests))
+ $(addprefix install-,$(install_manifests)): install-%: $(install_manifest_depends)
+ ifneq (,$(filter FasterMake+RecursiveMake,$(BUILD_BACKENDS)))
+ 	@# If we're using the hybrid FasterMake/RecursiveMake backend, we want
+diff --git a/python/mozbuild/mozbuild/backend/tup.py b/python/mozbuild/mozbuild/backend/tup.py
+--- a/python/mozbuild/mozbuild/backend/tup.py
++++ b/python/mozbuild/mozbuild/backend/tup.py
+@@ -183,16 +183,20 @@ class TupOnly(CommonBackend, PartialBack
+             '*.py',
+             '*.rs',
+         )
+ 
+         # These are 'group' dependencies - All rules that list these as an output
+         # will be built before any rules that list this as an input.
+         self._installed_idls = '$(MOZ_OBJ_ROOT)/<installed-idls>'
+         self._installed_files = '$(MOZ_OBJ_ROOT)/<installed-files>'
++        # The preprocessor including source-repo.h and buildid.h creates
++        # dependencies that aren't specified by moz.build and cause errors
++        # in Tup. Express these as a group dependency.
++        self._early_generated_files = '$(MOZ_OBJ_ROOT)/<early-generated-files>'
+ 
+     def _get_backend_file(self, relobjdir):
+         objdir = mozpath.normpath(mozpath.join(self.environment.topobjdir, relobjdir))
+         if objdir not in self._backend_files:
+             self._backend_files[objdir] = \
+                     BackendTupfile(objdir, self.environment,
+                                    self.environment.topsrcdir, self.environment.topobjdir)
+         return self._backend_files[objdir]
+@@ -216,24 +220,20 @@ class TupOnly(CommonBackend, PartialBack
+ 
+         consumed = CommonBackend.consume_object(self, obj)
+         if consumed:
+             return True
+ 
+         backend_file = self._get_backend_file_for(obj)
+ 
+         if isinstance(obj, GeneratedFile):
+-            # These files are already generated by make before tup runs.
+-            skip_files = (
+-                'buildid.h',
+-                'source-repo.h',
+-            )
++            skip_files = []
+ 
+             if self.environment.is_artifact_build:
+-                skip_files = skip_files + self._compile_env_gen_files
++                skip_files = self._compile_env_gen_files
+ 
+             for f in obj.outputs:
+                 if any(mozpath.match(f, p) for p in skip_files):
+                     return False
+ 
+             if 'application.ini.h' in obj.outputs:
+                 # application.ini.h is a special case since we need to process
+                 # the FINAL_TARGET_PP_FILES for application.ini before running
+@@ -266,16 +266,22 @@ class TupOnly(CommonBackend, PartialBack
+             self._process_computed_flags(obj, backend_file)
+         elif isinstance(obj, (Sources, GeneratedSources)):
+             backend_file.sources[obj.canonical_suffix].extend(obj.files)
+         elif isinstance(obj, HostSources):
+             backend_file.host_sources[obj.canonical_suffix].extend(obj.files)
+         elif isinstance(obj, VariablePassthru):
+             backend_file.variables = obj.variables
+ 
++        # The top-level Makefile.in still contains our driver target and some
++        # things related to artifact builds, so as a special case ensure the
++        # make backend generates a Makefile there.
++        if obj.objdir == self.environment.topobjdir:
++            return False
++
+         return True
+ 
+     def consume_finished(self):
+         CommonBackend.consume_finished(self)
+ 
+         # The approach here is similar to fastermake.py, but we
+         # simply write out the resulting files here.
+         for target, entries in self._manifest_entries.iteritems():
+@@ -342,17 +348,21 @@ class TupOnly(CommonBackend, PartialBack
+             full_inputs = [f.full_path for f in obj.inputs]
+             cmd.extend(full_inputs)
+             cmd.extend(shell_quote(f) for f in obj.flags)
+ 
+             outputs = []
+             outputs.extend(obj.outputs)
+             outputs.append('%s.pp' % obj.outputs[0])
+ 
+-            extra_outputs = [self._installed_files] if obj.required_for_compile else None
++            if any(f in obj.outputs for f in ('source-repo.h', 'buildid.h')):
++                extra_outputs = [self._early_generated_files]
++            else:
++                extra_outputs = [self._installed_files] if obj.required_for_compile else []
++                full_inputs += [self._early_generated_files]
+ 
+             backend_file.rule(
+                 display='python {script}:{method} -> [%o]'.format(script=obj.script, method=obj.method),
+                 cmd=cmd,
+                 inputs=full_inputs,
+                 outputs=outputs,
+                 extra_outputs=extra_outputs,
+             )
+@@ -506,16 +516,17 @@ class TupOnly(CommonBackend, PartialBack
+ 
+         base_input = mozpath.basename(input_file)
+         if base_input.endswith('.in'):
+             base_input = mozpath.splitext(base_input)[0]
+         output = mozpath.join(destdir, base_input) if destdir else base_input
+ 
+         backend_file.rule(
+             inputs=[input_file],
++            extra_inputs=[self._early_generated_files],
+             display='Preprocess %o',
+             cmd=cmd,
+             outputs=[output],
+         )
+ 
+     def _handle_ipdl_sources(self, ipdl_dir, sorted_ipdl_sources, sorted_nonstatic_ipdl_sources,
+                              sorted_static_ipdl_sources, unified_ipdl_cppsrcs_mapping):
+         # Preferably we wouldn't have to import ipdl, but we need to parse the

+ 30 - 0
rel-257/ian/patches/1445503-61a1.patch

@@ -0,0 +1,30 @@
+# HG changeset patch
+# User Michael Webster <miketwebster@gmail.com>
+# Date 1520981400 -7200
+# Node ID d25f89538c905c647a1e5d513b22b5bcd5ef936d
+# Parent  78f4f38c05b4f557bc61ea4438cc1c0792f12d88
+Bug 1445503 - Use MIN instead of unnecessary CLAMP r=karlt
+CLAMP is unnecessary as the minimum acceptable value is 0, and
+progressPercent is unsigned. CLAMP can trigger the following warning/error in some builds:
+error: comparison of unsigned expression < 0 is always false [-Werror=type-limits]
+
+diff --git a/widget/gtk/nsWindow.cpp b/widget/gtk/nsWindow.cpp
+--- a/widget/gtk/nsWindow.cpp
++++ b/widget/gtk/nsWindow.cpp
+@@ -6439,15 +6439,15 @@ nsWindow::SetProgress(unsigned long prog
+   if (!mIsX11Display) {
+     return;
+   }
+ 
+   if (!mShell) {
+     return;
+   }
+ 
+-  progressPercent = CLAMP(progressPercent, 0, 100);
++  progressPercent = MIN(progressPercent, 100);
+ 
+   set_window_hint_cardinal(GDK_WINDOW_XID(gtk_widget_get_window(mShell)),
+                            PROGRESS_HINT,
+                            progressPercent);
+ #endif // MOZ_X11
+ }

+ 47 - 0
rel-257/ian/patches/1445671-61a1.patch

@@ -0,0 +1,47 @@
+# HG changeset patch
+# User Dão Gottwald <dao@mozilla.com>
+# Date 1524567548 -7200
+# Node ID 7b8e832071f1c1b64d05dd597d692f4d4eb0866e
+# Parent  b5a845e976b6cf54fbfc88abdfb45d8da3cf628e
+Bug 1445671 - Stop using -moz-font-smoothing-background-color for the selected tab when using a lightweight theme. r=mstange
+
+MozReview-Commit-ID: 32ZrF86Xeon
+
+diff --git a/browser/themes/osx/browser.css b/browser/themes/osx/browser.css
+--- a/browser/themes/osx/browser.css
++++ b/browser/themes/osx/browser.css
+@@ -754,17 +754,17 @@ html|input.urlbar-input {
+ :root:-moz-any([inFullscreen], [tabsintitlebar]) #TabsToolbar:not(:-moz-lwtheme) {
+   -moz-appearance: -moz-mac-vibrant-titlebar-dark;
+   -moz-font-smoothing-background-color: -moz-mac-vibrant-titlebar-dark;
+   background-color: #232323;
+   color: hsl(240, 9%, 98%);
+   text-shadow: none;
+ }
+ 
+-.tabbrowser-tab[visuallyselected=true] {
++.tabbrowser-tab[visuallyselected=true]:not(:-moz-lwtheme) {
+   -moz-font-smoothing-background-color: var(--toolbar-bgcolor);
+ }
+ 
+ #tabbrowser-tabs {
+   -moz-box-align: stretch;
+ }
+ 
+ /**
+diff --git a/browser/themes/osx/compacttheme.css b/browser/themes/osx/compacttheme.css
+--- a/browser/themes/osx/compacttheme.css
++++ b/browser/themes/osx/compacttheme.css
+@@ -8,8 +8,12 @@
+ #main-window[tabsintitlebar] #titlebar-content {
+   background: var(--chrome-background-color);
+ }
+ 
+ #TabsToolbar:-moz-lwtheme-darktext {
+   -moz-appearance: -moz-mac-vibrant-titlebar-light;
+   -moz-font-smoothing-background-color: -moz-mac-vibrant-titlebar-light;
+ }
++
++.tabbrowser-tab[visuallyselected=true] {
++  -moz-font-smoothing-background-color: var(--toolbar-bgcolor);
++}

+ 12804 - 0
rel-257/ian/patches/1445731-1-NSS337-61a1.patch

@@ -0,0 +1,12804 @@
+# HG changeset patch
+# User J.C. Jones <jjones@mozilla.com>
+# Date 1521129648 25200
+#      Thu Mar 15 09:00:48 2018 -0700
+# Node ID 30b30a7267c7384e2d091c14a2a01e2f29b4fe9c
+# Parent  1aeaa33a64f9873fdeb8f986ef71ec35aa672347
+Bug 1445731 - land NSS f0d4789c8916 UPGRADE_NSS_RELEASE, r=me
+
+diff --git a/security/nss/.taskcluster.yml b/security/nss/.taskcluster.yml
+--- a/security/nss/.taskcluster.yml
++++ b/security/nss/.taskcluster.yml
+@@ -1,69 +1,77 @@
+-# This file is rendered via JSON-e in a hook with context:
+-#   {
+-#     tasks_for: 'hg-push',
+-#     push: {owner, pushlog_id, pushdate},
+-#     repository: {url, project, level},
+-#     now,
+-#     ownTaskId: // taskId of the task that will be created
+-#   }
+ ---
+-version: 1
++version: 0
++metadata:
++  name: "NSS Continuous Integration"
++  description: "The Taskcluster task graph for the NSS tree"
++  owner: "mozilla-taskcluster-maintenance@mozilla.com"
++  source: {{{source}}}
++
++scopes:
++  # Note the below scopes are insecure however these get overriden on the server
++  # side to whatever scopes are set by mozilla-taskcluster.
++  - queue:*
++  - docker-worker:*
++  - scheduler:*
++
++# Available mustache parameters (see the mozilla-taskcluster source):
++#
++# - owner:          push user (email address)
++# - source:         URL of this YAML file
++# - url:            repository URL
++# - project:        alias for the destination repository (basename of
++#                   the repo url)
++# - level:          SCM level of the destination repository
++#                   (1 = try, 3 = core)
++# - revision:       (short) hg revision of the head of the push
++# - revision_hash:  (long) hg revision of the head of the push
++# - comment:        comment of the push
++# - pushlog_id:     id in the pushlog table of the repository
++#
++# and functions:
++# - as_slugid:      convert a label into a slugId
++# - from_now:       generate a timestamp at a fixed offset from now
++
+ tasks:
+-  - $let:
+-      # sometimes the push user is just `ffxbld` or the like, but we want an
+-      # email-like field..
+-      ownerEmail:
+-        $if: '"@" in push.owner'
+-        then: '${push.owner}'
+-        else: '${push.owner}@noreply.mozilla.org'
+-      # ensure there's no trailing `/` on the repo URL
+-      repoUrl:
+-        $if: 'repository.url[-1] == "/"'
+-        then: {$eval: 'repository.url[:-1]'}
+-        else: {$eval: 'repository.url'}
+-    in:
+-      taskId: '${ownTaskId}'
+-      taskGroupId: '${ownTaskId}'
+-      schedulerId: 'nss-level-${repository.level}'
+-      created: {$fromNow: ''}
+-      deadline: {$fromNow: '1 day'}
+-      expires: {$fromNow: '14 days'}
++  - taskId: '{{#as_slugid}}decision task{{/as_slugid}}'
++    reruns: 3
++    task:
++      created: '{{now}}'
++      deadline: '{{#from_now}}1 day{{/from_now}}'
++      expires: '{{#from_now}}14 days{{/from_now}}'
+ 
+       metadata:
+         owner: mozilla-taskcluster-maintenance@mozilla.com
+-        source: "${repository.url}"
++        source: {{{source}}}
+         name: "NSS Decision Task"
+         description: |
+             The task that creates all of the other tasks in the task graph
+ 
+       workerType: "hg-worker"
+       provisionerId: "aws-provisioner-v1"
+ 
+-      scopes:
+-        - 'assume:repo:${repoUrl[8:]}:branch:default'
+       tags:
+-        createdForUser: "${ownerEmail}"
++        createdForUser: {{owner}}
+ 
+       routes:
+-        - "tc-treeherder-stage.v2.${repository.project}.${push.revision}.${push.pushlog_id}"
+-        - "tc-treeherder.v2.${repository.project}.${push.revision}.${push.pushlog_id}"
++        - "tc-treeherder-stage.v2.{{project}}.{{revision}}.{{pushlog_id}}"
++        - "tc-treeherder.v2.{{project}}.{{revision}}.{{pushlog_id}}"
+ 
+       payload:
+-        # TODO: use nssdev org , not djmitche, once the image is pushed there
+-        image: djmitche/nss-decision:0.0.3
++        image: nssdev/nss-decision:0.0.2
+ 
+         env:
+-          TC_OWNER: "${push.owner}"
+-          TC_SOURCE: "${repository.url}"
+-          TC_PROJECT: ${repository.project}
+-          NSS_PUSHLOG_ID: '${push.pushlog_id}'
+-          NSS_HEAD_REPOSITORY: '${repository.url}'
+-          NSS_HEAD_REVISION: '${push.revision}'
++          TC_OWNER: {{owner}}
++          TC_SOURCE: {{{source}}}
++          TC_PROJECT: {{project}}
++          TC_COMMENT: '{{comment}}'
++          NSS_PUSHLOG_ID: '{{pushlog_id}}'
++          NSS_HEAD_REPOSITORY: '{{{url}}}'
++          NSS_HEAD_REVISION: '{{revision}}'
+ 
+         maxRunTime: 1800
+ 
+         command:
+           - bash
+           - -cx
+           - >
+             bin/checkout.sh &&
+diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO
+--- a/security/nss/TAG-INFO
++++ b/security/nss/TAG-INFO
+@@ -1,1 +1,1 @@
+-NSS_3_36_8_RTM
++f0d4789c8916
+diff --git a/security/nss/automation/abi-check/expected-report-libssl3.so.txt b/security/nss/automation/abi-check/expected-report-libssl3.so.txt
+--- a/security/nss/automation/abi-check/expected-report-libssl3.so.txt
++++ b/security/nss/automation/abi-check/expected-report-libssl3.so.txt
+@@ -1,28 +0,0 @@
+-
+-1 function with some indirect sub-type change:
+-
+-  [C]'function SECStatus SSL_GetChannelInfo(PRFileDesc*, SSLChannelInfo*, PRUintn)' at sslinfo.c:12:1 has some indirect sub-type changes:
+-    parameter 2 of type 'SSLChannelInfo*' has sub-type changes:
+-      in pointed to type 'typedef SSLChannelInfo' at sslt.h:318:1:
+-        underlying type 'struct SSLChannelInfoStr' at sslt.h:251:1 changed:
+-          type size hasn't changed
+-          1 data member change:
+-           type of 'SSLSignatureScheme SSLChannelInfoStr::signatureScheme' changed:
+-             underlying type 'enum __anonymous_enum__' at sslt.h:115:1 changed:
+-               type size hasn't changed
+-               3 enumerator deletions:
+-                 '__anonymous_enum__::ssl_sig_rsa_pss_sha256' value '2052'
+-                 '__anonymous_enum__::ssl_sig_rsa_pss_sha384' value '2053'
+-                 '__anonymous_enum__::ssl_sig_rsa_pss_sha512' value '2054'
+-
+-               6 enumerator insertions:
+-                 '__anonymous_enum__::ssl_sig_rsa_pss_rsae_sha256' value '2052'
+-                 '__anonymous_enum__::ssl_sig_rsa_pss_rsae_sha384' value '2053'
+-                 '__anonymous_enum__::ssl_sig_rsa_pss_rsae_sha512' value '2054'
+-                 '__anonymous_enum__::ssl_sig_rsa_pss_pss_sha256' value '2057'
+-                 '__anonymous_enum__::ssl_sig_rsa_pss_pss_sha384' value '2058'
+-                 '__anonymous_enum__::ssl_sig_rsa_pss_pss_sha512' value '2059'
+-
+-
+-
+-
+diff --git a/security/nss/automation/abi-check/previous-nss-release b/security/nss/automation/abi-check/previous-nss-release
+--- a/security/nss/automation/abi-check/previous-nss-release
++++ b/security/nss/automation/abi-check/previous-nss-release
+@@ -1,1 +1,1 @@
+-NSS_3_35_BRANCH
++NSS_3_36_BRANCH
+diff --git a/security/nss/automation/taskcluster/docker-hacl/Dockerfile b/security/nss/automation/taskcluster/docker-hacl/Dockerfile
+--- a/security/nss/automation/taskcluster/docker-hacl/Dockerfile
++++ b/security/nss/automation/taskcluster/docker-hacl/Dockerfile
+@@ -1,20 +1,20 @@
+ FROM ubuntu:xenial
+ 
+ MAINTAINER Franziskus Kiefer <franziskuskiefer@gmail.com>
+ # Based on the HACL* image from Benjamin Beurdouche and
+ # the original F* formula with Daniel Fabian
+ 
+ # Pinned versions of HACL* (F* and KreMLin are pinned as submodules)
+-ENV haclrepo https://github.com/franziskuskiefer/hacl-star.git
++ENV haclrepo https://github.com/mitls/hacl-star.git
+ 
+ # Define versions of dependencies
+ ENV opamv 4.04.2
+-ENV haclversion 668d6cf274c33bbe2e951e3a84b73f2b6442a51f
++ENV haclversion 426abe1c4e55f3e569bd9815d52bffc4daac44e5
+ 
+ # Install required packages and set versions
+ ADD setup.sh /tmp/setup.sh
+ RUN bash /tmp/setup.sh
+ 
+ # Create user, add scripts.
+ RUN useradd -ms /bin/bash worker
+ WORKDIR /home/worker
+diff --git a/security/nss/automation/taskcluster/scripts/run_hacl.sh b/security/nss/automation/taskcluster/scripts/run_hacl.sh
+--- a/security/nss/automation/taskcluster/scripts/run_hacl.sh
++++ b/security/nss/automation/taskcluster/scripts/run_hacl.sh
+@@ -7,19 +7,16 @@ if [[ $(id -u) -eq 0 ]]; then
+ fi
+ 
+ set -e -x -v
+ 
+ # The docker image this is running in has the HACL* and NSS sources.
+ # The extracted C code from HACL* is already generated and the HACL* tests were
+ # successfully executed.
+ 
+-# Verify Poly1305 (doesn't work in docker image build)
+-make verify -C ~/hacl-star/code/poly1305 -j$(nproc)
+-
+ # Add license header to specs
+ spec_files=($(find ~/hacl-star/specs -type f -name '*.fst'))
+ for f in "${spec_files[@]}"; do
+     cat /tmp/license.txt "$f" > /tmp/tmpfile && mv /tmp/tmpfile "$f"
+ done
+ 
+ # Format the extracted C code.
+ cd ~/hacl-star/snapshots/nss
+diff --git a/security/nss/automation/taskcluster/windows/setup.sh b/security/nss/automation/taskcluster/windows/setup.sh
+--- a/security/nss/automation/taskcluster/windows/setup.sh
++++ b/security/nss/automation/taskcluster/windows/setup.sh
+@@ -18,9 +18,9 @@ hg_clone() {
+         sleep $i
+         hg clone -r "$rev" "$repo" "$dir" && return
+         rm -rf "$dir"
+     done
+     exit 1
+ }
+ 
+ hg_clone https://hg.mozilla.org/build/tools tools default
+-tools/scripts/tooltool/tooltool_wrapper.sh $(dirname $0)/releng.manifest https://tooltool.mozilla-releng.net/ non-existant-file.sh /c/mozilla-build/python/python.exe /c/builds/tooltool.py --authentication-file /c/builds/relengapi.tok -c /c/builds/tooltool_cache
++tools/scripts/tooltool/tooltool_wrapper.sh $(dirname $0)/releng.manifest https://api.pub.build.mozilla.org/tooltool/ non-existant-file.sh /c/mozilla-build/python/python.exe /c/builds/tooltool.py --authentication-file /c/builds/relengapi.tok -c /c/builds/tooltool_cache
+diff --git a/security/nss/cmd/bltest/blapitest.c b/security/nss/cmd/bltest/blapitest.c
+--- a/security/nss/cmd/bltest/blapitest.c
++++ b/security/nss/cmd/bltest/blapitest.c
+@@ -3719,33 +3719,33 @@ main(int argc, char **argv)
+     if (bltest.commands[cmd_RSAPopulateKV].activated) {
+         PORT_Free(cipherInfo);
+         return doRSAPopulateTestKV();
+     }
+ 
+     /* test the RSA_PopulatePrivateKey function */
+     if (bltest.commands[cmd_RSAPopulate].activated) {
+         unsigned int keySize = 1024;
+-        unsigned long exponent = 65537;
++        unsigned long keyExponent = 65537;
+         int rounds = 1;
+         int ret = -1;
+ 
+         if (bltest.options[opt_KeySize].activated) {
+             keySize = PORT_Atoi(bltest.options[opt_KeySize].arg);
+         }
+         if (bltest.options[opt_Rounds].activated) {
+             rounds = PORT_Atoi(bltest.options[opt_Rounds].arg);
+         }
+         if (bltest.options[opt_Exponent].activated) {
+-            exponent = PORT_Atoi(bltest.options[opt_Exponent].arg);
++            keyExponent = PORT_Atoi(bltest.options[opt_Exponent].arg);
+         }
+ 
+         for (i = 0; i < rounds; i++) {
+             printf("Running RSA Populate test round %d\n", i);
+-            ret = doRSAPopulateTest(keySize, exponent);
++            ret = doRSAPopulateTest(keySize, keyExponent);
+             if (ret != 0) {
+                 break;
+             }
+         }
+         if (ret != 0) {
+             fprintf(stderr, "RSA Populate test round %d: FAILED\n", i);
+         }
+         PORT_Free(cipherInfo);
+diff --git a/security/nss/cmd/certutil/certutil.c b/security/nss/cmd/certutil/certutil.c
+--- a/security/nss/cmd/certutil/certutil.c
++++ b/security/nss/cmd/certutil/certutil.c
+@@ -777,27 +777,27 @@ ValidateCert(CERTCertDBHandle *handle, c
+ 
+         rv = CERT_VerifyCertificate(handle, cert, checkSig, usage,
+                                     timeBoundary, pwdata, log, &usage);
+         if (log) {
+             if (log->head == NULL) {
+                 fprintf(stdout, "%s: certificate is valid\n", progName);
+                 GEN_BREAK(SECSuccess)
+             } else {
+-                char *name;
++                char *nick;
+                 CERTVerifyLogNode *node;
+ 
+                 node = log->head;
+                 while (node) {
+                     if (node->cert->nickname != NULL) {
+-                        name = node->cert->nickname;
++                        nick = node->cert->nickname;
+                     } else {
+-                        name = node->cert->subjectName;
++                        nick = node->cert->subjectName;
+                     }
+-                    fprintf(stderr, "%s : %s\n", name,
++                    fprintf(stderr, "%s : %s\n", nick,
+                             SECU_Strerror(node->error));
+                     CERT_DestroyCertificate(node->cert);
+                     node = node->next;
+                 }
+             }
+         } else {
+             if (rv != SECSuccess) {
+                 PRErrorCode perr = PORT_GetError();
+@@ -840,17 +840,17 @@ SECItemToHex(const SECItem *item, char *
+         for (; len > 0; --len, dst += 2) {
+             sprintf(dst, "%02x", *src++);
+         }
+         *dst = '\0';
+     }
+ }
+ 
+ static const char *const keyTypeName[] = {
+-    "null", "rsa", "dsa", "fortezza", "dh", "kea", "ec"
++    "null", "rsa", "dsa", "fortezza", "dh", "kea", "ec", "rsaPss"
+ };
+ 
+ #define MAX_CKA_ID_BIN_LEN 20
+ #define MAX_CKA_ID_STR_LEN 40
+ 
+ /* print key number, key ID (in hex or ASCII), key label (nickname) */
+ static SECStatus
+ PrintKey(PRFileDesc *out, const char *nickName, int count,
+@@ -994,17 +994,17 @@ static SECStatus
+ DeleteKey(char *nickname, secuPWData *pwdata)
+ {
+     SECStatus rv;
+     CERTCertificate *cert;
+     PK11SlotInfo *slot;
+ 
+     slot = PK11_GetInternalKeySlot();
+     if (PK11_NeedLogin(slot)) {
+-        SECStatus rv = PK11_Authenticate(slot, PR_TRUE, pwdata);
++        rv = PK11_Authenticate(slot, PR_TRUE, pwdata);
+         if (rv != SECSuccess) {
+             SECU_PrintError(progName, "could not authenticate to token %s.",
+                             PK11_GetTokenName(slot));
+             return SECFailure;
+         }
+     }
+     cert = PK11_FindCertFromNickname(nickname, pwdata);
+     if (!cert) {
+@@ -1061,17 +1061,17 @@ PrintBuildFlags()
+ #endif
+ #ifdef NSS_NO_INIT_SUPPORT
+     PR_fprintf(PR_STDOUT, "NSS_NO_INIT_SUPPORT\n");
+ #endif
+     exit(0);
+ }
+ 
+ static void
+-PrintSyntax(char *progName)
++PrintSyntax()
+ {
+ #define FPS fprintf(stderr,
+     FPS "Type %s -H for more detailed descriptions\n", progName);
+     FPS "Usage:  %s -N [-d certdir] [-P dbprefix] [-f pwfile] [--empty-password]\n", progName);
+     FPS "Usage:  %s -T [-d certdir] [-P dbprefix] [-h token-name]\n"
+         "\t\t [-f pwfile] [-0 SSO-password]\n", progName);
+     FPS "\t%s -A -n cert-name -t trustargs [-d certdir] [-P dbprefix] [-a] [-i input]\n",
+         progName);
+@@ -1833,17 +1833,17 @@ luBuildFlags(enum usage_level ul, const 
+     FPS "%-15s Print enabled build flags relevant for NSS test execution\n",
+         "--build-flags");
+     if (ul == usage_selected && !is_my_command)
+         return;
+     FPS "\n");
+ }
+ 
+ static void
+-LongUsage(char *progName, enum usage_level ul, const char *command)
++LongUsage(enum usage_level ul, const char *command)
+ {
+     luA(ul, command);
+     luB(ul, command);
+     luE(ul, command);
+     luC(ul, command);
+     luG(ul, command);
+     luD(ul, command);
+     luRename(ul, command);
+@@ -1861,24 +1861,24 @@ LongUsage(char *progName, enum usage_lev
+     luW(ul, command);
+     luUpgradeMerge(ul, command);
+     luMerge(ul, command);
+     luS(ul, command);
+ #undef FPS
+ }
+ 
+ static void
+-Usage(char *progName)
++Usage()
+ {
+     PR_fprintf(PR_STDERR,
+                "%s - Utility to manipulate NSS certificate databases\n\n"
+                "Usage:  %s <command> -d <database-directory> <options>\n\n"
+                "Valid commands:\n",
+                progName, progName);
+-    LongUsage(progName, usage_selected, NULL);
++    LongUsage(usage_selected, NULL);
+     PR_fprintf(PR_STDERR, "\n"
+                           "%s -H <command> : Print available options for the given command\n"
+                           "%s -H : Print complete help output of all commands and options\n"
+                           "%s --syntax : Print a short summary of all commands and options\n",
+                progName, progName, progName);
+     exit(1);
+ }
+ 
+@@ -2264,54 +2264,53 @@ flagArray opFlagsArray[] =
+       { NAME_SIZE(encrypt), CKF_ENCRYPT },
+       { NAME_SIZE(decrypt), CKF_DECRYPT },
+       { NAME_SIZE(sign), CKF_SIGN },
+       { NAME_SIZE(sign_recover), CKF_SIGN_RECOVER },
+       { NAME_SIZE(verify), CKF_VERIFY },
+       { NAME_SIZE(verify_recover), CKF_VERIFY_RECOVER },
+       { NAME_SIZE(wrap), CKF_WRAP },
+       { NAME_SIZE(unwrap), CKF_UNWRAP },
+-      { NAME_SIZE(derive), CKF_DERIVE },
++      { NAME_SIZE(derive), CKF_DERIVE }
+     };
+ 
+-int opFlagsCount = sizeof(opFlagsArray) / sizeof(flagArray);
++int opFlagsCount = PR_ARRAY_SIZE(opFlagsArray);
+ 
+ flagArray attrFlagsArray[] =
+     {
+       { NAME_SIZE(token), PK11_ATTR_TOKEN },
+       { NAME_SIZE(session), PK11_ATTR_SESSION },
+       { NAME_SIZE(private), PK11_ATTR_PRIVATE },
+       { NAME_SIZE(public), PK11_ATTR_PUBLIC },
+       { NAME_SIZE(modifiable), PK11_ATTR_MODIFIABLE },
+       { NAME_SIZE(unmodifiable), PK11_ATTR_UNMODIFIABLE },
+       { NAME_SIZE(sensitive), PK11_ATTR_SENSITIVE },
+       { NAME_SIZE(insensitive), PK11_ATTR_INSENSITIVE },
+       { NAME_SIZE(extractable), PK11_ATTR_EXTRACTABLE },
+       { NAME_SIZE(unextractable), PK11_ATTR_UNEXTRACTABLE }
+-
+     };
+ 
+-int attrFlagsCount = sizeof(attrFlagsArray) / sizeof(flagArray);
++int attrFlagsCount = PR_ARRAY_SIZE(attrFlagsArray);
+ 
+ #define MAX_STRING 30
+ CK_ULONG
+-GetFlags(char *flagsString, flagArray *flagArray, int count)
++GetFlags(char *flagsString, flagArray *flags, int count)
+ {
+     CK_ULONG flagsValue = strtol(flagsString, NULL, 0);
+     int i;
+ 
+     if ((flagsValue != 0) || (*flagsString == 0)) {
+         return flagsValue;
+     }
+     while (*flagsString) {
+         for (i = 0; i < count; i++) {
+-            if (strncmp(flagsString, flagArray[i].name, flagArray[i].nameSize) ==
++            if (strncmp(flagsString, flags[i].name, flags[i].nameSize) ==
+                 0) {
+-                flagsValue |= flagArray[i].value;
+-                flagsString += flagArray[i].nameSize;
++                flagsValue |= flags[i].value;
++                flagsString += flags[i].nameSize;
+                 if (*flagsString != 0) {
+                     flagsString++;
+                 }
+                 break;
+             }
+         }
+         if (i == count) {
+             char name[MAX_STRING];
+@@ -2686,41 +2685,40 @@ certutil_main(int argc, char **argv, PRB
+     progName = PORT_Strrchr(argv[0], '/');
+     progName = progName ? progName + 1 : argv[0];
+     memcpy(certutil_commands, commands_init, sizeof commands_init);
+     memcpy(certutil_options, options_init, sizeof options_init);
+ 
+     rv = SECU_ParseCommandLine(argc, argv, progName, &certutil);
+ 
+     if (rv != SECSuccess)
+-        Usage(progName);
++        Usage();
+ 
+     if (certutil.commands[cmd_PrintSyntax].activated) {
+-        PrintSyntax(progName);
++        PrintSyntax();
+     }
+ 
+     if (certutil.commands[cmd_PrintHelp].activated) {
+-        int i;
+         char buf[2];
+         const char *command = NULL;
+         for (i = 0; i < max_cmd; i++) {
+             if (i == cmd_PrintHelp)
+                 continue;
+             if (certutil.commands[i].activated) {
+                 if (certutil.commands[i].flag) {
+                     buf[0] = certutil.commands[i].flag;
+                     buf[1] = 0;
+                     command = buf;
+                 } else {
+                     command = certutil.commands[i].longform;
+                 }
+                 break;
+             }
+         }
+-        LongUsage(progName, (command ? usage_selected : usage_all), command);
++        LongUsage((command ? usage_selected : usage_all), command);
+         exit(1);
+     }
+ 
+     if (certutil.commands[cmd_BuildFlags].activated) {
+         PrintBuildFlags();
+     }
+ 
+     if (certutil.options[opt_PasswordFile].arg) {
+@@ -2818,26 +2816,26 @@ certutil_main(int argc, char **argv, PRB
+         serialNumber = sn;
+     }
+ 
+     /*  -P certdb name prefix */
+     if (certutil.options[opt_DBPrefix].activated) {
+         if (certutil.options[opt_DBPrefix].arg) {
+             certPrefix = certutil.options[opt_DBPrefix].arg;
+         } else {
+-            Usage(progName);
++            Usage();
+         }
+     }
+ 
+     /*  --source-prefix certdb name prefix */
+     if (certutil.options[opt_SourcePrefix].activated) {
+         if (certutil.options[opt_SourcePrefix].arg) {
+             srcCertPrefix = certutil.options[opt_SourcePrefix].arg;
+         } else {
+-            Usage(progName);
++            Usage();
+         }
+     }
+ 
+     /*  -q PQG file or curve name */
+     if (certutil.options[opt_PQGFile].activated) {
+         if ((keytype != dsaKey) && (keytype != ecKey)) {
+             PR_fprintf(PR_STDERR, "%s -q: specifies a PQG file for DSA keys"
+                                   " (-k dsa) or a named curve for EC keys (-k ec)\n)",
+@@ -2911,17 +2909,17 @@ certutil_main(int argc, char **argv, PRB
+         for (i = 0; i < certutil.numCommands; i++) {
+             if (certutil.commands[i].activated)
+                 PR_fprintf(PR_STDERR, " -%c", certutil.commands[i].flag);
+         }
+         PR_fprintf(PR_STDERR, "\n");
+         return 255;
+     }
+     if (commandsEntered == 0) {
+-        Usage(progName);
++        Usage();
+     }
+ 
+     if (certutil.commands[cmd_ListCerts].activated ||
+         certutil.commands[cmd_PrintHelp].activated ||
+         certutil.commands[cmd_ListKeys].activated ||
+         certutil.commands[cmd_ListModules].activated ||
+         certutil.commands[cmd_CheckCertValidity].activated ||
+         certutil.commands[cmd_Version].activated) {
+diff --git a/security/nss/cmd/crlutil/crlutil.c b/security/nss/cmd/crlutil/crlutil.c
+--- a/security/nss/cmd/crlutil/crlutil.c
++++ b/security/nss/cmd/crlutil/crlutil.c
+@@ -765,17 +765,17 @@ loser:
+     if (signCrl)
+         SEC_DestroyCrl(signCrl);
+     if (cert)
+         CERT_DestroyCertificate(cert);
+     return (rv);
+ }
+ 
+ static void
+-Usage(char *progName)
++Usage()
+ {
+     fprintf(stderr,
+             "Usage:  %s -L [-n nickname] [-d keydir] [-P dbprefix] [-t crlType]\n"
+             "        %s -D -n nickname [-d keydir] [-P dbprefix]\n"
+             "        %s -S -i crl\n"
+             "        %s -I -i crl -t crlType [-u url] [-d keydir] [-P dbprefix] [-B] "
+             "[-p pwd-file] -w [pwd-string]\n"
+             "        %s -E -t crlType [-d keydir] [-P dbprefix]\n"
+@@ -903,17 +903,17 @@ main(int argc, char **argv)
+     crlType = SEC_CRL_TYPE;
+     /*
+      * Parse command line arguments
+      */
+     optstate = PL_CreateOptState(argc, argv, "sqBCDGILMSTEP:f:d:i:h:n:p:t:u:r:aZ:o:c:");
+     while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
+         switch (optstate->option) {
+             case '?':
+-                Usage(progName);
++                Usage();
+                 break;
+ 
+             case 'T':
+                 test = PR_TRUE;
+                 break;
+ 
+             case 'E':
+                 erase = PR_TRUE;
+@@ -1033,27 +1033,27 @@ main(int argc, char **argv)
+                 case 'u':
+                     url = PORT_Strdup(optstate->value);
+                     break;
+             }
+         }
+     }
+ 
+     if (deleteCRL && !nickName)
+-        Usage(progName);
++        Usage();
+     if (importCRL && !inFile)
+-        Usage(progName);
++        Usage();
+     if (showFileCRL && !inFile)
+-        Usage(progName);
++        Usage();
+     if ((generateCRL && !nickName) ||
+         (modifyCRL && !inFile && !nickName))
+-        Usage(progName);
++        Usage();
+     if (!(listCRL || deleteCRL || importCRL || showFileCRL || generateCRL ||
+           modifyCRL || test || erase))
+-        Usage(progName);
++        Usage();
+ 
+     if (listCRL || showFileCRL) {
+         readonly = PR_TRUE;
+     }
+ 
+     PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
+ 
+     PK11_SetPasswordFunc(SECU_GetModulePassword);
+diff --git a/security/nss/cmd/crmftest/testcrmf.c b/security/nss/cmd/crmftest/testcrmf.c
+--- a/security/nss/cmd/crmftest/testcrmf.c
++++ b/security/nss/cmd/crmftest/testcrmf.c
+@@ -572,17 +572,16 @@ Decode(void)
+         printf("Error decoding CertReqMessages.\n");
+         return 202;
+     }
+     numMsgs = CRMF_CertReqMessagesGetNumMessages(certReqMsgs);
+     if (numMsgs <= 0) {
+         printf("WARNING: The DER contained %d messages.\n", numMsgs);
+     }
+     for (i = 0; i < numMsgs; i++) {
+-        SECStatus rv;
+         printf("crmftest: Processing cert request %d\n", i);
+         certReqMsg = CRMF_CertReqMessagesGetCertReqMsgAtIndex(certReqMsgs, i);
+         if (certReqMsg == NULL) {
+             printf("ERROR: Could not access the message at index %d of %s\n",
+                    i, filePath);
+         }
+         rv = CRMF_CertReqMsgGetID(certReqMsg, &lame);
+         if (rv) {
+diff --git a/security/nss/cmd/dbtest/dbtest.c b/security/nss/cmd/dbtest/dbtest.c
+--- a/security/nss/cmd/dbtest/dbtest.c
++++ b/security/nss/cmd/dbtest/dbtest.c
+@@ -53,17 +53,17 @@ getPassword(PK11SlotInfo *slot, PRBool r
+         return NULL;
+     }
+ 
+     *success = 1;
+     return PORT_Strdup(userPassword);
+ }
+ 
+ static void
+-Usage(const char *progName)
++Usage()
+ {
+     printf("Usage:  %s [-r] [-f] [-i] [-d dbdir ] \n",
+            progName);
+     printf("%-20s open database readonly (NSS_INIT_READONLY)\n", "-r");
+     printf("%-20s Continue to force initializations even if the\n", "-f");
+     printf("%-20s databases cannot be opened (NSS_INIT_FORCEOPEN)\n", " ");
+     printf("%-20s Try to initialize the database\n", "-i");
+     printf("%-20s Supply a password with which to initialize the db\n", "-p");
+@@ -91,17 +91,17 @@ main(int argc, char **argv)
+     progName = progName ? progName + 1 : argv[0];
+ 
+     optstate = PL_CreateOptState(argc, argv, "rfip:d:h");
+ 
+     while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
+         switch (optstate->option) {
+             case 'h':
+             default:
+-                Usage(progName);
++                Usage();
+                 break;
+ 
+             case 'r':
+                 flags |= NSS_INIT_READONLY;
+                 break;
+ 
+             case 'f':
+                 flags |= NSS_INIT_FORCEOPEN;
+@@ -117,17 +117,17 @@ main(int argc, char **argv)
+ 
+             case 'd':
+                 dbDir = PORT_Strdup(optstate->value);
+                 break;
+         }
+     }
+     PL_DestroyOptState(optstate);
+     if (optstatus == PL_OPT_BAD)
+-        Usage(progName);
++        Usage();
+ 
+     if (dbDir) {
+         char *tmp = dbDir;
+         dbDir = SECU_ConfigDirectory(tmp);
+         PORT_Free(tmp);
+     } else {
+         /* Look in $SSL_DIR */
+         dbDir = SECU_ConfigDirectory(SECU_DefaultSSLDir());
+@@ -176,17 +176,16 @@ main(int argc, char **argv)
+                         secmodName, flags);
+     if (rv != SECSuccess) {
+         SECU_PrintPRandOSError(progName);
+         ret = NSS_INITIALIZE_FAILED_ERR;
+     } else {
+         ret = SUCCESS;
+         if (doInitTest) {
+             PK11SlotInfo *slot = PK11_GetInternalKeySlot();
+-            SECStatus rv;
+             int passwordSuccess = 0;
+             int type = CKM_DES3_CBC;
+             SECItem keyid = { 0, NULL, 0 };
+             unsigned char keyIdData[] = { 0xff, 0xfe };
+             PK11SymKey *key = NULL;
+ 
+             keyid.data = keyIdData;
+             keyid.len = sizeof(keyIdData);
+diff --git a/security/nss/cmd/httpserv/httpserv.c b/security/nss/cmd/httpserv/httpserv.c
+--- a/security/nss/cmd/httpserv/httpserv.c
++++ b/security/nss/cmd/httpserv/httpserv.c
+@@ -677,16 +677,17 @@ handle_connection(
+                         NSSBase64_DecodeBuffer(arena, &postData, getData, strlen(getData));
+                     }
+                 }
+                 if (postData.len) {
+                     request = CERT_DecodeOCSPRequest(&postData);
+                 }
+                 if (arena) {
+                     PORT_FreeArena(arena, PR_FALSE);
++                    arena = NULL;
+                 }
+                 if (!request || !request->tbsRequest ||
+                     !request->tbsRequest->requestList ||
+                     !request->tbsRequest->requestList[0]) {
+                     PORT_Sprintf(msgBuf, "Cannot decode OCSP request.\r\n");
+ 
+                     iovs[numIOVs].iov_base = msgBuf;
+                     iovs[numIOVs].iov_len = PORT_Strlen(msgBuf);
+@@ -748,21 +749,21 @@ handle_connection(
+                                 nextUpdate = PR_Now() + (PRTime)60 * 60 * 24 * PR_USEC_PER_SEC; /*tomorrow*/
+                                 revoDate = PR_Now() - (PRTime)60 * 60 * 24 * PR_USEC_PER_SEC;   /*yesterday*/
+                             }
+                         }
+                     }
+ 
+                     {
+                         PRTime now = PR_Now();
+-                        PLArenaPool *arena = NULL;
+                         CERTOCSPSingleResponse *sr;
+                         CERTOCSPSingleResponse **singleResponses;
+                         SECItem *ocspResponse;
+ 
++                        PORT_Assert(!arena);
+                         arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
+ 
+                         if (unknown) {
+                             sr = CERT_CreateOCSPSingleResponseUnknown(arena, reqid, now,
+                                                                       &nextUpdate);
+                         } else if (revoked) {
+                             sr = CERT_CreateOCSPSingleResponseRevoked(arena, reqid, now,
+                                                                       &nextUpdate, revoDate, NULL);
+@@ -782,18 +783,18 @@ handle_connection(
+                         if (!ocspResponse) {
+                             PORT_Sprintf(msgBuf, "Failed to encode response\r\n");
+                             iovs[numIOVs].iov_base = msgBuf;
+                             iovs[numIOVs].iov_len = PORT_Strlen(msgBuf);
+                             numIOVs++;
+                         } else {
+                             PR_Write(ssl_sock, outOcspHeader, strlen(outOcspHeader));
+                             PR_Write(ssl_sock, ocspResponse->data, ocspResponse->len);
+-                            PORT_FreeArena(arena, PR_FALSE);
+                         }
++                        PORT_FreeArena(arena, PR_FALSE);
+                     }
+                     CERT_DestroyOCSPRequest(request);
+                     break;
+                 }
+             } else if (local_file_fd) {
+                 PRInt32 bytes;
+                 int errLen;
+                 bytes = PR_TransmitFile(ssl_sock, local_file_fd, outHeader,
+@@ -1352,17 +1353,16 @@ main(int argc, char **argv)
+             fputs("NSS_Init failed.\n", stderr);
+             exit(8);
+         }
+ 
+         if (caRevoInfos) {
+             caRevoIter = &caRevoInfos->link;
+             do {
+                 PRFileDesc *inFile;
+-                int rv = SECFailure;
+                 SECItem crlDER;
+                 crlDER.data = NULL;
+ 
+                 revoInfo = (caRevoInfo *)caRevoIter;
+                 revoInfo->cert = CERT_FindCertByNickname(
+                     CERT_GetDefaultCertDB(), revoInfo->nickname);
+                 if (!revoInfo->cert) {
+                     fprintf(stderr, "cannot find cert with nickname %s\n",
+@@ -1408,21 +1408,19 @@ main(int argc, char **argv)
+         server_main(listen_sock, 0, 0, 0,
+                     0);
+     }
+ 
+     VLOG(("httpserv: server_thread: exiting"));
+ 
+     if (provideOcsp) {
+         if (caRevoInfos) {
+-            PRCList *caRevoIter;
+-
+             caRevoIter = &caRevoInfos->link;
+             do {
+-                caRevoInfo *revoInfo = (caRevoInfo *)caRevoIter;
++                revoInfo = (caRevoInfo *)caRevoIter;
+                 if (revoInfo->nickname)
+                     PORT_Free(revoInfo->nickname);
+                 if (revoInfo->crlFilename)
+                     PORT_Free(revoInfo->crlFilename);
+                 if (revoInfo->cert)
+                     CERT_DestroyCertificate(revoInfo->cert);
+                 if (revoInfo->id)
+                     CERT_DestroyOCSPCertID(revoInfo->id);
+diff --git a/security/nss/cmd/lib/secutil.c b/security/nss/cmd/lib/secutil.c
+--- a/security/nss/cmd/lib/secutil.c
++++ b/security/nss/cmd/lib/secutil.c
+@@ -1523,19 +1523,19 @@ SECU_PrintDumpDerIssuerAndSerial(FILE *o
+     PORT_Free(derSerialB64);
+ 
+     fprintf(out, "Serial DER as C source: \n{ %d, \"", c->serialNumber.len);
+ 
+     {
+         unsigned int i;
+         for (i = 0; i < c->serialNumber.len; ++i) {
+             unsigned char *chardata = (unsigned char *)(c->serialNumber.data);
+-            unsigned char c = *(chardata + i);
+-
+-            fprintf(out, "\\x%02x", c);
++            unsigned char ch = *(chardata + i);
++
++            fprintf(out, "\\x%02x", ch);
+         }
+         fprintf(out, "\" }\n");
+     }
+ 
+ loser:
+     PORT_FreeArena(arena, PR_FALSE);
+     return rv;
+ }
+@@ -3132,17 +3132,17 @@ loser:
+ typedef enum {
+     noSignature = 0,
+     withSignature = 1
+ } SignatureOptionType;
+ 
+ static int
+ secu_PrintSignedDataSigOpt(FILE *out, SECItem *der, const char *m,
+                            int level, SECU_PPFunc inner,
+-                           SignatureOptionType withSignature)
++                           SignatureOptionType signatureOption)
+ {
+     PLArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
+     CERTSignedData *sd;
+     int rv = SEC_ERROR_NO_MEMORY;
+ 
+     if (!arena)
+         return rv;
+ 
+@@ -3159,17 +3159,17 @@ secu_PrintSignedDataSigOpt(FILE *out, SE
+     if (m) {
+         SECU_Indent(out, level);
+         fprintf(out, "%s:\n", m);
+     } else {
+         level -= 1;
+     }
+     rv = (*inner)(out, &sd->data, "Data", level + 1);
+ 
+-    if (withSignature) {
++    if (signatureOption == withSignature) {
+         SECU_PrintAlgorithmID(out, &sd->signatureAlgorithm, "Signature Algorithm",
+                               level + 1);
+         DER_ConvertBitString(&sd->signature);
+         SECU_PrintAsHex(out, &sd->signature, "Signature", level + 1);
+     }
+     SECU_PrintFingerprints(out, der, "Fingerprint", level + 1);
+ loser:
+     PORT_FreeArena(arena, PR_FALSE);
+diff --git a/security/nss/cmd/listsuites/listsuites.c b/security/nss/cmd/listsuites/listsuites.c
+--- a/security/nss/cmd/listsuites/listsuites.c
++++ b/security/nss/cmd/listsuites/listsuites.c
+@@ -59,19 +59,17 @@ main(int argc, char **argv)
+         goto out;
+     }
+ 
+     fputs("This version of libSSL supports these cipher suites:\n\n", stdout);
+ 
+     /* disable all the SSL3 cipher suites */
+     for (i = 0; i < SSL_NumImplementedCiphers; i++) {
+         PRUint16 suite = cipherSuites[i];
+-        SECStatus rv;
+         PRBool enabled;
+-        PRErrorCode err;
+         SSLCipherSuiteInfo info;
+ 
+         rv = SSL_CipherPrefGetDefault(suite, &enabled);
+         if (rv != SECSuccess) {
+             err = PR_GetError();
+             ++errCount;
+             fprintf(stderr,
+                     "SSL_CipherPrefGetDefault didn't like value 0x%04x (i = %d): %s\n",
+diff --git a/security/nss/cmd/lowhashtest/lowhashtest.c b/security/nss/cmd/lowhashtest/lowhashtest.c
+--- a/security/nss/cmd/lowhashtest/lowhashtest.c
++++ b/security/nss/cmd/lowhashtest/lowhashtest.c
+@@ -385,17 +385,17 @@ testSHA512(NSSLOWInitContext *initCtx)
+                                (const unsigned char *)sha512tests[cnt].input,
+                                sha512tests[cnt].result, &results[0]);
+     }
+     rv += test_long_message_sha512(initCtx);
+     return rv;
+ }
+ 
+ static void
+-Usage(char *progName)
++Usage()
+ {
+     fprintf(stderr, "Usage: %s [algorithm]\n",
+             progName);
+     fprintf(stderr, "algorithm must be one of %s\n",
+             "{ MD5 | SHA1 | SHA224 | SHA256 | SHA384 | SHA512 }");
+     fprintf(stderr, "default is to test all\n");
+     exit(-1);
+ }
+@@ -431,15 +431,15 @@ main(int argc, char **argv)
+     } else if (strcmp(argv[1], "SHA226") == 0) {
+         rv += testSHA256(initCtx);
+     } else if (strcmp(argv[1], "SHA384") == 0) {
+         rv += testSHA384(initCtx);
+     } else if (strcmp(argv[1], "SHA512") == 0) {
+         rv += testSHA512(initCtx);
+     } else {
+         SECU_PrintError(progName, "Unsupported hash type %s\n", argv[0]);
+-        Usage(progName);
++        Usage();
+     }
+ 
+     NSSLOW_Shutdown(initCtx);
+ 
+     return (rv == 0) ? 0 : 1;
+ }
+diff --git a/security/nss/cmd/modutil/install-ds.c b/security/nss/cmd/modutil/install-ds.c
+--- a/security/nss/cmd/modutil/install-ds.c
++++ b/security/nss/cmd/modutil/install-ds.c
+@@ -83,21 +83,21 @@ static const char* errString[] = {
+     "No ModuleName specification in module %s",
+     "No Platforms specification in installer script",
+     "Platform %s has an equivalency loop",
+     "Module file \"%s\" in platform \"%s\" does not exist"
+ };
+ 
+ static char* PR_Strdup(const char* str);
+ 
+-#define PAD(x)                  \
+-    {                           \
+-        int i;                  \
+-        for (i = 0; i < x; i++) \
+-            printf(" ");        \
++#define PAD(x)                                \
++    {                                         \
++        int pad_i;                            \
++        for (pad_i = 0; pad_i < (x); pad_i++) \
++            printf(" ");                      \
+     }
+ #define PADINC 4
+ 
+ Pk11Install_File*
+ Pk11Install_File_new()
+ {
+     Pk11Install_File* new_this;
+     new_this = (Pk11Install_File*)PR_Malloc(sizeof(Pk11Install_File));
+diff --git a/security/nss/cmd/mpitests/mpi-test.c b/security/nss/cmd/mpitests/mpi-test.c
+--- a/security/nss/cmd/mpitests/mpi-test.c
++++ b/security/nss/cmd/mpitests/mpi-test.c
+@@ -370,24 +370,24 @@ int find_name(char *name);
+ void reason(char *fmt, ...);
+ 
+ /*------------------------------------------------------------------------*/
+ /*------------------------------------------------------------------------*/
+ 
+ char g_intbuf[4096]; /* buffer for integer comparison   */
+ char a_intbuf[4096]; /* buffer for integer comparison   */
+ int g_verbose = 1;   /* print out reasons for failure?  */
+-int res;
+ 
+-#define IFOK(x)                                            \
+-    {                                                      \
+-        if (MP_OKAY > (res = (x))) {                       \
+-            reason("test %s failed: error %d\n", #x, res); \
+-            return 1;                                      \
+-        }                                                  \
++#define IFOK(x)                                                 \
++    {                                                           \
++        int ifok_res = (x);                                     \
++        if (MP_OKAY > ifok_res) {                               \
++            reason("test %s failed: error %d\n", #x, ifok_res); \
++            return 1;                                           \
++        }                                                       \
+     }
+ 
+ int
+ main(int argc, char *argv[])
+ {
+     int which, res;
+ 
+     srand((unsigned int)time(NULL));
+diff --git a/security/nss/cmd/ocspclnt/ocspclnt.c b/security/nss/cmd/ocspclnt/ocspclnt.c
+--- a/security/nss/cmd/ocspclnt/ocspclnt.c
++++ b/security/nss/cmd/ocspclnt/ocspclnt.c
+@@ -33,62 +33,62 @@
+ #endif
+ 
+ #define DEFAULT_DB_DIR "~/.netscape"
+ 
+ /* global */
+ char *program_name;
+ 
+ static void
+-synopsis(char *program_name)
++synopsis(char *progname)
+ {
+     PRFileDesc *pr_stderr;
+ 
+     pr_stderr = PR_STDERR;
+     PR_fprintf(pr_stderr, "Usage:");
+     PR_fprintf(pr_stderr,
+                "\t%s -p [-d <dir>]\n",
+-               program_name);
++               progname);
+     PR_fprintf(pr_stderr,
+                "\t%s -P [-d <dir>]\n",
+-               program_name);
++               progname);
+     PR_fprintf(pr_stderr,
+                "\t%s -r <name> [-a] [-L] [-s <name>] [-d <dir>]\n",
+-               program_name);
++               progname);
+     PR_fprintf(pr_stderr,
+                "\t%s -R <name> [-a] [-l <location>] [-s <name>] [-d <dir>]\n",
+-               program_name);
++               progname);
+     PR_fprintf(pr_stderr,
+                "\t%s -S <name> [-a] [-l <location> -t <name>]\n",
+-               program_name);
++               progname);
+     PR_fprintf(pr_stderr,
+                "\t\t [-s <name>] [-w <time>] [-d <dir>]\n");
+     PR_fprintf(pr_stderr,
+                "\t%s -V <name> [-a] -u <usage> [-l <location> -t <name>]\n",
+-               program_name);
++               progname);
+     PR_fprintf(pr_stderr,
+                "\t\t [-s <name>] [-w <time>] [-d <dir>]\n");
+ }
+ 
+ static void
+-short_usage(char *program_name)
++short_usage(char *progname)
+ {
+     PR_fprintf(PR_STDERR,
+                "Type %s -H for more detailed descriptions\n",
+-               program_name);
+-    synopsis(program_name);
++               progname);
++    synopsis(progname);
+ }
+ 
+ static void
+-long_usage(char *program_name)
++long_usage(char *progname)
+ {
+     PRFileDesc *pr_stderr;
+ 
+     pr_stderr = PR_STDERR;
+-    synopsis(program_name);
++    synopsis(progname);
+     PR_fprintf(pr_stderr, "\nCommands (must specify exactly one):\n");
+     PR_fprintf(pr_stderr,
+                "  %-13s Pretty-print a binary request read from stdin\n",
+                "-p");
+     PR_fprintf(pr_stderr,
+                "  %-13s Pretty-print a binary response read from stdin\n",
+                "-P");
+     PR_fprintf(pr_stderr,
+diff --git a/security/nss/cmd/ocspresp/ocspresp.c b/security/nss/cmd/ocspresp/ocspresp.c
+--- a/security/nss/cmd/ocspresp/ocspresp.c
++++ b/security/nss/cmd/ocspresp/ocspresp.c
+@@ -189,34 +189,34 @@ main(int argc, char **argv)
+     PORT_Assert(encodedRev);
+     decodedRev = CERT_DecodeOCSPResponse(encodedRev);
+     PORT_CheckSuccess(CERT_GetOCSPResponseStatus(decodedRev));
+ 
+     PORT_CheckSuccess(CERT_VerifyOCSPResponseSignature(decodedRev, certHandle, &pwdata,
+                                                        &obtainedSignerCert, caCert));
+ #ifdef DEBUG
+     {
+-        SECStatus rv = CERT_GetOCSPStatusForCertID(certHandle, decodedRev, cid,
+-                                                   obtainedSignerCert, now);
++        rv = CERT_GetOCSPStatusForCertID(certHandle, decodedRev, cid,
++                                         obtainedSignerCert, now);
+         PORT_Assert(rv == SECFailure);
+         PORT_Assert(PORT_GetError() == SEC_ERROR_REVOKED_CERTIFICATE);
+     }
+ #else
+     (void)CERT_GetOCSPStatusForCertID(certHandle, decodedRev, cid,
+                                       obtainedSignerCert, now);
+ #endif
+     CERT_DestroyCertificate(obtainedSignerCert);
+ 
+     encodedFail = CERT_CreateEncodedOCSPErrorResponse(
+         arena, SEC_ERROR_OCSP_TRY_SERVER_LATER);
+     PORT_Assert(encodedFail);
+     decodedFail = CERT_DecodeOCSPResponse(encodedFail);
+ #ifdef DEBUG
+     {
+-        SECStatus rv = CERT_GetOCSPResponseStatus(decodedFail);
++        rv = CERT_GetOCSPResponseStatus(decodedFail);
+         PORT_Assert(rv == SECFailure);
+         PORT_Assert(PORT_GetError() == SEC_ERROR_OCSP_TRY_SERVER_LATER);
+     }
+ #else
+     (void)CERT_GetOCSPResponseStatus(decodedFail);
+ #endif
+     retval = 0;
+ loser:
+diff --git a/security/nss/cmd/pk12util/pk12util.c b/security/nss/cmd/pk12util/pk12util.c
+--- a/security/nss/cmd/pk12util/pk12util.c
++++ b/security/nss/cmd/pk12util/pk12util.c
+@@ -23,17 +23,17 @@
+ static char *progName;
+ PRBool pk12_debugging = PR_FALSE;
+ PRBool dumpRawFile;
+ static PRBool pk12uForceUnicode;
+ 
+ PRIntn pk12uErrno = 0;
+ 
+ static void
+-Usage(char *progName)
++Usage()
+ {
+ #define FPS PR_fprintf(PR_STDERR,
+     FPS "Usage:	 %s -i importfile [-d certdir] [-P dbprefix] [-h tokenname]\n",
+ 				 progName);
+     FPS "\t\t [-k slotpwfile | -K slotpw] [-w p12filepwfile | -W p12filepw]\n");
+     FPS "\t\t [-v]\n");
+ 
+     FPS "Usage:	 %s -l listfile [-d certdir] [-P dbprefix] [-h tokenname]\n",
+@@ -1015,36 +1015,36 @@ main(int argc, char **argv)
+     pk12util.options = pk12util_options;
+ 
+     progName = strrchr(argv[0], '/');
+     progName = progName ? progName + 1 : argv[0];
+ 
+     rv = SECU_ParseCommandLine(argc, argv, progName, &pk12util);
+ 
+     if (rv != SECSuccess)
+-        Usage(progName);
++        Usage();
+ 
+     pk12_debugging = pk12util.options[opt_Debug].activated;
+ 
+     if ((pk12util.options[opt_Import].activated +
+          pk12util.options[opt_Export].activated +
+          pk12util.options[opt_List].activated) != 1) {
+-        Usage(progName);
++        Usage();
+     }
+ 
+     if (pk12util.options[opt_Export].activated &&
+         !pk12util.options[opt_Nickname].activated) {
+-        Usage(progName);
++        Usage();
+     }
+ 
+     rv = NSS_OptionGet(__NSS_PKCS12_DECODE_FORCE_UNICODE, &forceUnicode);
+     if (rv != SECSuccess) {
+         SECU_PrintError(progName,
+                         "Failed to get NSS_PKCS12_DECODE_FORCE_UNICODE option");
+-        Usage(progName);
++        Usage();
+     }
+     pk12uForceUnicode = forceUnicode;
+ 
+     slotname = SECU_GetOptionArg(&pk12util, opt_TokenName);
+ 
+     import_file = (pk12util.options[opt_List].activated) ? SECU_GetOptionArg(&pk12util, opt_List)
+                                                          : SECU_GetOptionArg(&pk12util, opt_Import);
+     export_file = SECU_GetOptionArg(&pk12util, opt_Export);
+@@ -1139,17 +1139,17 @@ main(int argc, char **argv)
+         P12U_ExportPKCS12Object(pk12util.options[opt_Nickname].arg,
+                                 export_file, slot, cipher, certCipher,
+                                 &slotPw, &p12FilePw);
+ 
+     } else if (pk12util.options[opt_List].activated) {
+         P12U_ListPKCS12File(import_file, slot, &slotPw, &p12FilePw);
+ 
+     } else {
+-        Usage(progName);
++        Usage();
+         pk12uErrno = PK12UERR_USAGE;
+     }
+ 
+ done:
+     if (import_file != NULL)
+         PORT_ZFree(import_file, PL_strlen(import_file));
+     if (export_file != NULL)
+         PORT_ZFree(export_file, PL_strlen(export_file));
+diff --git a/security/nss/cmd/rsaperf/rsaperf.c b/security/nss/cmd/rsaperf/rsaperf.c
+--- a/security/nss/cmd/rsaperf/rsaperf.c
++++ b/security/nss/cmd/rsaperf/rsaperf.c
+@@ -308,17 +308,17 @@ main(int argc, char **argv)
+     NSSLOWKEYPublicKey *pubKey = NULL;
+     CERTCertificate *cert = NULL;
+     char *progName = NULL;
+     char *secDir = NULL;
+     char *nickname = NULL;
+     char *slotname = NULL;
+     long keybits = 0;
+     RSAOp fn;
+-    void *rsaKey = NULL;
++    void *rsaKeyPtr = NULL;
+     PLOptState *optstate;
+     PLOptStatus optstatus;
+     long iters = DEFAULT_ITERS;
+     int i;
+     PRBool doPriv = PR_FALSE;
+     PRBool doPub = PR_FALSE;
+     int rv;
+     unsigned char buf[BUFFER_BYTES];
+@@ -459,17 +459,17 @@ main(int argc, char **argv)
+         if (pubHighKey == NULL) {
+             fprintf(stderr, "Can't extract public key from certificate");
+             exit(1);
+         }
+ 
+         if (doPub) {
+             /* do public key ops */
+             fn = (RSAOp)PK11_PublicKeyOp;
+-            rsaKey = (void *)pubHighKey;
++            rsaKeyPtr = (void *)pubHighKey;
+ 
+             kh = PK11_ImportPublicKey(cert->slot, pubHighKey, PR_FALSE);
+             if (CK_INVALID_HANDLE == kh) {
+                 fprintf(stderr,
+                         "Unable to import public key to certificate slot.");
+                 exit(1);
+             }
+             pubHighKey->pkcs11Slot = PK11_ReferenceSlot(cert->slot);
+@@ -484,17 +484,17 @@ main(int argc, char **argv)
+                         "Can't find private key by name \"%s\"\n", nickname);
+                 exit(1);
+             }
+ 
+             SECKEY_CacheStaticFlags(privHighKey);
+             fn = (RSAOp)PK11_PrivateKeyOp;
+             keys.privKey = privHighKey;
+             keys.pubKey = pubHighKey;
+-            rsaKey = (void *)&keys;
++            rsaKeyPtr = (void *)&keys;
+             printf("Using PKCS#11 for RSA decryption with token %s.\n",
+                    PK11_GetTokenName(privHighKey->pkcs11Slot));
+         }
+     } else
+ 
+         if (useSessionKey) {
+         /* use PKCS#11 session key objects */
+         PK11RSAGenParams rsaparams;
+@@ -532,23 +532,23 @@ main(int argc, char **argv)
+ 
+         SECKEY_CacheStaticFlags(privHighKey);
+ 
+         fprintf(stderr, "Keygen completed.\n");
+ 
+         if (doPub) {
+             /* do public key operations */
+             fn = (RSAOp)PK11_PublicKeyOp;
+-            rsaKey = (void *)pubHighKey;
++            rsaKeyPtr = (void *)pubHighKey;
+         } else {
+             /* do private key operations */
+             fn = (RSAOp)PK11_PrivateKeyOp;
+             keys.privKey = privHighKey;
+             keys.pubKey = pubHighKey;
+-            rsaKey = (void *)&keys;
++            rsaKeyPtr = (void *)&keys;
+         }
+     } else
+ 
+     {
+         /* use freebl directly */
+         if (!keybits) {
+             keybits = DEFAULT_KEY_BITS;
+         }
+@@ -569,56 +569,56 @@ main(int argc, char **argv)
+                                                0xff);
+                     peCount++;
+                 }
+             }
+             pe.len = peCount;
+             pe.data = &pubEx[0];
+             pe.type = siBuffer;
+ 
+-            rsaKey = RSA_NewKey(keybits, &pe);
++            rsaKeyPtr = RSA_NewKey(keybits, &pe);
+             fprintf(stderr, "Keygen completed.\n");
+         } else {
+             /* use a hardcoded key */
+             printf("Using hardcoded %ld bits key.\n", keybits);
+             if (doPub) {
+                 pubKey = getDefaultRSAPublicKey();
+             } else {
+                 privKey = getDefaultRSAPrivateKey();
+             }
+         }
+ 
+         if (doPub) {
+             /* do public key operations */
+             fn = (RSAOp)RSA_PublicKeyOp;
+-            if (rsaKey) {
++            if (rsaKeyPtr) {
+                 /* convert the RSAPrivateKey to RSAPublicKey */
+                 pubKeyStr.arena = NULL;
+-                pubKeyStr.modulus = ((RSAPrivateKey *)rsaKey)->modulus;
++                pubKeyStr.modulus = ((RSAPrivateKey *)rsaKeyPtr)->modulus;
+                 pubKeyStr.publicExponent =
+-                    ((RSAPrivateKey *)rsaKey)->publicExponent;
+-                rsaKey = &pubKeyStr;
++                    ((RSAPrivateKey *)rsaKeyPtr)->publicExponent;
++                rsaKeyPtr = &pubKeyStr;
+             } else {
+                 /* convert NSSLOWKeyPublicKey to RSAPublicKey */
+-                rsaKey = (void *)(&pubKey->u.rsa);
++                rsaKeyPtr = (void *)(&pubKey->u.rsa);
+             }
+-            PORT_Assert(rsaKey);
++            PORT_Assert(rsaKeyPtr);
+         } else {
+             /* do private key operations */
+             fn = (RSAOp)RSA_PrivateKeyOp;
+             if (privKey) {
+                 /* convert NSSLOWKeyPrivateKey to RSAPrivateKey */
+-                rsaKey = (void *)(&privKey->u.rsa);
++                rsaKeyPtr = (void *)(&privKey->u.rsa);
+             }
+-            PORT_Assert(rsaKey);
++            PORT_Assert(rsaKeyPtr);
+         }
+     }
+ 
+     memset(buf, 1, sizeof buf);
+-    rv = fn(rsaKey, buf2, buf);
++    rv = fn(rsaKeyPtr, buf2, buf);
+     if (rv != SECSuccess) {
+         PRErrorCode errNum;
+         const char *errStr = NULL;
+ 
+         errNum = PORT_GetError();
+         if (errNum)
+             errStr = SECU_Strerror(errNum);
+         else
+@@ -633,17 +633,17 @@ main(int argc, char **argv)
+     runDataArr = (ThreadRunData **)PORT_Alloc(threadNum * sizeof(ThreadRunData *));
+     timeCtx = CreateTimingContext();
+     TimingBegin(timeCtx, PR_Now());
+     for (i = 0; i < threadNum; i++) {
+         runDataArr[i] = (ThreadRunData *)PORT_Alloc(sizeof(ThreadRunData));
+         runDataArr[i]->fn = fn;
+         runDataArr[i]->buf = buf;
+         runDataArr[i]->doIters = &doIters;
+-        runDataArr[i]->rsaKey = rsaKey;
++        runDataArr[i]->rsaKey = rsaKeyPtr;
+         runDataArr[i]->seconds = seconds;
+         runDataArr[i]->iters = iters;
+         threadsArr[i] =
+             PR_CreateThread(PR_USER_THREAD,
+                             ThreadExecFunction,
+                             (void *)runDataArr[i],
+                             PR_PRIORITY_NORMAL,
+                             PR_GLOBAL_THREAD,
+diff --git a/security/nss/cmd/selfserv/selfserv.c b/security/nss/cmd/selfserv/selfserv.c
+--- a/security/nss/cmd/selfserv/selfserv.c
++++ b/security/nss/cmd/selfserv/selfserv.c
+@@ -52,17 +52,17 @@
+ #endif
+ 
+ #ifndef PORT_Malloc
+ #define PORT_Malloc PR_Malloc
+ #endif
+ 
+ int NumSidCacheEntries = 1024;
+ 
+-static int handle_connection(PRFileDesc *, PRFileDesc *, int);
++static int handle_connection(PRFileDesc *, PRFileDesc *);
+ 
+ static const char envVarName[] = { SSL_ENV_VAR_NAME };
+ static const char inheritableSockName[] = { "SELFSERV_LISTEN_SOCKET" };
+ 
+ #define MAX_VIRT_SERVER_NAME_ARRAY_INDEX 10
+ #define MAX_CERT_NICKNAME_ARRAY_INDEX 10
+ 
+ #define DEFAULT_BULK_TEST 16384
+@@ -504,17 +504,16 @@ loser:
+ #define MAX_THREADS 4096
+ #define MAX_PROCS 25
+ static int maxThreads = DEFAULT_THREADS;
+ 
+ typedef struct jobStr {
+     PRCList link;
+     PRFileDesc *tcp_sock;
+     PRFileDesc *model_sock;
+-    int requestCert;
+ } JOB;
+ 
+ static PZLock *qLock;             /* this lock protects all data immediately below */
+ static PRLock *lastLoadedCrlLock; /* this lock protects lastLoadedCrl variable */
+ static PZCondVar *jobQNotEmptyCv;
+ static PZCondVar *freeListNotEmptyCv;
+ static PZCondVar *threadCountChangeCv;
+ static int threadCount;
+@@ -536,51 +535,50 @@ setupJobs(int maxJobs)
+ 
+     for (i = 0; i < maxJobs; ++i) {
+         JOB *pJob = jobTable + i;
+         PR_APPEND_LINK(&pJob->link, &freeJobs);
+     }
+     return SECSuccess;
+ }
+ 
+-typedef int startFn(PRFileDesc *a, PRFileDesc *b, int c);
++typedef int startFn(PRFileDesc *a, PRFileDesc *b);
+ 
+ typedef enum { rs_idle = 0,
+                rs_running = 1,
+                rs_zombie = 2 } runState;
+ 
+ typedef struct perThreadStr {
+     PRFileDesc *a;
+     PRFileDesc *b;
+-    int c;
+     int rv;
+     startFn *startFunc;
+     PRThread *prThread;
+     runState state;
+ } perThread;
+ 
+ static perThread *threads;
+ 
+ void
+ thread_wrapper(void *arg)
+ {
+     perThread *slot = (perThread *)arg;
+ 
+-    slot->rv = (*slot->startFunc)(slot->a, slot->b, slot->c);
++    slot->rv = (*slot->startFunc)(slot->a, slot->b);
+ 
+     /* notify the thread exit handler. */
+     PZ_Lock(qLock);
+     slot->state = rs_zombie;
+     --threadCount;
+     PZ_NotifyAllCondVar(threadCountChangeCv);
+     PZ_Unlock(qLock);
+ }
+ 
+ int
+-jobLoop(PRFileDesc *a, PRFileDesc *b, int c)
++jobLoop(PRFileDesc *a, PRFileDesc *b)
+ {
+     PRCList *myLink = 0;
+     JOB *myJob;
+ 
+     PZ_Lock(qLock);
+     do {
+         myLink = 0;
+         while (PR_CLIST_IS_EMPTY(&jobQ) && !stopping) {
+@@ -590,31 +588,29 @@ jobLoop(PRFileDesc *a, PRFileDesc *b, in
+             myLink = PR_LIST_HEAD(&jobQ);
+             PR_REMOVE_AND_INIT_LINK(myLink);
+         }
+         PZ_Unlock(qLock);
+         myJob = (JOB *)myLink;
+         /* myJob will be null when stopping is true and jobQ is empty */
+         if (!myJob)
+             break;
+-        handle_connection(myJob->tcp_sock, myJob->model_sock,
+-                          myJob->requestCert);
++        handle_connection(myJob->tcp_sock, myJob->model_sock);
+         PZ_Lock(qLock);
+         PR_APPEND_LINK(myLink, &freeJobs);
+         PZ_NotifyCondVar(freeListNotEmptyCv);
+     } while (PR_TRUE);
+     return 0;
+ }
+ 
+ SECStatus
+ launch_threads(
+     startFn *startFunc,
+     PRFileDesc *a,
+     PRFileDesc *b,
+-    int c,
+     PRBool local)
+ {
+     int i;
+     SECStatus rv = SECSuccess;
+ 
+     /* create the thread management serialization structs */
+     qLock = PZ_NewLock(nssILockSelfServ);
+     jobQNotEmptyCv = PZ_NewCondVar(qLock);
+@@ -640,17 +636,16 @@ launch_threads(
+ 
+     PZ_Lock(qLock);
+     for (i = 0; i < maxThreads; ++i) {
+         perThread *slot = threads + i;
+ 
+         slot->state = rs_running;
+         slot->a = a;
+         slot->b = b;
+-        slot->c = c;
+         slot->startFunc = startFunc;
+         slot->prThread = PR_CreateThread(PR_USER_THREAD,
+                                          thread_wrapper, slot, PR_PRIORITY_NORMAL,
+                                          (PR_TRUE ==
+                                           local)
+                                              ? PR_LOCAL_THREAD
+                                              : PR_GLOBAL_THREAD,
+                                          PR_JOINABLE_THREAD, 0);
+@@ -888,18 +883,17 @@ int /* returns count */
+     }
+     PZ_Unlock(lv->lock);
+     return rv;
+ }
+ 
+ int
+ do_writes(
+     PRFileDesc *ssl_sock,
+-    PRFileDesc *model_sock,
+-    int requestCert)
++    PRFileDesc *model_sock)
+ {
+     int sent = 0;
+     int count = 0;
+     lockedVars *lv = (lockedVars *)model_sock;
+ 
+     VLOG(("selfserv: do_writes: starting"));
+     while (sent < bigBuf.len) {
+ 
+@@ -920,18 +914,17 @@ do_writes(
+     FLUSH;
+     VLOG(("selfserv: do_writes: exiting"));
+     return (sent < bigBuf.len) ? SECFailure : SECSuccess;
+ }
+ 
+ static int
+ handle_fdx_connection(
+     PRFileDesc *tcp_sock,
+-    PRFileDesc *model_sock,
+-    int requestCert)
++    PRFileDesc *model_sock)
+ {
+     PRFileDesc *ssl_sock = NULL;
+     SECStatus result;
+     int firstTime = 1;
+     lockedVars lv;
+     PRSocketOptionData opt;
+     char buf[10240];
+ 
+@@ -955,18 +948,17 @@ handle_fdx_connection(
+     } else {
+         ssl_sock = tcp_sock;
+     }
+ 
+     lockedVars_Init(&lv);
+     lockedVars_AddToCount(&lv, 1);
+ 
+     /* Attempt to launch the writer thread. */
+-    result = launch_thread(do_writes, ssl_sock, (PRFileDesc *)&lv,
+-                           requestCert);
++    result = launch_thread(do_writes, ssl_sock, (PRFileDesc *)&lv);
+ 
+     if (result == SECSuccess)
+         do {
+             /* do reads here. */
+             int count;
+             count = PR_Read(ssl_sock, buf, sizeof buf);
+             if (count < 0) {
+                 errWarn("FDX PR_Read");
+@@ -1088,17 +1080,17 @@ makeCorruptedOCSPResponse(PLArenaPool *a
+ 
+     result->items[0].data = ocspResponse->data;
+     result->items[0].len = ocspResponse->len;
+ 
+     return result;
+ }
+ 
+ SECItemArray *
+-makeSignedOCSPResponse(PLArenaPool *arena, ocspStaplingModeType osm,
++makeSignedOCSPResponse(PLArenaPool *arena,
+                        CERTCertificate *cert, secuPWData *pwdata)
+ {
+     SECItemArray *result = NULL;
+     SECItem *ocspResponse = NULL;
+     CERTOCSPSingleResponse **singleResponses;
+     CERTOCSPSingleResponse *sr = NULL;
+     CERTOCSPCertID *cid = NULL;
+     CERTCertificate *ca;
+@@ -1112,17 +1104,17 @@ makeSignedOCSPResponse(PLArenaPool *aren
+         errExit("cannot find CA");
+ 
+     cid = CERT_CreateOCSPCertID(cert, now);
+     if (!cid)
+         errExit("cannot created cid");
+ 
+     nextUpdate = now + (PRTime)60 * 60 * 24 * PR_USEC_PER_SEC; /* plus 1 day */
+ 
+-    switch (osm) {
++    switch (ocspStaplingMode) {
+         case osm_good:
+         case osm_badsig:
+             sr = CERT_CreateOCSPSingleResponseGood(arena, cid, now,
+                                                    &nextUpdate);
+             break;
+         case osm_unknown:
+             sr = CERT_CreateOCSPSingleResponseUnknown(arena, cid, now,
+                                                       &nextUpdate);
+@@ -1145,17 +1137,17 @@ makeSignedOCSPResponse(PLArenaPool *aren
+     singleResponses = PORT_ArenaNewArray(arena, CERTOCSPSingleResponse *, 2);
+     if (singleResponses == NULL)
+         errExit("cannot allocate singleResponses");
+ 
+     singleResponses[0] = sr;
+     singleResponses[1] = NULL;
+ 
+     ocspResponse = CERT_CreateEncodedOCSPSuccessResponse(arena,
+-                                                         (osm == osm_badsig)
++                                                         (ocspStaplingMode == osm_badsig)
+                                                              ? NULL
+                                                              : ca,
+                                                          ocspResponderID_byName, now, singleResponses,
+                                                          &pwdata);
+     if (!ocspResponse)
+         errExit("cannot created ocspResponse");
+ 
+     CERT_DestroyCertificate(ca);
+@@ -1170,17 +1162,17 @@ makeSignedOCSPResponse(PLArenaPool *aren
+ 
+     CERT_DestroyOCSPCertID(cid);
+     cid = NULL;
+ 
+     return result;
+ }
+ 
+ void
+-setupCertStatus(PLArenaPool *arena, enum ocspStaplingModeEnum ocspStaplingMode,
++setupCertStatus(PLArenaPool *arena,
+                 CERTCertificate *cert, int index, secuPWData *pwdata)
+ {
+     if (ocspStaplingMode == osm_random) {
+         /* 6 different responses */
+         int r = rand() % 6;
+         switch (r) {
+             case 0:
+                 ocspStaplingMode = osm_good;
+@@ -1208,17 +1200,17 @@ setupCertStatus(PLArenaPool *arena, enum
+     if (ocspStaplingMode != osm_disabled) {
+         SECItemArray *multiOcspResponses = NULL;
+         switch (ocspStaplingMode) {
+             case osm_good:
+             case osm_revoked:
+             case osm_unknown:
+             case osm_badsig:
+                 multiOcspResponses =
+-                    makeSignedOCSPResponse(arena, ocspStaplingMode, cert,
++                    makeSignedOCSPResponse(arena, cert,
+                                            pwdata);
+                 break;
+             case osm_corrupted:
+                 multiOcspResponses = makeCorruptedOCSPResponse(arena);
+                 break;
+             case osm_failure:
+                 multiOcspResponses = makeTryLaterOCSPResponse(arena);
+                 break;
+@@ -1231,20 +1223,17 @@ setupCertStatus(PLArenaPool *arena, enum
+         }
+         if (multiOcspResponses) {
+             certStatus[index] = multiOcspResponses;
+         }
+     }
+ }
+ 
+ int
+-handle_connection(
+-    PRFileDesc *tcp_sock,
+-    PRFileDesc *model_sock,
+-    int requestCert)
++handle_connection(PRFileDesc *tcp_sock, PRFileDesc *model_sock)
+ {
+     PRFileDesc *ssl_sock = NULL;
+     PRFileDesc *local_file_fd = NULL;
+     char *post;
+     char *pBuf; /* unused space at end of buf */
+     const char *errString;
+     PRStatus status;
+     int bufRem;    /* unused bytes at end of buf */
+@@ -1267,17 +1256,16 @@ handle_connection(
+ 
+     VLOG(("selfserv: handle_connection: starting"));
+     opt.option = PR_SockOpt_Nonblocking;
+     opt.value.non_blocking = PR_FALSE;
+     PR_SetSocketOption(tcp_sock, &opt);
+ 
+     VLOG(("selfserv: handle_connection: starting\n"));
+     if (useModelSocket && model_sock) {
+-        SECStatus rv;
+         ssl_sock = SSL_ImportFD(model_sock, tcp_sock);
+         if (!ssl_sock) {
+             errWarn("SSL_ImportFD with model");
+             goto cleanup;
+         }
+         rv = SSL_ResetHandshake(ssl_sock, /* asServer */ 1);
+         if (rv != SECSuccess) {
+             errWarn("SSL_ResetHandshake");
+@@ -1583,18 +1571,17 @@ sigusr1_handler(int sig)
+     stop_server();
+ }
+ 
+ #endif
+ 
+ SECStatus
+ do_accepts(
+     PRFileDesc *listen_sock,
+-    PRFileDesc *model_sock,
+-    int requestCert)
++    PRFileDesc *model_sock)
+ {
+     PRNetAddr addr;
+     PRErrorCode perr;
+ #ifdef XP_UNIX
+     struct sigaction act;
+ #endif
+ 
+     VLOG(("selfserv: do_accepts: starting"));
+@@ -1654,17 +1641,16 @@ do_accepts(
+         PR_REMOVE_AND_INIT_LINK(myLink);
+         /* could release qLock here and reaquire it 7 lines below, but
+         ** why bother for 4 assignment statements?
+         */
+         {
+             JOB *myJob = (JOB *)myLink;
+             myJob->tcp_sock = tcp_sock;
+             myJob->model_sock = model_sock;
+-            myJob->requestCert = requestCert;
+         }
+ 
+         PR_APPEND_LINK(myLink, &jobQ);
+         PZ_NotifyCondVar(jobQNotEmptyCv);
+         PZ_Unlock(qLock);
+     }
+ 
+     FPRINTF(stderr, "selfserv: Closing listen socket.\n");
+@@ -1813,17 +1799,16 @@ handshakeCallback(PRFileDesc *fd, void *
+             SECITEM_FreeItem(hostInfo, PR_TRUE);
+         }
+     }
+ }
+ 
+ void
+ server_main(
+     PRFileDesc *listen_sock,
+-    int requestCert,
+     SECKEYPrivateKey **privKey,
+     CERTCertificate **cert,
+     const char *expectedHostNameVal)
+ {
+     int i;
+     PRFileDesc *model_sock = NULL;
+     int rv;
+     SECStatus secStatus;
+@@ -2016,17 +2001,17 @@ server_main(
+     }
+ 
+     if (MakeCertOK)
+         SSL_BadCertHook(model_sock, myBadCertHandler, NULL);
+ 
+     /* end of ssl configuration. */
+ 
+     /* Now, do the accepting, here in the main thread. */
+-    rv = do_accepts(listen_sock, model_sock, requestCert);
++    rv = do_accepts(listen_sock, model_sock);
+ 
+     terminateWorkerThreads();
+ 
+     if (useModelSocket && model_sock) {
+         if (model_sock) {
+             PR_Close(model_sock);
+         }
+     }
+@@ -2649,19 +2634,18 @@ main(int argc, char **argv)
+                     exit(9);
+                 }
+                 ndx = tolower(ndx) - 'a';
+                 if (ndx < PR_ARRAY_SIZE(ssl3CipherSuites)) {
+                     cipher = ssl3CipherSuites[ndx];
+                 }
+             }
+             if (cipher > 0) {
+-                SECStatus status;
+-                status = SSL_CipherPrefSetDefault(cipher, SSL_ALLOWED);
+-                if (status != SECSuccess)
++                rv = SSL_CipherPrefSetDefault(cipher, SSL_ALLOWED);
++                if (rv != SECSuccess)
+                     SECU_PrintError(progName, "SSL_CipherPrefSet()");
+             } else {
+                 fprintf(stderr,
+                         "Invalid cipher specification (-c arg).\n");
+                 exit(9);
+             }
+         }
+         PORT_Free(cstringSaved);
+@@ -2679,45 +2663,45 @@ main(int argc, char **argv)
+         }
+         privKey[i] = PK11_FindKeyByAnyCert(cert[i], &pwdata);
+         if (privKey[i] == NULL) {
+             fprintf(stderr, "selfserv: Can't find Private Key for cert %s\n",
+                     certNicknameArray[i]);
+             exit(11);
+         }
+         if (privKey[i]->keyType != ecKey)
+-            setupCertStatus(certStatusArena, ocspStaplingMode, cert[i], i, &pwdata);
++            setupCertStatus(certStatusArena, cert[i], i, &pwdata);
+     }
+ 
+     if (configureWeakDHE > 0) {
+         fprintf(stderr, "selfserv: Creating dynamic weak DH parameters\n");
+         rv = SSL_EnableWeakDHEPrimeGroup(NULL, PR_TRUE);
+         if (rv != SECSuccess) {
+             goto cleanup;
+         }
+         fprintf(stderr, "selfserv: Done creating dynamic weak DH parameters\n");
+     }
+ 
+     /* allocate the array of thread slots, and launch the worker threads. */
+-    rv = launch_threads(&jobLoop, 0, 0, requestCert, useLocalThreads);
++    rv = launch_threads(&jobLoop, 0, 0, useLocalThreads);
+ 
+     if (rv == SECSuccess && logStats) {
+         loggerThread = PR_CreateThread(PR_SYSTEM_THREAD,
+                                        logger, NULL, PR_PRIORITY_NORMAL,
+                                        useLocalThreads ? PR_LOCAL_THREAD
+                                                        : PR_GLOBAL_THREAD,
+                                        PR_JOINABLE_THREAD, 0);
+         if (loggerThread == NULL) {
+             fprintf(stderr, "selfserv: Failed to launch logger thread!\n");
+             rv = SECFailure;
+         }
+     }
+ 
+     if (rv == SECSuccess) {
+-        server_main(listen_sock, requestCert, privKey, cert,
++        server_main(listen_sock, privKey, cert,
+                     expectedHostNameVal);
+     }
+ 
+     VLOG(("selfserv: server_thread: exiting"));
+ 
+ cleanup:
+     printSSLStatistics();
+     ssl3stats = SSL_GetStatistics();
+@@ -2726,17 +2710,16 @@ cleanup:
+         exit(1);
+     }
+     if (failedToNegotiateName) {
+         fprintf(stderr, "selfserv: Failed properly negotiate server name\n");
+         exit(1);
+     }
+ 
+     {
+-        int i;
+         for (i = 0; i < certNicknameIndex; i++) {
+             if (cert[i]) {
+                 CERT_DestroyCertificate(cert[i]);
+             }
+             if (privKey[i]) {
+                 SECKEY_DestroyPrivateKey(privKey[i]);
+             }
+             PORT_Free(certNicknameArray[i]);
+diff --git a/security/nss/cmd/signtool/javascript.c b/security/nss/cmd/signtool/javascript.c
+--- a/security/nss/cmd/signtool/javascript.c
++++ b/security/nss/cmd/signtool/javascript.c
+@@ -1295,17 +1295,16 @@ extract_js(char *filename)
+     if (dumpParse) {
+         PrintHTMLStream(outputFD, head);
+     }
+ 
+     /*
+      * Now we have a stream of tags and text.  Go through and deal with each.
+      */
+     for (curitem = head; curitem; curitem = curitem->next) {
+-        TagItem *tagp = NULL;
+         AVPair *pairp = NULL;
+         char *src = NULL, *id = NULL, *codebase = NULL;
+         PRBool hasEventHandler = PR_FALSE;
+         int i;
+ 
+         /* Reset archive directory for each tag */
+         if (archiveDir) {
+             PR_Free(archiveDir);
+@@ -1664,21 +1663,24 @@ loser:
+  *
+  * e n s u r e E x i s t s
+  *
+  * Check for existence of indicated directory.  If it doesn't exist,
+  * it will be created.
+  * Returns PR_SUCCESS if the directory is present, PR_FAILURE otherwise.
+  */
+ static PRStatus
+-ensureExists(char *base, char *path)
++ensureExists(char *basepath, char *path)
+ {
+     char fn[FNSIZE];
+     PRDir *dir;
+-    sprintf(fn, "%s/%s", base, path);
++    int c = snprintf(fn, sizeof(fn), "%s/%s", basepath, path);
++    if (c >= sizeof(fn)) {
++        return PR_FAILURE;
++    }
+ 
+     /*PR_fprintf(outputFD, "Trying to open directory %s.\n", fn);*/
+ 
+     if ((dir = PR_OpenDir(fn))) {
+         PR_CloseDir(dir);
+         return PR_SUCCESS;
+     }
+     return PR_MkDir(fn, 0777);
+diff --git a/security/nss/cmd/signtool/sign.c b/security/nss/cmd/signtool/sign.c
+--- a/security/nss/cmd/signtool/sign.c
++++ b/security/nss/cmd/signtool/sign.c
+@@ -170,36 +170,36 @@ typedef struct {
+ /*
+  *  S i g n A l l A r c
+  *
+  *  Javascript may generate multiple .arc directories, one
+  *  for each jar archive needed. Sign them all.
+  *
+  */
+ int
+-SignAllArc(char *jartree, char *keyName, int javascript, char *metafile,
+-           char *install_script, int optimize, PRBool recurse)
++SignAllArc(char *jartree, char *keyName, int javascript, char *metafilename,
++           char *install_script, int optimize_level, PRBool recurse)
+ {
+     SignArcInfo info;
+ 
+     info.keyName = keyName;
+     info.javascript = javascript;
+-    info.metafile = metafile;
++    info.metafile = metafilename;
+     info.install_script = install_script;
+-    info.optimize = optimize;
++    info.optimize = optimize_level;
+ 
+     return foreach (jartree, "", sign_all_arc_fn, recurse,
+                     PR_TRUE /*include dirs*/, (void *)&info);
+ }
+ 
+ static int
+ sign_all_arc_fn(char *relpath, char *basedir, char *reldir, char *filename,
+                 void *arg)
+ {
+-    char *zipfile = NULL;
++    char *zipfilename = NULL;
+     char *arc = NULL, *archive = NULL;
+     int retval = 0;
+     SignArcInfo *infop = (SignArcInfo *)arg;
+ 
+     /* Make sure there is one and only one ".arc" in the relative path,
+      * and that it is at the end of the path (don't sign .arcs within .arcs) */
+     if ((PL_strcaserstr(relpath, ".arc") == relpath + strlen(relpath) - 4) &&
+         (PL_strcasestr(relpath, ".arc") == relpath + strlen(relpath) - 4)) {
+@@ -207,40 +207,40 @@ sign_all_arc_fn(char *relpath, char *bas
+         if (!infop) {
+             PR_fprintf(errorFD, "%s: Internal failure\n", PROGRAM_NAME);
+             errorCount++;
+             retval = -1;
+             goto finish;
+         }
+         archive = PR_smprintf("%s/%s", basedir, relpath);
+ 
+-        zipfile = PL_strdup(archive);
+-        arc = PORT_Strrchr(zipfile, '.');
++        zipfilename = PL_strdup(archive);
++        arc = PORT_Strrchr(zipfilename, '.');
+ 
+         if (arc == NULL) {
+             PR_fprintf(errorFD, "%s: Internal failure\n", PROGRAM_NAME);
+             errorCount++;
+             retval = -1;
+             goto finish;
+         }
+ 
+         PL_strcpy(arc, ".jar");
+ 
+         if (verbosity >= 0) {
+-            PR_fprintf(outputFD, "\nsigning: %s\n", zipfile);
++            PR_fprintf(outputFD, "\nsigning: %s\n", zipfilename);
+         }
+-        retval = SignArchive(archive, infop->keyName, zipfile,
++        retval = SignArchive(archive, infop->keyName, zipfilename,
+                              infop->javascript, infop->metafile, infop->install_script,
+                              infop->optimize, PR_TRUE /* recurse */);
+     }
+ finish:
+     if (archive)
+         PR_Free(archive);
+-    if (zipfile)
+-        PR_Free(zipfile);
++    if (zipfilename)
++        PR_Free(zipfilename);
+ 
+     return retval;
+ }
+ 
+ /*********************************************************************
+  *
+  * c r e a t e _ p k 7
+  */
+@@ -702,123 +702,123 @@ SignFile(FILE *outFile, FILE *inFile, CE
+  *  From the supplied manifest file, calculates
+  *  digests on the various sections, creating a .SF
+  *  file in the process.
+  *
+  */
+ static int
+ generate_SF_file(char *manifile, char *who)
+ {
+-    FILE *sf;
+-    FILE *mf;
++    FILE *sfFile;
++    FILE *mfFile;
+     long r1, r2, r3;
+     char whofile[FNSIZE];
+     char *buf, *name = NULL;
+     char *md5, *sha1;
+     JAR_Digest dig;
+     int line = 0;
+ 
+     strcpy(whofile, who);
+ 
+-    if ((mf = fopen(manifile, "rb")) == NULL) {
++    if ((mfFile = fopen(manifile, "rb")) == NULL) {
+         perror(manifile);
+         exit(ERRX);
+     }
+ 
+-    if ((sf = fopen(whofile, "wb")) == NULL) {
++    if ((sfFile = fopen(whofile, "wb")) == NULL) {
+         perror(who);
+         exit(ERRX);
+     }
+ 
+     buf = (char *)PORT_ZAlloc(BUFSIZ);
+ 
+     if (buf)
+         name = (char *)PORT_ZAlloc(BUFSIZ);
+ 
+     if (buf == NULL || name == NULL)
+         out_of_memory();
+ 
+-    fprintf(sf, "Signature-Version: 1.0\n");
+-    fprintf(sf, "Created-By: %s\n", CREATOR);
+-    fprintf(sf, "Comments: %s\n", BREAKAGE);
++    fprintf(sfFile, "Signature-Version: 1.0\n");
++    fprintf(sfFile, "Created-By: %s\n", CREATOR);
++    fprintf(sfFile, "Comments: %s\n", BREAKAGE);
+ 
+-    if (fgets(buf, BUFSIZ, mf) == NULL) {
++    if (fgets(buf, BUFSIZ, mfFile) == NULL) {
+         PR_fprintf(errorFD, "%s: empty manifest file!\n", PROGRAM_NAME);
+         errorCount++;
+         exit(ERRX);
+     }
+ 
+     if (strncmp(buf, "Manifest-Version:", 17)) {
+         PR_fprintf(errorFD, "%s: not a manifest file!\n", PROGRAM_NAME);
+         errorCount++;
+         exit(ERRX);
+     }
+ 
+-    fseek(mf, 0L, SEEK_SET);
++    fseek(mfFile, 0L, SEEK_SET);
+ 
+     /* Process blocks of headers, and calculate their hashen */
+ 
+     while (1) {
+         /* Beginning range */
+-        r1 = ftell(mf);
++        r1 = ftell(mfFile);
+ 
+-        if (fgets(name, BUFSIZ, mf) == NULL)
++        if (fgets(name, BUFSIZ, mfFile) == NULL)
+             break;
+ 
+         line++;
+ 
+         if (r1 != 0 && strncmp(name, "Name:", 5)) {
+             PR_fprintf(errorFD,
+                        "warning: unexpected input in manifest file \"%s\" at line %d:\n",
+                        manifile, line);
+             PR_fprintf(errorFD, "%s\n", name);
+             warningCount++;
+         }
+ 
+         r2 = r1;
+-        while (fgets(buf, BUFSIZ, mf)) {
++        while (fgets(buf, BUFSIZ, mfFile)) {
+             if (*buf == 0 || *buf == '\n' || *buf == '\r')
+                 break;
+ 
+             line++;
+ 
+             /* Ending range for hashing */
+-            r2 = ftell(mf);
++            r2 = ftell(mfFile);
+         }
+ 
+-        r3 = ftell(mf);
++        r3 = ftell(mfFile);
+ 
+         if (r1) {
+-            fprintf(sf, "\n");
+-            fprintf(sf, "%s", name);
++            fprintf(sfFile, "\n");
++            fprintf(sfFile, "%s", name);
+         }
+ 
+-        calculate_MD5_range(mf, r1, r2, &dig);
++        calculate_MD5_range(mfFile, r1, r2, &dig);
+ 
+         if (optimize == 0) {
+-            fprintf(sf, "Digest-Algorithms: MD5 SHA1\n");
++            fprintf(sfFile, "Digest-Algorithms: MD5 SHA1\n");
+ 
+             md5 = BTOA_DataToAscii(dig.md5, MD5_LENGTH);
+-            fprintf(sf, "MD5-Digest: %s\n", md5);
++            fprintf(sfFile, "MD5-Digest: %s\n", md5);
+             PORT_Free(md5);
+         }
+ 
+         sha1 = BTOA_DataToAscii(dig.sha1, SHA1_LENGTH);
+-        fprintf(sf, "SHA1-Digest: %s\n", sha1);
++        fprintf(sfFile, "SHA1-Digest: %s\n", sha1);
+         PORT_Free(sha1);
+ 
+         /* restore normalcy after changing offset position */
+-        fseek(mf, r3, SEEK_SET);
++        fseek(mfFile, r3, SEEK_SET);
+     }
+ 
+     PORT_Free(buf);
+     PORT_Free(name);
+ 
+-    fclose(sf);
+-    fclose(mf);
++    fclose(sfFile);
++    fclose(mfFile);
+ 
+     return 0;
+ }
+ 
+ /*
+  *  c a l c u l a t e _ M D 5 _ r a n g e
+  *
+  *  Calculate the MD5 digest on a range of bytes in
+diff --git a/security/nss/cmd/signtool/zip.c b/security/nss/cmd/signtool/zip.c
+--- a/security/nss/cmd/signtool/zip.c
++++ b/security/nss/cmd/signtool/zip.c
+@@ -124,17 +124,17 @@ handle_zerror(int err, char *msg)
+ /****************************************************************
+  *
+  * J z i p A d d
+  *
+  * Adds a new file into a ZIP file.  The ZIP file must have already
+  * been opened with JzipOpen.
+  */
+ int
+-JzipAdd(char *fullname, char *filename, ZIPfile *zipfile, int compression_level)
++JzipAdd(char *fullname, char *filename, ZIPfile *zipfile, int lvl)
+ {
+     ZIPentry *entry;
+     PRFileDesc *readfp;
+     PRFileDesc *zipfp;
+     unsigned long crc;
+     unsigned long local_size_pos;
+     int num;
+     int err;
+@@ -314,17 +314,17 @@ JzipAdd(char *fullname, char *filename, 
+     zstream.next_out = outbuf;
+     zstream.avail_out = BUFSIZ;
+     /* Setting the windowBits to -MAX_WBITS is an undocumented feature of
+      * zlib (see deflate.c in zlib).  It is the same thing that Java does
+      * when you specify the nowrap option for deflation in java.util.zip.
+      * It causes zlib to leave out its headers and footers, which don't
+      * work in PKZIP files.
+      */
+-    err = deflateInit2(&zstream, compression_level, Z_DEFLATED,
++    err = deflateInit2(&zstream, lvl, Z_DEFLATED,
+                        -MAX_WBITS, 8 /*default*/, Z_DEFAULT_STRATEGY);
+     if (err != Z_OK) {
+         handle_zerror(err, zstream.msg);
+         exit(ERRX);
+     }
+ 
+     while ((zstream.avail_in = PR_Read(readfp, inbuf, BUFSIZ)) > 0) {
+         zstream.next_in = inbuf;
+diff --git a/security/nss/cmd/smimetools/cmsutil.c b/security/nss/cmd/smimetools/cmsutil.c
+--- a/security/nss/cmd/smimetools/cmsutil.c
++++ b/security/nss/cmd/smimetools/cmsutil.c
+@@ -63,17 +63,17 @@ DigestFile(PLArenaPool *poolp, SECItem *
+ 
+     NSS_CMSDigestContext_Update(digcx, input->data, input->len);
+ 
+     rv = NSS_CMSDigestContext_FinishMultiple(digcx, poolp, digests);
+     return rv;
+ }
+ 
+ static void
+-Usage(char *progName)
++Usage(void)
+ {
+     fprintf(stderr,
+             "Usage:  %s [-C|-D|-E|-O|-S] [<options>] [-d dbdir] [-u certusage]\n"
+             " -C            create a CMS encrypted data message\n"
+             " -D            decode a CMS message\n"
+             "  -b           decode a batch of files named in infile\n"
+             "  -c content   use this detached content\n"
+             "  -n           suppress output of content\n"
+@@ -275,17 +275,16 @@ decode(FILE *out, SECItem *input, const 
+                 nsigners = NSS_CMSSignedData_SignerInfoCount(sigd);
+                 if (decodeOptions->headerLevel >= 0)
+                     fprintf(out, "nsigners=%d; ", nsigners);
+                 if (nsigners == 0) {
+                     /* Might be a cert transport message
+                     ** or might be an invalid message, such as a QA test message
+                     ** or a message from an attacker.
+                     */
+-                    SECStatus rv;
+                     rv = NSS_CMSSignedData_VerifyCertsOnly(sigd,
+                                                            decodeOptions->options->certHandle,
+                                                            decodeOptions->options->certUsage);
+                     if (rv != SECSuccess) {
+                         fprintf(stderr, "cmsutil: Verify certs-only failed!\n");
+                         goto loser;
+                     }
+                     return cmsg;
+@@ -1122,27 +1121,27 @@ main(int argc, char **argv)
+             case 'E':
+                 mode = ENVELOPE;
+                 break;
+             case 'G':
+                 if (mode != SIGN) {
+                     fprintf(stderr,
+                             "%s: option -G only supported with option -S.\n",
+                             progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 signOptions.signingTime = PR_TRUE;
+                 break;
+             case 'H':
+                 if (mode != SIGN) {
+                     fprintf(stderr,
+                             "%s: option -H only supported with option -S.\n",
+                             progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 decodeOptions.suppressContent = PR_TRUE;
+                 if (!strcmp(optstate->value, "MD2"))
+                     signOptions.hashAlgTag = SEC_OID_MD2;
+                 else if (!strcmp(optstate->value, "MD4"))
+                     signOptions.hashAlgTag = SEC_OID_MD4;
+                 else if (!strcmp(optstate->value, "MD5"))
+@@ -1162,75 +1161,75 @@ main(int argc, char **argv)
+                     exit(1);
+                 }
+                 break;
+             case 'N':
+                 if (mode != SIGN) {
+                     fprintf(stderr,
+                             "%s: option -N only supported with option -S.\n",
+                             progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 signOptions.nickname = PORT_Strdup(optstate->value);
+                 break;
+             case 'O':
+                 mode = CERTSONLY;
+                 break;
+             case 'P':
+                 if (mode != SIGN) {
+                     fprintf(stderr,
+                             "%s: option -P only supported with option -S.\n",
+                             progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 signOptions.smimeProfile = PR_TRUE;
+                 break;
+             case 'S':
+                 mode = SIGN;
+                 break;
+             case 'T':
+                 if (mode != SIGN) {
+                     fprintf(stderr,
+                             "%s: option -T only supported with option -S.\n",
+                             progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 signOptions.detached = PR_TRUE;
+                 break;
+             case 'Y':
+                 if (mode != SIGN) {
+                     fprintf(stderr,
+                             "%s: option -Y only supported with option -S.\n",
+                             progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 signOptions.encryptionKeyPreferenceNick = strdup(optstate->value);
+                 break;
+ 
+             case 'b':
+                 if (mode != DECODE) {
+                     fprintf(stderr,
+                             "%s: option -b only supported with option -D.\n",
+                             progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 batch = PR_TRUE;
+                 break;
+ 
+             case 'c':
+                 if (mode != DECODE) {
+                     fprintf(stderr,
+                             "%s: option -c only supported with option -D.\n",
+                             progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 contentFile = PR_Open(optstate->value, PR_RDONLY, 006600);
+                 if (contentFile == NULL) {
+                     fprintf(stderr, "%s: unable to open \"%s\" for reading.\n",
+                             progName, optstate->value);
+                     exit(1);
+                 }
+@@ -1256,17 +1255,17 @@ main(int argc, char **argv)
+                 encryptOptions.envFile = PR_Open(envFileName, PR_RDONLY, 00660);
+                 break;
+ 
+             case 'h':
+                 if (mode != DECODE) {
+                     fprintf(stderr,
+                             "%s: option -h only supported with option -D.\n",
+                             progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 decodeOptions.headerLevel = atoi(optstate->value);
+                 if (decodeOptions.headerLevel < 0) {
+                     fprintf(stderr, "option -h cannot have a negative value.\n");
+                     exit(1);
+                 }
+                 break;
+@@ -1283,64 +1282,64 @@ main(int argc, char **argv)
+                 }
+                 break;
+ 
+             case 'k':
+                 if (mode != DECODE) {
+                     fprintf(stderr,
+                             "%s: option -k only supported with option -D.\n",
+                             progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 decodeOptions.keepCerts = PR_TRUE;
+                 break;
+ 
+             case 'n':
+                 if (mode != DECODE) {
+                     fprintf(stderr,
+                             "%s: option -n only supported with option -D.\n",
+                             progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 decodeOptions.suppressContent = PR_TRUE;
+                 break;
+             case 'o':
+                 outFile = fopen(optstate->value, "wb");
+                 if (outFile == NULL) {
+                     fprintf(stderr, "%s: unable to open \"%s\" for writing\n",
+                             progName, optstate->value);
+                     exit(1);
+                 }
+                 break;
+             case 'p':
+                 if (!optstate->value) {
+                     fprintf(stderr, "%s: option -p must have a value.\n", progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+ 
+                 options.password = strdup(optstate->value);
+                 break;
+ 
+             case 'f':
+                 if (!optstate->value) {
+                     fprintf(stderr, "%s: option -f must have a value.\n", progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+ 
+                 options.pwfile = strdup(optstate->value);
+                 break;
+ 
+             case 'r':
+                 if (!optstate->value) {
+                     fprintf(stderr, "%s: option -r must have a value.\n", progName);
+-                    Usage(progName);
++                    Usage();
+                     exit(1);
+                 }
+                 envelopeOptions.recipients = ptrarray;
+                 str = (char *)optstate->value;
+                 do {
+                     tok = strchr(str, ',');
+                     if (tok)
+                         *tok = '\0';
+@@ -1363,21 +1362,21 @@ main(int argc, char **argv)
+                 break;
+             }
+             case 'v':
+                 cms_verbose = 1;
+                 break;
+         }
+     }
+     if (status == PL_OPT_BAD)
+-        Usage(progName);
++        Usage();
+     PL_DestroyOptState(optstate);
+ 
+     if (mode == UNKNOWN)
+-        Usage(progName);
++        Usage();
+ 
+     if (mode != CERTSONLY && !batch) {
+         rv = SECU_FileToItem(&input, inFile);
+         if (rv != SECSuccess) {
+             SECU_PrintError(progName, "unable to read infile");
+             exit(1);
+         }
+     }
+@@ -1524,17 +1523,17 @@ main(int argc, char **argv)
+             cmsg = signed_data_certsonly(&certsonlyOptions);
+             if (!cmsg) {
+                 SECU_PrintError(progName, "problem with certs-only");
+                 exitstatus = 1;
+             }
+             break;
+         default:
+             fprintf(stderr, "One of options -D, -S or -E must be set.\n");
+-            Usage(progName);
++            Usage();
+             exitstatus = 1;
+     }
+ 
+     if (signOptions.nickname) {
+         PORT_Free(signOptions.nickname);
+     }
+ 
+     if ((mode == SIGN || mode == ENVELOPE || mode == CERTSONLY) &&
+diff --git a/security/nss/cmd/strsclnt/strsclnt.c b/security/nss/cmd/strsclnt/strsclnt.c
+--- a/security/nss/cmd/strsclnt/strsclnt.c
++++ b/security/nss/cmd/strsclnt/strsclnt.c
+@@ -132,17 +132,17 @@ SECItem bigBuf;
+ #define PRINTF   \
+     if (verbose) \
+     printf
+ #define FPRINTF  \
+     if (verbose) \
+     fprintf
+ 
+ static void
+-Usage(const char *progName)
++Usage(void)
+ {
+     fprintf(stderr,
+             "Usage: %s [-n nickname] [-p port] [-d dbdir] [-c connections]\n"
+             "          [-BDNovqs] [-f filename] [-N | -P percentage]\n"
+             "          [-w dbpasswd] [-C cipher(s)] [-t threads] [-W pwfile]\n"
+             "          [-V [min-version]:[max-version]] [-a sniHostName] hostname\n"
+             " where -v means verbose\n"
+             "       -o flag is interpreted as follows:\n"
+@@ -255,17 +255,16 @@ myBadCertHandler(void *arg, PRFileDesc *
+                 err, SECU_Strerror(err));
+     return (MakeCertOK ? SECSuccess : SECFailure);
+ }
+ 
+ void
+ printSecurityInfo(PRFileDesc *fd)
+ {
+     CERTCertificate *cert = NULL;
+-    SSL3Statistics *ssl3stats = SSL_GetStatistics();
+     SECStatus result;
+     SSLChannelInfo channel;
+     SSLCipherSuiteInfo suite;
+ 
+     static int only_once;
+ 
+     if (only_once && verbose < 2)
+         return;
+@@ -1090,17 +1089,16 @@ client_main(
+         int ndx;
+ 
+         /* disable all the ciphers, then enable the ones we want. */
+         disableAllSSLCiphers();
+ 
+         while (0 != (ndx = *cipherString)) {
+             const char *startCipher = cipherString++;
+             int cipher = 0;
+-            SECStatus rv;
+ 
+             if (ndx == ':') {
+                 cipher = hexchar_to_int(*cipherString++);
+                 cipher <<= 4;
+                 cipher |= hexchar_to_int(*cipherString++);
+                 cipher <<= 4;
+                 cipher |= hexchar_to_int(*cipherString++);
+                 cipher <<= 4;
+@@ -1348,17 +1346,17 @@ main(int argc, char **argv)
+                 ThrottleUp = PR_TRUE;
+                 break;
+ 
+             case 'V':
+                 if (SECU_ParseSSLVersionRangeString(optstate->value,
+                                                     enabledVersions, &enabledVersions) !=
+                     SECSuccess) {
+                     fprintf(stderr, "Bad version specified.\n");
+-                    Usage(progName);
++                    Usage();
+                 }
+                 break;
+ 
+             case 'a':
+                 sniHostName = PL_strdup(optstate->value);
+                 break;
+ 
+             case 'c':
+@@ -1426,37 +1424,37 @@ main(int argc, char **argv)
+                 break;
+ 
+             case 'z':
+                 enableCompression = PR_TRUE;
+                 break;
+ 
+             case 0: /* positional parameter */
+                 if (hostName) {
+-                    Usage(progName);
++                    Usage();
+                 }
+                 hostName = PL_strdup(optstate->value);
+                 break;
+ 
+             default:
+             case '?':
+-                Usage(progName);
++                Usage();
+                 break;
+         }
+     }
+     PL_DestroyOptState(optstate);
+ 
+     if (!hostName || status == PL_OPT_BAD)
+-        Usage(progName);
++        Usage();
+ 
+     if (fullhs != NO_FULLHS_PERCENTAGE && (fullhs < 0 || fullhs > 100 || NoReuse))
+-        Usage(progName);
++        Usage();
+ 
+     if (port == 0)
+-        Usage(progName);
++        Usage();
+ 
+     if (fileName)
+         readBigFile(fileName);
+ 
+     PK11_SetPasswordFunc(SECU_GetModulePassword);
+ 
+     tmp = PR_GetEnvSecure("NSS_DEBUG_TIMEOUT");
+     if (tmp && tmp[0]) {
+diff --git a/security/nss/cmd/symkeyutil/symkeyutil.c b/security/nss/cmd/symkeyutil/symkeyutil.c
+--- a/security/nss/cmd/symkeyutil/symkeyutil.c
++++ b/security/nss/cmd/symkeyutil/symkeyutil.c
+@@ -1029,20 +1029,20 @@ main(int argc, char **argv)
+     }
+ 
+     /*  Move key (-M)  */
+     if (symKeyUtil.commands[cmd_MoveKey].activated) {
+         PK11SlotInfo *target;
+         char *targetName = symKeyUtil.options[opt_TargetToken].arg;
+         PK11SymKey *newKey;
+         PK11SymKey *symKey = FindKey(slot, name, &keyID, &pwdata);
+-        char *keyName = PK11_GetSymKeyNickname(symKey);
++        char *keyName;
+ 
+         if (!symKey) {
+-            char *keyName = keyID.data ? BufToHex(&keyID) : PORT_Strdup(name);
++            keyName = keyID.data ? BufToHex(&keyID) : PORT_Strdup(name);
+             PR_fprintf(PR_STDERR, "%s: Couldn't find key %s on %s\n",
+                        progName, keyName, PK11_GetTokenName(slot));
+             PORT_Free(keyName);
+             goto shutdown;
+         }
+         target = PK11_FindSlotByName(targetName);
+         if (!target) {
+             PR_fprintf(PR_STDERR, "%s: Couldn't find slot %s\n",
+@@ -1056,16 +1056,17 @@ main(int argc, char **argv)
+             goto shutdown;
+         }
+         rv = SECFailure;
+         newKey = PK11_MoveSymKey(target, CKA_ENCRYPT, 0, PR_TRUE, symKey);
+         if (!newKey) {
+             PR_fprintf(PR_STDERR, "%s: Couldn't move the key \n", progName);
+             goto shutdown;
+         }
++        keyName = PK11_GetSymKeyNickname(symKey);
+         if (keyName) {
+             rv = PK11_SetSymKeyNickname(newKey, keyName);
+             if (rv != SECSuccess) {
+                 PK11_DeleteTokenSymKey(newKey);
+                 PK11_FreeSymKey(newKey);
+                 PR_fprintf(PR_STDERR, "%s: Couldn't set nickname on key\n",
+                            progName);
+                 goto shutdown;
+diff --git a/security/nss/cmd/tstclnt/tstclnt.c b/security/nss/cmd/tstclnt/tstclnt.c
+--- a/security/nss/cmd/tstclnt/tstclnt.c
++++ b/security/nss/cmd/tstclnt/tstclnt.c
+@@ -167,31 +167,31 @@ printSecurityInfo(PRFileDesc *fd)
+     if (scts && scts->len) {
+         fprintf(stderr, "Received a Signed Certificate Timestamp of length"
+                         " %u\n",
+                 scts->len);
+     }
+ }
+ 
+ static void
+-PrintUsageHeader(const char *progName)
++PrintUsageHeader()
+ {
+     fprintf(stderr,
+             "Usage:  %s -h host [-a 1st_hs_name ] [-a 2nd_hs_name ] [-p port]\n"
+             "[-D | -d certdir] [-C] [-b | -R root-module] \n"
+             "[-n nickname] [-Bafosvx] [-c ciphers] [-Y] [-Z]\n"
+             "[-V [min-version]:[max-version]] [-K] [-T] [-U]\n"
+             "[-r N] [-w passwd] [-W pwfile] [-q [-t seconds]] [-I groups]\n"
+             "[-A requestfile] [-L totalconnections] [-P {client,server}] [-Q]\n"
+             "\n",
+             progName);
+ }
+ 
+ static void
+-PrintParameterUsage(void)
++PrintParameterUsage()
+ {
+     fprintf(stderr, "%-20s Send different SNI name. 1st_hs_name - at first\n"
+                     "%-20s handshake, 2nd_hs_name - at second handshake.\n"
+                     "%-20s Default is host from the -h argument.\n",
+             "-a name",
+             "", "");
+     fprintf(stderr, "%-20s Hostname to connect with\n", "-h host");
+     fprintf(stderr, "%-20s Port number for SSL server\n", "-p port");
+@@ -254,27 +254,27 @@ PrintParameterUsage(void)
+                     "%-20s P256, P384, P521, x25519, FF2048, FF3072, FF4096, FF6144, FF8192\n",
+             "-I", "", "");
+     fprintf(stderr, "%-20s Enable alternative TLS 1.3 handshake\n", "-X alt-server-hello");
+     fprintf(stderr, "%-20s Use DTLS\n", "-P {client, server}");
+     fprintf(stderr, "%-20s Exit after handshake\n", "-Q");
+ }
+ 
+ static void
+-Usage(const char *progName)
++Usage()
+ {
+-    PrintUsageHeader(progName);
++    PrintUsageHeader();
+     PrintParameterUsage();
+     exit(1);
+ }
+ 
+ static void
+-PrintCipherUsage(const char *progName)
++PrintCipherUsage()
+ {
+-    PrintUsageHeader(progName);
++    PrintUsageHeader();
+     fprintf(stderr, "%-20s Letter(s) chosen from the following list\n",
+             "-c ciphers");
+     fprintf(stderr,
+             "c    SSL3 RSA WITH RC4 128 MD5\n"
+             "d    SSL3 RSA WITH 3DES EDE CBC SHA\n"
+             "e    SSL3 RSA WITH DES CBC SHA\n"
+             "i    SSL3 RSA WITH NULL MD5\n"
+             "n    SSL3 RSA WITH RC4 128 SHA\n"
+@@ -298,17 +298,17 @@ PrintCipherUsage(const char *progName)
+ void
+ milliPause(PRUint32 milli)
+ {
+     PRIntervalTime ticks = PR_MillisecondsToInterval(milli);
+     PR_Sleep(ticks);
+ }
+ 
+ void
+-disableAllSSLCiphers(void)
++disableAllSSLCiphers()
+ {
+     const PRUint16 *cipherSuites = SSL_GetImplementedCiphers();
+     int i = SSL_GetNumImplementedCiphers();
+     SECStatus rv;
+ 
+     /* disable all the SSL3 cipher suites */
+     while (--i >= 0) {
+         PRUint16 suite = cipherSuites[i];
+@@ -839,17 +839,17 @@ separateReqHeader(const PRFileDesc *outF
+ #define HEXCHAR_TO_INT(c, i)                   \
+     if (((c) >= '0') && ((c) <= '9')) {        \
+         i = (c) - '0';                         \
+     } else if (((c) >= 'a') && ((c) <= 'f')) { \
+         i = (c) - 'a' + 10;                    \
+     } else if (((c) >= 'A') && ((c) <= 'F')) { \
+         i = (c) - 'A' + 10;                    \
+     } else {                                   \
+-        Usage(progName);                       \
++        Usage();                               \
+     }
+ 
+ static SECStatus
+ restartHandshakeAfterServerCertIfNeeded(PRFileDesc *fd,
+                                         ServerCertAuth *serverCertAuth,
+                                         PRBool override)
+ {
+     SECStatus rv;
+@@ -1010,27 +1010,27 @@ handshakeCallback(PRFileDesc *fd, void *
+     if (stopAfterHandshake) {
+         requestToExit = PR_TRUE;
+     }
+ }
+ 
+ #define REQUEST_WAITING (requestString && !requestSent)
+ 
+ static SECStatus
+-installServerCertificate(PRFileDesc *s, char *nickname)
++installServerCertificate(PRFileDesc *s, char *nick)
+ {
+     CERTCertificate *cert;
+     SECKEYPrivateKey *privKey = NULL;
+ 
+-    if (!nickname) {
++    if (!nick) {
+         PORT_SetError(SEC_ERROR_INVALID_ARGS);
+         return SECFailure;
+     }
+ 
+-    cert = PK11_FindCertFromNickname(nickname, &pwdata);
++    cert = PK11_FindCertFromNickname(nick, &pwdata);
+     if (cert == NULL) {
+         return SECFailure;
+     }
+ 
+     privKey = PK11_FindKeyByAnyCert(cert, &pwdata);
+     if (privKey == NULL) {
+         return SECFailure;
+     }
+@@ -1124,17 +1124,17 @@ connectToServer(PRFileDesc *s, PRPollDes
+             return SECFailure;
+         }
+     }
+ 
+     return SECSuccess;
+ }
+ 
+ static int
+-run(void)
++run()
+ {
+     int headerSeparatorPtrnId = 0;
+     int error = 0;
+     SECStatus rv;
+     PRStatus status;
+     PRInt32 filesReady;
+     int npds;
+     PRFileDesc *s = NULL;
+@@ -1220,29 +1220,28 @@ run(void)
+                 HEXCHAR_TO_INT(*cipherString, ctmp)
+                 cipher |= (ctmp << 4);
+                 cipherString++;
+                 HEXCHAR_TO_INT(*cipherString, ctmp)
+                 cipher |= ctmp;
+                 cipherString++;
+             } else {
+                 if (!isalpha(ndx))
+-                    Usage(progName);
++                    Usage();
+                 ndx = tolower(ndx) - 'a';
+                 if (ndx < PR_ARRAY_SIZE(ssl3CipherSuites)) {
+                     cipher = ssl3CipherSuites[ndx];
+                 }
+             }
+             if (cipher > 0) {
+-                SECStatus status;
+-                status = SSL_CipherPrefSet(s, cipher, SSL_ALLOWED);
+-                if (status != SECSuccess)
++                rv = SSL_CipherPrefSet(s, cipher, SSL_ALLOWED);
++                if (rv != SECSuccess)
+                     SECU_PrintError(progName, "SSL_CipherPrefSet()");
+             } else {
+-                Usage(progName);
++                Usage();
+             }
+         }
+         PORT_Free(cstringSaved);
+     }
+ 
+     rv = SSL_VersionRangeSet(s, &enabledVersions);
+     if (rv != SECSuccess) {
+         SECU_PrintError(progName, "error setting SSL/TLS version range ");
+@@ -1648,28 +1647,28 @@ main(int argc, char **argv)
+     /* XXX: 'B' was used in the past but removed in 3.28,
+      *      please leave some time before resuing it. */
+     optstate = PL_CreateOptState(argc, argv,
+                                  "46A:CDFGHI:KL:M:OP:QR:STUV:W:X:YZa:bc:d:fgh:m:n:op:qr:st:uvw:z");
+     while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
+         switch (optstate->option) {
+             case '?':
+             default:
+-                Usage(progName);
++                Usage();
+                 break;
+ 
+             case '4':
+                 allowIPv6 = PR_FALSE;
+                 if (!allowIPv4)
+-                    Usage(progName);
++                    Usage();
+                 break;
+             case '6':
+                 allowIPv4 = PR_FALSE;
+                 if (!allowIPv6)
+-                    Usage(progName);
++                    Usage();
+                 break;
+ 
+             case 'A':
+                 requestStringLen = ReadFile(optstate->value, &requestString);
+                 if (requestStringLen < 0) {
+                     fprintf(stderr, "Couldn't read file %s\n", optstate->value);
+                     exit(1);
+                 }
+@@ -1730,17 +1729,17 @@ main(int argc, char **argv)
+                 break;
+ 
+             case 'P':
+                 useDTLS = PR_TRUE;
+                 if (!strcmp(optstate->value, "server")) {
+                     actAsServer = 1;
+                 } else {
+                     if (strcmp(optstate->value, "client")) {
+-                        Usage(progName);
++                        Usage();
+                     }
+                 }
+                 break;
+ 
+             case 'Q':
+                 stopAfterHandshake = PR_TRUE;
+                 break;
+ 
+@@ -1763,35 +1762,35 @@ main(int argc, char **argv)
+             case 'V':
+                 versionString = PORT_Strdup(optstate->value);
+                 break;
+ 
+             case 'X':
+                 if (!strcmp(optstate->value, "alt-server-hello")) {
+                     enableAltServerHello = PR_TRUE;
+                 } else {
+-                    Usage(progName);
++                    Usage();
+                 }
+                 break;
+             case 'Y':
+-                PrintCipherUsage(progName);
++                PrintCipherUsage();
+                 exit(0);
+                 break;
+ 
+             case 'Z':
+                 enableZeroRtt = PR_TRUE;
+                 break;
+ 
+             case 'a':
+                 if (!hs1SniHostName) {
+                     hs1SniHostName = PORT_Strdup(optstate->value);
+                 } else if (!hs2SniHostName) {
+                     hs2SniHostName = PORT_Strdup(optstate->value);
+                 } else {
+-                    Usage(progName);
++                    Usage();
+                 }
+                 break;
+ 
+             case 'b':
+                 loadDefaultRootCAs = PR_TRUE;
+                 break;
+ 
+             case 'c':
+@@ -1870,42 +1869,42 @@ main(int argc, char **argv)
+                 enableCompression = 1;
+                 break;
+ 
+             case 'I':
+                 rv = parseGroupList(optstate->value, &enabledGroups, &enabledGroupsCount);
+                 if (rv != SECSuccess) {
+                     PL_DestroyOptState(optstate);
+                     fprintf(stderr, "Bad group specified.\n");
+-                    Usage(progName);
++                    Usage();
+                 }
+                 break;
+         }
+     }
+     PL_DestroyOptState(optstate);
+ 
+     SSL_VersionRangeGetSupported(useDTLS ? ssl_variant_datagram : ssl_variant_stream, &enabledVersions);
+ 
+     if (versionString) {
+         if (SECU_ParseSSLVersionRangeString(versionString,
+                                             enabledVersions, &enabledVersions) !=
+             SECSuccess) {
+             fprintf(stderr, "Bad version specified.\n");
+-            Usage(progName);
++            Usage();
+         }
+         PORT_Free(versionString);
+     }
+ 
+     if (optstatus == PL_OPT_BAD) {
+-        Usage(progName);
++        Usage();
+     }
+ 
+     if (!host || !portno) {
+         fprintf(stderr, "%s: parameters -h and -p are mandatory\n", progName);
+-        Usage(progName);
++        Usage();
+     }
+ 
+     if (serverCertAuth.testFreshStatusFromSideChannel &&
+         serverCertAuth.shouldPause) {
+         fprintf(stderr, "%s: -F requires the use of -O\n", progName);
+         exit(1);
+     }
+ 
+diff --git a/security/nss/cmd/vfyserv/vfyserv.c b/security/nss/cmd/vfyserv/vfyserv.c
+--- a/security/nss/cmd/vfyserv/vfyserv.c
++++ b/security/nss/cmd/vfyserv/vfyserv.c
+@@ -322,19 +322,17 @@ do_connects(void *a, int connection)
+         return secStatus;
+     }
+ 
+     PR_Close(sslSocket);
+     return SECSuccess;
+ }
+ 
+ void
+-client_main(unsigned short port,
+-            int connections,
+-            const char *hostName)
++client_main(int connections)
+ {
+     int i;
+     SECStatus secStatus;
+     PRStatus prStatus;
+     PRInt32 rv;
+     PRNetAddr addr;
+     PRHostEnt hostEntry;
+     char buffer[PR_NETDB_BUF_SIZE];
+@@ -548,17 +546,17 @@ main(int argc, char **argv)
+             if (cipher > 0) {
+                 SSL_CipherPrefSetDefault(cipher, PR_TRUE);
+             } else {
+                 Usage(progName);
+             }
+         }
+     }
+ 
+-    client_main(port, connections, hostName);
++    client_main(connections);
+ 
+ cleanup:
+     if (doOcspCheck) {
+         CERTCertDBHandle *handle = CERT_GetDefaultCertDB();
+         CERT_DisableOCSPDefaultResponder(handle);
+         CERT_DisableOCSPChecking(handle);
+     }
+ 
+diff --git a/security/nss/cmd/vfyserv/vfyutil.c b/security/nss/cmd/vfyserv/vfyutil.c
+--- a/security/nss/cmd/vfyserv/vfyutil.c
++++ b/security/nss/cmd/vfyserv/vfyutil.c
+@@ -305,23 +305,23 @@ myHandshakeCallback(PRFileDesc *socket, 
+ **
+ ** Routines for disabling SSL ciphers.
+ **
+ **************************************************************************/
+ 
+ void
+ disableAllSSLCiphers(void)
+ {
+-    const PRUint16 *cipherSuites = SSL_ImplementedCiphers;
++    const PRUint16 *allSuites = SSL_ImplementedCiphers;
+     int i = SSL_NumImplementedCiphers;
+     SECStatus rv;
+ 
+     /* disable all the SSL3 cipher suites */
+     while (--i >= 0) {
+-        PRUint16 suite = cipherSuites[i];
++        PRUint16 suite = allSuites[i];
+         rv = SSL_CipherPrefSetDefault(suite, PR_FALSE);
+         if (rv != SECSuccess) {
+             fprintf(stderr,
+                     "SSL_CipherPrefSetDefault didn't like value 0x%04x (i = %d)\n",
+                     suite, i);
+             errWarn("SSL_CipherPrefSetDefault");
+             exit(2);
+         }
+diff --git a/security/nss/coreconf/Werror.mk b/security/nss/coreconf/Werror.mk
+--- a/security/nss/coreconf/Werror.mk
++++ b/security/nss/coreconf/Werror.mk
+@@ -43,19 +43,21 @@ ifndef GCC_VERSION
+ endif
+ 
+ ifndef WARNING_CFLAGS
+   ifneq (1,$(CC_IS_GCC))
+     WARNING_CFLAGS = $(NULL)
+   else
+     # This tests to see if enabling the warning is possible before
+     # setting an option to disable it.
+-    disable_warning = $(shell $(CC) -x c -E -Werror -W$(1) /dev/null >/dev/null 2>&1 && echo -Wno-$(1))
++    set_warning = $(shell $(CC) -x c -E -Werror -W$(1) /dev/null >/dev/null 2>&1 && echo -W$(2)$(1))
++    enable_warning = $(call set_warning,$(1),)
++    disable_warning = $(call set_warning,$(1),no-)
+ 
+-    WARNING_CFLAGS = -Wall
++    WARNING_CFLAGS = -Wall $(call enable_warning,shadow)
+     ifdef CC_IS_CLANG
+       # -Qunused-arguments : clang objects to arguments that it doesn't understand
+       #    and fixing this would require rearchitecture
+       WARNING_CFLAGS += -Qunused-arguments
+       # -Wno-parentheses-equality : because clang warns about macro expansions
+       WARNING_CFLAGS += $(call disable_warning,parentheses-equality)
+       ifdef BUILD_OPT
+         # clang is unable to handle glib's expansion of strcmp and similar for optimized
+diff --git a/security/nss/coreconf/nsinstall/pathsub.c b/security/nss/coreconf/nsinstall/pathsub.c
+--- a/security/nss/coreconf/nsinstall/pathsub.c
++++ b/security/nss/coreconf/nsinstall/pathsub.c
+@@ -207,17 +207,17 @@ reversepath(char *inpath, char *name, in
+ 	    len = strlen(name);
+ 	    cp -= len + 1;
+ 	    strcpy(cp, name);
+ 	    cp[len] = '/';
+ 	    free(name);
+ 	    xchdir("..");
+ 	} else {
+ 	    cp -= 3;
+-	    strncpy(cp, "../", 3);
++	    memcpy(cp, "../", 3);
+ 	    xchdir(buf);
+ 	}
+     }
+     strcpy(outpath, cp);
+ }
+ 
+ void
+ diagnosePath(const char * path)
+diff --git a/security/nss/coreconf/werror.py b/security/nss/coreconf/werror.py
+--- a/security/nss/coreconf/werror.py
++++ b/security/nss/coreconf/werror.py
+@@ -49,12 +49,12 @@ def main():
+         # clang is unable to handle glib's expansion of strcmp and similar for
+         # optimized builds, so disable the resulting errors.
+         # See https://llvm.org/bugs/show_bug.cgi?id=20144
+         for w in ['array-bounds', 'unevaluated-expression',
+                   'parentheses-equality']:
+             set_warning(w, 'no-')
+         print('-Qunused-arguments')
+ 
+-    # set_warning('shadow') # Bug 1309068
++    set_warning('shadow')
+ 
+ if __name__ == '__main__':
+     main()
+diff --git a/security/nss/cpputil/databuffer.cc b/security/nss/cpputil/databuffer.cc
+--- a/security/nss/cpputil/databuffer.cc
++++ b/security/nss/cpputil/databuffer.cc
+@@ -13,22 +13,22 @@
+ #if defined(WIN32) || defined(WIN64)
+ #include <winsock2.h>
+ #else
+ #include <arpa/inet.h>
+ #endif
+ 
+ namespace nss_test {
+ 
+-void DataBuffer::Assign(const uint8_t* data, size_t len) {
+-  if (data) {
+-    Allocate(len);
+-    memcpy(static_cast<void*>(data_), static_cast<const void*>(data), len);
++void DataBuffer::Assign(const uint8_t* d, size_t l) {
++  if (d) {
++    Allocate(l);
++    memcpy(static_cast<void*>(data_), static_cast<const void*>(d), l);
+   } else {
+-    assert(len == 0);
++    assert(l == 0);
+     data_ = nullptr;
+     len_ = 0;
+   }
+ }
+ 
+ // Write will do a new allocation and expand the size of the buffer if needed.
+ // Returns the offset of the end of the write.
+ size_t DataBuffer::Write(size_t index, const uint8_t* val, size_t count) {
+diff --git a/security/nss/cpputil/databuffer.h b/security/nss/cpputil/databuffer.h
+--- a/security/nss/cpputil/databuffer.h
++++ b/security/nss/cpputil/databuffer.h
+@@ -12,42 +12,42 @@
+ #include <iomanip>
+ #include <iostream>
+ 
+ namespace nss_test {
+ 
+ class DataBuffer {
+  public:
+   DataBuffer() : data_(nullptr), len_(0) {}
+-  DataBuffer(const uint8_t* data, size_t len) : data_(nullptr), len_(0) {
+-    Assign(data, len);
++  DataBuffer(const uint8_t* d, size_t l) : data_(nullptr), len_(0) {
++    Assign(d, l);
+   }
+   DataBuffer(const DataBuffer& other) : data_(nullptr), len_(0) {
+     Assign(other);
+   }
+   ~DataBuffer() { delete[] data_; }
+ 
+   DataBuffer& operator=(const DataBuffer& other) {
+     if (&other != this) {
+       Assign(other);
+     }
+     return *this;
+   }
+ 
+-  void Allocate(size_t len) {
++  void Allocate(size_t l) {
+     delete[] data_;
+-    data_ = new uint8_t[len ? len : 1];  // Don't depend on new [0].
+-    len_ = len;
++    data_ = new uint8_t[l ? l : 1];  // Don't depend on new [0].
++    len_ = l;
+   }
+ 
+-  void Truncate(size_t len) { len_ = (std::min)(len_, len); }
++  void Truncate(size_t l) { len_ = (std::min)(len_, l); }
+ 
+   void Assign(const DataBuffer& other) { Assign(other.data(), other.len()); }
+ 
+-  void Assign(const uint8_t* data, size_t len);
++  void Assign(const uint8_t* d, size_t l);
+ 
+   // Write will do a new allocation and expand the size of the buffer if needed.
+   // Returns the offset of the end of the write.
+   size_t Write(size_t index, const uint8_t* val, size_t count);
+   size_t Write(size_t index, const DataBuffer& buf) {
+     return Write(index, buf.data(), buf.len());
+   }
+ 
+diff --git a/security/nss/cpputil/scoped_ptrs.h b/security/nss/cpputil/scoped_ptrs.h
+--- a/security/nss/cpputil/scoped_ptrs.h
++++ b/security/nss/cpputil/scoped_ptrs.h
+@@ -5,17 +5,16 @@
+  * You can obtain one at http://mozilla.org/MPL/2.0/. */
+ 
+ #ifndef scoped_ptrs_h__
+ #define scoped_ptrs_h__
+ 
+ #include <memory>
+ #include "cert.h"
+ #include "keyhi.h"
+-#include "p12.h"
+ #include "pk11pub.h"
+ #include "pkcs11uri.h"
+ #include "sslexp.h"
+ 
+ struct ScopedDelete {
+   void operator()(CERTCertificate* cert) { CERT_DestroyCertificate(cert); }
+   void operator()(CERTCertificateList* list) {
+     CERT_DestroyCertificateList(list);
+@@ -37,19 +36,16 @@ struct ScopedDelete {
+   }
+   void operator()(PK11URI* uri) { PK11URI_DestroyURI(uri); }
+   void operator()(PLArenaPool* arena) { PORT_FreeArena(arena, PR_FALSE); }
+   void operator()(PK11Context* context) { PK11_DestroyContext(context, true); }
+   void operator()(PK11GenericObject* obj) { PK11_DestroyGenericObject(obj); }
+   void operator()(SSLResumptionTokenInfo* token) {
+     SSL_DestroyResumptionTokenInfo(token);
+   }
+-  void operator()(SEC_PKCS12DecoderContext* dcx) {
+-    SEC_PKCS12DecoderFinish(dcx);
+-  }
+ };
+ 
+ template <class T>
+ struct ScopedMaybeDelete {
+   void operator()(T* ptr) {
+     if (ptr) {
+       ScopedDelete del;
+       del(ptr);
+@@ -72,13 +68,12 @@ SCOPED(SECItem);
+ SCOPED(SECKEYPublicKey);
+ SCOPED(SECKEYPrivateKey);
+ SCOPED(SECKEYPrivateKeyList);
+ SCOPED(PK11URI);
+ SCOPED(PLArenaPool);
+ SCOPED(PK11Context);
+ SCOPED(PK11GenericObject);
+ SCOPED(SSLResumptionTokenInfo);
+-SCOPED(SEC_PKCS12DecoderContext);
+ 
+ #undef SCOPED
+ 
+ #endif  // scoped_ptrs_h__
+diff --git a/security/nss/fuzz/fuzz.gyp b/security/nss/fuzz/fuzz.gyp
+--- a/security/nss/fuzz/fuzz.gyp
++++ b/security/nss/fuzz/fuzz.gyp
+@@ -39,16 +39,19 @@
+         '<(DEPTH)/lib/dev/dev.gyp:nssdev',
+         '<(DEPTH)/lib/pki/pki.gyp:nsspki',
+         '<(DEPTH)/lib/util/util.gyp:nssutil',
+         '<(DEPTH)/lib/nss/nss.gyp:nss_static',
+         '<(DEPTH)/lib/pkcs7/pkcs7.gyp:pkcs7',
+         # This is a static build of pk11wrap, softoken, and freebl.
+         '<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap_static',
+       ],
++      'cflags_cc': [
++        '-Wno-error=shadow',
++      ],
+       'conditions': [
+         ['fuzz_oss==0', {
+           'sources': [
+             '<!@(ls <(DEPTH)/fuzz/libFuzzer/*.cpp)',
+           ],
+           'cflags/': [
+             ['exclude', '-fsanitize-coverage'],
+           ],
+diff --git a/security/nss/gtests/der_gtest/der_gtest.gyp b/security/nss/gtests/der_gtest/der_gtest.gyp
+--- a/security/nss/gtests/der_gtest/der_gtest.gyp
++++ b/security/nss/gtests/der_gtest/der_gtest.gyp
+@@ -8,26 +8,23 @@
+   ],
+   'targets': [
+     {
+       'target_name': 'der_gtest',
+       'type': 'executable',
+       'sources': [
+         'der_getint_unittest.cc',
+         'der_quickder_unittest.cc',
+-        'p12_import_unittest.cc',
+         '<(DEPTH)/gtests/common/gtests.cc'
+       ],
+       'dependencies': [
+         '<(DEPTH)/exports.gyp:nss_exports',
+         '<(DEPTH)/gtests/google_test/google_test.gyp:gtest',
+         '<(DEPTH)/lib/util/util.gyp:nssutil3',
+         '<(DEPTH)/lib/ssl/ssl.gyp:ssl3',
+         '<(DEPTH)/lib/nss/nss.gyp:nss3',
+-        '<(DEPTH)/lib/pkcs12/pkcs12.gyp:pkcs12',
+-        '<(DEPTH)/lib/pkcs7/pkcs7.gyp:pkcs7',
+       ]
+     }
+   ],
+   'variables': {
+     'module': 'nss'
+   }
+ }
+diff --git a/security/nss/gtests/der_gtest/manifest.mn b/security/nss/gtests/der_gtest/manifest.mn
+--- a/security/nss/gtests/der_gtest/manifest.mn
++++ b/security/nss/gtests/der_gtest/manifest.mn
+@@ -4,17 +4,16 @@
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ CORE_DEPTH = ../..
+ DEPTH      = ../..
+ MODULE = nss
+ 
+ CPPSRCS = \
+       der_getint_unittest.cc \
+       der_quickder_unittest.cc \
+-      p12_import_unittest.cc \
+       $(NULL)
+ 
+ INCLUDES += -I$(CORE_DEPTH)/gtests/google_test/gtest/include \
+             -I$(CORE_DEPTH)/gtests/common \
+             -I$(CORE_DEPTH)/cpputil
+ 
+ REQUIRES = nspr gtest
+ 
+diff --git a/security/nss/gtests/der_gtest/p12_import_unittest.cc b/security/nss/gtests/der_gtest/p12_import_unittest.cc
+deleted file mode 100644
+--- a/security/nss/gtests/der_gtest/p12_import_unittest.cc
++++ /dev/null
+@@ -1,251 +0,0 @@
+-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+-/* vim: set ts=2 et sw=2 tw=80: */
+-/* This Source Code Form is subject to the terms of the Mozilla Public
+- * 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/. */
+-
+-#include "nss.h"
+-#include "p12.h"
+-
+-#include "gtest/gtest.h"
+-#include "scoped_ptrs.h"
+-
+-namespace nss_test {
+-
+-static const uint8_t cert_p12[] = {
+-    0x30, 0x82, 0x0a, 0x1f, 0x02, 0x01, 0x03, 0x30, 0x82, 0x09, 0xe5, 0x06,
+-    0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x82,
+-    0x09, 0xd6, 0x04, 0x82, 0x09, 0xd2, 0x30, 0x82, 0x09, 0xce, 0x30, 0x82,
+-    0x04, 0x42, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07,
+-    0x06, 0xa0, 0x82, 0x04, 0x33, 0x30, 0x82, 0x04, 0x2f, 0x02, 0x01, 0x00,
+-    0x30, 0x82, 0x04, 0x28, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
+-    0x01, 0x07, 0x01, 0x30, 0x57, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
+-    0x0d, 0x01, 0x05, 0x0d, 0x30, 0x4a, 0x30, 0x29, 0x06, 0x09, 0x2a, 0x86,
+-    0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0c, 0x30, 0x1c, 0x04, 0x08, 0x05,
+-    0x66, 0xc7, 0x5c, 0x27, 0x4e, 0x15, 0xd9, 0x02, 0x02, 0x08, 0x00, 0x30,
+-    0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x09, 0x05,
+-    0x00, 0x30, 0x1d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04,
+-    0x01, 0x2a, 0x04, 0x10, 0x4e, 0x61, 0xa7, 0x23, 0xc4, 0x3b, 0x37, 0xea,
+-    0xba, 0xe9, 0x9f, 0x44, 0x8e, 0x5e, 0xf7, 0xf2, 0x80, 0x82, 0x03, 0xc0,
+-    0x76, 0x7d, 0x91, 0x89, 0xe1, 0x04, 0x59, 0x91, 0x0c, 0x72, 0x14, 0x93,
+-    0xc4, 0x37, 0xe8, 0xd1, 0xbb, 0x49, 0xfc, 0x23, 0x49, 0x19, 0x6f, 0xc9,
+-    0x05, 0x08, 0x52, 0xd8, 0x63, 0xdf, 0x27, 0x63, 0x24, 0x85, 0x73, 0x11,
+-    0xfa, 0x6d, 0xca, 0xed, 0xb2, 0x91, 0x77, 0xc6, 0x1f, 0x0b, 0xdb, 0x4d,
+-    0x66, 0x34, 0xb9, 0x51, 0xef, 0xf0, 0x8f, 0xf8, 0x71, 0x2b, 0x68, 0xf7,
+-    0x5c, 0xdf, 0x99, 0x21, 0x7c, 0xb6, 0xa7, 0x45, 0xdb, 0x71, 0x69, 0x0b,
+-    0xb3, 0x2e, 0xff, 0x84, 0xcd, 0xd1, 0xb8, 0x87, 0xe9, 0xaa, 0x3e, 0xcd,
+-    0x11, 0x90, 0xcb, 0xd8, 0xe7, 0x08, 0x87, 0x32, 0x82, 0x26, 0x69, 0x9b,
+-    0xa6, 0xb1, 0x76, 0xf2, 0x28, 0xe2, 0x6c, 0xf5, 0x50, 0x16, 0x2d, 0x13,
+-    0x75, 0x73, 0xed, 0xd1, 0x40, 0x1b, 0xd9, 0x43, 0xf5, 0x1d, 0x60, 0x98,
+-    0x33, 0x5e, 0x18, 0xb0, 0xba, 0xe0, 0x8a, 0xaa, 0xa4, 0x3b, 0x78, 0x49,
+-    0x59, 0x5f, 0xa4, 0xd5, 0xb5, 0x10, 0xb8, 0x87, 0x46, 0x48, 0xff, 0x5e,
+-    0x91, 0x3b, 0xf9, 0xef, 0x29, 0x92, 0x99, 0xfd, 0x22, 0x8c, 0xcd, 0x05,
+-    0x2e, 0x0a, 0x24, 0xbf, 0xe4, 0x1b, 0x95, 0x86, 0x94, 0xf2, 0xd9, 0x8c,
+-    0x4d, 0xac, 0xe8, 0xb8, 0x49, 0x93, 0x74, 0xcd, 0x79, 0x3f, 0xa4, 0x29,
+-    0x09, 0x5a, 0x00, 0x44, 0xfe, 0x75, 0x53, 0x23, 0x7e, 0xe4, 0xf5, 0x71,
+-    0xcf, 0x1e, 0x48, 0x1d, 0x89, 0x42, 0x67, 0xa6, 0x1d, 0x0d, 0x0b, 0xe0,
+-    0x4a, 0x7a, 0x59, 0xe0, 0x88, 0x63, 0xfc, 0x72, 0x97, 0xc2, 0x9f, 0x5d,
+-    0xc3, 0xb2, 0x75, 0x73, 0x25, 0x10, 0x6f, 0x40, 0x93, 0x4f, 0x7d, 0x69,
+-    0x01, 0x2d, 0xf4, 0xbe, 0xa9, 0xd9, 0x3c, 0x83, 0x77, 0x92, 0xf4, 0xa1,
+-    0x2a, 0x7d, 0x3e, 0xab, 0x2d, 0xa1, 0x53, 0x63, 0x98, 0xaf, 0xc6, 0x11,
+-    0x78, 0x3d, 0x37, 0xa9, 0x3f, 0x9c, 0xa8, 0xce, 0xc1, 0x9f, 0xac, 0x45,
+-    0x9a, 0x2e, 0x38, 0x9f, 0x08, 0xf9, 0x2d, 0x9e, 0xf5, 0xca, 0x4d, 0x33,
+-    0x77, 0x89, 0x2b, 0xde, 0x32, 0x05, 0xe4, 0x39, 0x1a, 0x78, 0x06, 0x7f,
+-    0x74, 0x28, 0xab, 0x07, 0xbc, 0x59, 0xd0, 0x52, 0x11, 0x1b, 0x6a, 0x98,
+-    0x51, 0xed, 0x5c, 0xf7, 0x96, 0x59, 0xad, 0xb1, 0x48, 0x81, 0xc8, 0xde,
+-    0xec, 0xb0, 0x16, 0x7d, 0x61, 0x09, 0xaf, 0x36, 0xe8, 0x2d, 0xd3, 0x88,
+-    0x99, 0x35, 0xf2, 0x72, 0xa5, 0xfd, 0xd9, 0xbe, 0xf5, 0x6d, 0x52, 0x4f,
+-    0xdb, 0x65, 0x1b, 0x06, 0xfd, 0x1f, 0x61, 0xb3, 0xae, 0x03, 0x96, 0x50,
+-    0x96, 0xc4, 0x74, 0x28, 0x26, 0xda, 0x51, 0xc2, 0xd4, 0xff, 0xce, 0xc5,
+-    0x26, 0xea, 0x8c, 0xfd, 0x1e, 0x22, 0x03, 0xf0, 0xcd, 0x00, 0xf2, 0x72,
+-    0xf3, 0x81, 0x46, 0x1e, 0x95, 0xaf, 0xe1, 0xc1, 0x0a, 0x12, 0xfe, 0xb0,
+-    0x97, 0x2d, 0x40, 0xe8, 0x6d, 0xde, 0xe0, 0x9c, 0x7f, 0xad, 0x85, 0x89,
+-    0x28, 0x88, 0x4a, 0x64, 0xc1, 0xa4, 0x2f, 0xb6, 0x25, 0xae, 0x89, 0xb4,
+-    0xab, 0x02, 0xea, 0xca, 0xd6, 0x05, 0x4f, 0x3a, 0x64, 0xd0, 0xbf, 0x2d,
+-    0xba, 0x0a, 0x9c, 0x5a, 0xa5, 0x0b, 0xf5, 0xc7, 0x84, 0x6e, 0xb4, 0x5c,
+-    0x0e, 0x43, 0x96, 0xac, 0xfe, 0xc1, 0xc5, 0x3d, 0x15, 0x2b, 0x4d, 0x67,
+-    0x2a, 0x09, 0xd8, 0x64, 0x83, 0x13, 0x00, 0x10, 0xe1, 0x60, 0x76, 0x9b,
+-    0xf0, 0xa0, 0xdc, 0x8c, 0x4b, 0x4f, 0xc5, 0x93, 0xa8, 0xf8, 0xef, 0xd9,
+-    0x75, 0xdc, 0x62, 0xe9, 0xcf, 0xdf, 0x3f, 0x7b, 0x8d, 0x2c, 0x0e, 0x5a,
+-    0x99, 0xc6, 0x38, 0x4c, 0xd9, 0xfb, 0xe6, 0xb5, 0x1b, 0x6e, 0xbd, 0xae,
+-    0xef, 0x89, 0x71, 0x4e, 0xfd, 0x74, 0x46, 0x35, 0xf9, 0x48, 0x43, 0x11,
+-    0x81, 0xcd, 0x6f, 0xdc, 0xf3, 0x2e, 0x92, 0x93, 0x9e, 0xca, 0xf8, 0xfa,
+-    0xc6, 0x56, 0x75, 0x1e, 0x04, 0x89, 0x7d, 0x1c, 0x2e, 0xdb, 0xbd, 0x5b,
+-    0xec, 0xc8, 0x2d, 0xa3, 0xe2, 0x05, 0xef, 0xe9, 0x5f, 0x05, 0x4b, 0x89,
+-    0x82, 0x0c, 0x1e, 0x8c, 0x74, 0xe1, 0x5a, 0x67, 0xe4, 0x97, 0x9b, 0x22,
+-    0xd7, 0xdc, 0xe2, 0x74, 0xcf, 0x93, 0xc1, 0xca, 0xc6, 0xde, 0xae, 0xc0,
+-    0xd2, 0xf9, 0x57, 0xc5, 0x90, 0x96, 0x48, 0x0a, 0x25, 0x43, 0x75, 0xc1,
+-    0x94, 0xa4, 0xd5, 0x14, 0xb2, 0x27, 0xf8, 0x45, 0xf1, 0x3c, 0x01, 0xd6,
+-    0xb8, 0x73, 0x1c, 0xb6, 0x55, 0xc5, 0xc9, 0x10, 0x28, 0x2f, 0xba, 0x18,
+-    0x36, 0x8d, 0xfe, 0x0b, 0x23, 0xf3, 0x9a, 0x98, 0xfb, 0x2f, 0x59, 0x52,
+-    0x3a, 0x0f, 0x75, 0x60, 0xa0, 0x92, 0x0d, 0x78, 0xf0, 0xc7, 0x5d, 0x9d,
+-    0x3a, 0x72, 0xd0, 0xd1, 0x30, 0x73, 0x9e, 0x3c, 0x03, 0x99, 0x4c, 0xe2,
+-    0xe5, 0xd4, 0x77, 0xfe, 0x3a, 0x92, 0x08, 0x5b, 0x99, 0x51, 0x15, 0x57,
+-    0x05, 0x13, 0x51, 0xc2, 0xf4, 0xb5, 0x2d, 0xae, 0x68, 0x9f, 0x4e, 0xbf,
+-    0x00, 0x11, 0xc1, 0xe1, 0x48, 0xb3, 0xce, 0x36, 0x42, 0x6a, 0x74, 0xd7,
+-    0xe7, 0x84, 0x1e, 0xf3, 0x47, 0xc4, 0xab, 0x59, 0x18, 0x15, 0x31, 0xa4,
+-    0x28, 0x68, 0x16, 0xa3, 0x68, 0xbf, 0x6c, 0xfe, 0x7a, 0x36, 0xd9, 0xc1,
+-    0x22, 0xd6, 0x5e, 0x2d, 0xbb, 0x9a, 0x1f, 0xb6, 0x8c, 0xa6, 0x65, 0x24,
+-    0x3e, 0x01, 0x9c, 0x75, 0x5e, 0x17, 0x42, 0x12, 0x89, 0x85, 0x6f, 0x05,
+-    0xac, 0x54, 0xd5, 0x02, 0xea, 0x1e, 0xc2, 0xe1, 0xcd, 0x61, 0x0e, 0x53,
+-    0xd5, 0x9d, 0x3a, 0x67, 0x1b, 0x50, 0x9b, 0x90, 0x18, 0x66, 0x6d, 0xb2,
+-    0x7f, 0x3a, 0x69, 0xc9, 0xef, 0x07, 0x17, 0x91, 0x8a, 0xe9, 0x15, 0x35,
+-    0xed, 0x70, 0x9e, 0x74, 0x8c, 0xe7, 0xf4, 0xaa, 0xcf, 0xbe, 0xa3, 0x98,
+-    0x89, 0x8d, 0x3c, 0x5e, 0xa4, 0x6b, 0x8f, 0x1b, 0x18, 0x04, 0x79, 0xd2,
+-    0x11, 0x64, 0xb1, 0xc7, 0x68, 0xca, 0xaf, 0x44, 0xa1, 0x39, 0x29, 0x58,
+-    0x70, 0x4e, 0xce, 0xb7, 0x7a, 0x3c, 0x4b, 0xdc, 0x32, 0x92, 0x76, 0x74,
+-    0xab, 0x0a, 0x6f, 0x8b, 0x74, 0xf5, 0xfd, 0xed, 0x3b, 0x11, 0x95, 0xe8,
+-    0x10, 0x74, 0x4c, 0xd8, 0xbe, 0x0f, 0x50, 0xee, 0xa0, 0xee, 0x39, 0xd8,
+-    0x9f, 0xa1, 0xa0, 0x21, 0xa3, 0x47, 0x8c, 0xa6, 0xd9, 0xca, 0x8c, 0xb3,
+-    0x8b, 0x86, 0x9e, 0x31, 0x3b, 0xcc, 0x7f, 0xea, 0x23, 0xb1, 0x25, 0x73,
+-    0xfb, 0x66, 0x99, 0x28, 0xff, 0xf4, 0xe9, 0xb7, 0x19, 0x3e, 0xd5, 0xc6,
+-    0x5d, 0xd1, 0xaa, 0x08, 0x6f, 0xf2, 0xff, 0xab, 0x39, 0x69, 0x1f, 0xd3,
+-    0x6b, 0x20, 0xf3, 0x2f, 0xe4, 0xd5, 0xb8, 0x76, 0x3f, 0x6c, 0x8f, 0x05,
+-    0x3c, 0xe0, 0x18, 0x81, 0x82, 0xca, 0x05, 0x7f, 0xc0, 0x8e, 0x87, 0x50,
+-    0xfb, 0xb1, 0x65, 0xfa, 0x2f, 0xb7, 0xba, 0x20, 0x0b, 0x35, 0x5c, 0x87,
+-    0xba, 0x90, 0x5a, 0x7f, 0xfc, 0xe9, 0xf2, 0x98, 0x5f, 0x6e, 0xb2, 0xcc,
+-    0xef, 0x4b, 0x2d, 0xde, 0xdd, 0x6f, 0xd9, 0x8e, 0x79, 0x89, 0x45, 0xcd,
+-    0x4c, 0xdf, 0x27, 0xf1, 0x26, 0x47, 0x9e, 0x83, 0xdb, 0x73, 0x4a, 0x20,
+-    0x84, 0xde, 0x09, 0xe0, 0x58, 0xfe, 0x19, 0xcb, 0x92, 0xc4, 0x5b, 0x83,
+-    0x30, 0x82, 0x05, 0x84, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
+-    0x01, 0x07, 0x01, 0xa0, 0x82, 0x05, 0x75, 0x04, 0x82, 0x05, 0x71, 0x30,
+-    0x82, 0x05, 0x6d, 0x30, 0x82, 0x05, 0x69, 0x06, 0x0b, 0x2a, 0x86, 0x48,
+-    0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x02, 0xa0, 0x82, 0x05, 0x31,
+-    0x30, 0x82, 0x05, 0x2d, 0x30, 0x57, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
+-    0xf7, 0x0d, 0x01, 0x05, 0x0d, 0x30, 0x4a, 0x30, 0x29, 0x06, 0x09, 0x2a,
+-    0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0c, 0x30, 0x1c, 0x04, 0x08,
+-    0x5c, 0x72, 0x5e, 0xfb, 0xbc, 0x49, 0xaa, 0xa1, 0x02, 0x02, 0x08, 0x00,
+-    0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x09,
+-    0x05, 0x00, 0x30, 0x1d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
+-    0x04, 0x01, 0x2a, 0x04, 0x10, 0xcb, 0xa8, 0xda, 0x75, 0xba, 0x64, 0x22,
+-    0x70, 0x39, 0x3c, 0x83, 0x35, 0x0b, 0x41, 0xc4, 0x49, 0x04, 0x82, 0x04,
+-    0xd0, 0xb3, 0x3d, 0x9b, 0x03, 0x34, 0xdf, 0x62, 0x37, 0xb0, 0xbb, 0x37,
+-    0x0d, 0x88, 0x8c, 0x6b, 0xf2, 0x46, 0x33, 0xa4, 0x4b, 0x48, 0x86, 0x0a,
+-    0x36, 0x37, 0x24, 0x21, 0x08, 0x8e, 0x86, 0xbf, 0x4e, 0x9c, 0xe7, 0xa9,
+-    0x56, 0x4a, 0x02, 0xb4, 0x74, 0x6a, 0x8a, 0x1e, 0x51, 0x91, 0xe3, 0x8f,
+-    0xe3, 0xf6, 0xca, 0x0a, 0x2d, 0xe7, 0x09, 0x5e, 0x1e, 0x59, 0x46, 0x01,
+-    0xda, 0xe9, 0x5b, 0xb9, 0xd8, 0x15, 0x7c, 0x05, 0xd9, 0x5f, 0x8c, 0x3d,
+-    0xd4, 0xb2, 0xff, 0x25, 0x9d, 0xfe, 0x0e, 0xe3, 0x0c, 0xf0, 0x7f, 0x30,
+-    0x25, 0x92, 0x0e, 0x44, 0xf4, 0x16, 0xc7, 0xa2, 0x22, 0xb2, 0x31, 0xfa,
+-    0x55, 0x97, 0xf7, 0xd0, 0xd7, 0x58, 0x1f, 0x96, 0x81, 0x06, 0x86, 0xbb,
+-    0x07, 0x30, 0x9d, 0x01, 0xb8, 0x15, 0xb2, 0x81, 0xa9, 0x35, 0x09, 0x2c,
+-    0x97, 0xbc, 0x8e, 0x2e, 0x2e, 0x30, 0x20, 0x51, 0x94, 0x9d, 0x9f, 0xbd,
+-    0x83, 0x48, 0x7b, 0x25, 0xfc, 0x95, 0x42, 0xd7, 0x29, 0xd5, 0x67, 0xcd,
+-    0x48, 0xc6, 0x78, 0xe1, 0x6d, 0xdf, 0xf8, 0x0b, 0x3a, 0x95, 0xcc, 0xd0,
+-    0x93, 0xfe, 0x23, 0x8d, 0x99, 0xd9, 0x8c, 0x67, 0x38, 0x9f, 0xd0, 0x4c,
+-    0xff, 0x32, 0x45, 0x32, 0xa9, 0xe8, 0x9d, 0xbc, 0xbf, 0xaa, 0xb2, 0x49,
+-    0xaa, 0x1d, 0xa0, 0x04, 0x53, 0x14, 0xa4, 0x77, 0x96, 0x3f, 0x17, 0xbb,
+-    0x2e, 0x14, 0xbe, 0x39, 0x6b, 0x69, 0x16, 0x7a, 0x99, 0xb2, 0xf4, 0x16,
+-    0x1a, 0xb7, 0xaa, 0x0a, 0x97, 0xd9, 0x1d, 0x62, 0xbe, 0xfc, 0x38, 0x00,
+-    0x6c, 0x65, 0x75, 0xe0, 0xb0, 0x65, 0x8f, 0xb6, 0x4b, 0xe7, 0x21, 0x41,
+-    0x65, 0x65, 0x5a, 0x7c, 0x5b, 0xe8, 0x70, 0x83, 0x71, 0xd6, 0x65, 0x7c,
+-    0x4f, 0x00, 0x90, 0x55, 0xca, 0xff, 0xc9, 0x3f, 0x61, 0x1e, 0xc0, 0x41,
+-    0x67, 0x0c, 0x71, 0xb2, 0xef, 0x12, 0x8e, 0xb1, 0xaa, 0xcf, 0xf1, 0x78,
+-    0x9f, 0x5b, 0xb9, 0x7b, 0xbe, 0x04, 0x39, 0xf0, 0x87, 0xca, 0x3a, 0x77,
+-    0x31, 0xab, 0x85, 0x8f, 0x4f, 0x06, 0xad, 0x45, 0xf2, 0xe2, 0xc2, 0x20,
+-    0x74, 0xf1, 0xdc, 0x21, 0x3f, 0x79, 0x0d, 0xcc, 0xcf, 0x7f, 0xb9, 0x85,
+-    0x9e, 0x1a, 0x1b, 0x84, 0xe2, 0x5b, 0xe3, 0x77, 0x27, 0x91, 0xcc, 0xf2,
+-    0xe4, 0xf2, 0x19, 0xdd, 0x98, 0x64, 0x9d, 0xcb, 0xf1, 0xc5, 0xe6, 0x7b,
+-    0x75, 0x55, 0x4e, 0xa5, 0xca, 0xe3, 0x5b, 0xbe, 0xc2, 0xcd, 0x83, 0x27,
+-    0x92, 0xe1, 0x23, 0x3f, 0xd7, 0x3d, 0xb7, 0x3a, 0x8b, 0x3a, 0x26, 0xc1,
+-    0xfb, 0xed, 0x69, 0x7a, 0xab, 0xec, 0x0a, 0xe5, 0xaa, 0x81, 0x9f, 0xdf,
+-    0x97, 0x45, 0x64, 0x35, 0x7d, 0xad, 0x88, 0x4a, 0x75, 0x13, 0xc3, 0x13,
+-    0xd6, 0x9a, 0xf3, 0xa2, 0x94, 0xf7, 0x96, 0x09, 0xa7, 0xbe, 0xb8, 0xe4,
+-    0x29, 0x7d, 0xb0, 0xef, 0x4a, 0x5d, 0x0d, 0x02, 0xb4, 0x10, 0x54, 0x17,
+-    0x62, 0xef, 0xe2, 0xad, 0x89, 0x6d, 0x91, 0x51, 0x7e, 0x35, 0x28, 0xb4,
+-    0xe7, 0x02, 0xbb, 0xcb, 0x03, 0x37, 0xa6, 0xeb, 0x55, 0x51, 0xc0, 0xc2,
+-    0x21, 0x7a, 0x78, 0x44, 0x44, 0x70, 0x06, 0xb0, 0x5d, 0x19, 0xaa, 0xcb,
+-    0xf1, 0x9f, 0xaa, 0xd3, 0x5a, 0x29, 0xc4, 0xc7, 0x7a, 0x36, 0x1d, 0x65,
+-    0x21, 0x52, 0xf9, 0xe2, 0xc7, 0x60, 0xd4, 0x32, 0x03, 0xdf, 0x03, 0xcc,
+-    0xe5, 0x7c, 0xf9, 0x15, 0xe3, 0xe6, 0x46, 0xeb, 0xa8, 0xa8, 0x6f, 0xe7,
+-    0x46, 0x03, 0xc7, 0x5c, 0x29, 0xf6, 0xac, 0x61, 0x2d, 0xbe, 0xa0, 0xda,
+-    0xdc, 0xca, 0x29, 0x35, 0x3b, 0xa0, 0x43, 0x22, 0x22, 0x61, 0x65, 0x8f,
+-    0x2d, 0x13, 0xce, 0x61, 0x7c, 0x27, 0x45, 0x9d, 0x9b, 0x8d, 0xd6, 0xc1,
+-    0xb5, 0x8c, 0x5b, 0xdb, 0xbb, 0xf6, 0x7e, 0x9a, 0xd4, 0x5c, 0x6b, 0x7e,
+-    0xf3, 0x6d, 0x7e, 0x45, 0x2e, 0x55, 0x7d, 0x9f, 0x62, 0xc7, 0xf4, 0x03,
+-    0x6f, 0xb9, 0x02, 0xcf, 0x3d, 0x07, 0xc5, 0xc8, 0xce, 0x9e, 0xac, 0x56,
+-    0x43, 0x8b, 0xcc, 0xf0, 0x2d, 0xc5, 0x56, 0xfa, 0x61, 0xf9, 0xee, 0x1b,
+-    0x89, 0xa9, 0xd6, 0xe8, 0x1e, 0xa2, 0xdf, 0xfd, 0x0d, 0x33, 0x03, 0x91,
+-    0xd9, 0x30, 0x4d, 0xfb, 0x2d, 0x7e, 0x5b, 0xb0, 0xb5, 0x55, 0x1e, 0x9c,
+-    0x13, 0x96, 0x5a, 0xa6, 0xab, 0x88, 0x79, 0xe7, 0x42, 0x31, 0xb2, 0x2d,
+-    0xf8, 0x40, 0x89, 0xe4, 0x96, 0x4c, 0x42, 0xc9, 0x72, 0xd1, 0x8f, 0x3f,
+-    0x2d, 0xee, 0x1d, 0x91, 0xe0, 0xfb, 0x1f, 0xb5, 0x94, 0x41, 0xce, 0x89,
+-    0xed, 0xe7, 0xec, 0xa0, 0xb6, 0xb2, 0xa2, 0x5c, 0x72, 0xa1, 0x91, 0x40,
+-    0x82, 0xde, 0x62, 0xba, 0x12, 0x12, 0xa1, 0xab, 0x31, 0x62, 0x38, 0x48,
+-    0x4c, 0x49, 0x9e, 0x6c, 0xf3, 0xf1, 0x69, 0x3e, 0x8b, 0x6a, 0x24, 0x45,
+-    0x99, 0x5c, 0x5a, 0xe3, 0x52, 0x24, 0xb7, 0xcf, 0xf0, 0xc8, 0x82, 0x5e,
+-    0x9e, 0x10, 0x29, 0xcf, 0xda, 0x01, 0xd0, 0xc0, 0x81, 0xfd, 0x56, 0x15,
+-    0x1c, 0x6b, 0xff, 0x78, 0x91, 0xaa, 0x47, 0x63, 0xb0, 0xe2, 0xbd, 0x67,
+-    0x0d, 0x24, 0xc5, 0xfd, 0x1a, 0x6a, 0x6a, 0x71, 0x9b, 0xca, 0xc4, 0xb3,
+-    0xc0, 0x07, 0x3d, 0xd7, 0x3b, 0xf4, 0xc0, 0xb7, 0xb5, 0xc4, 0x46, 0x85,
+-    0x3d, 0x22, 0x03, 0x1b, 0xcf, 0xe6, 0xce, 0x2f, 0xae, 0x41, 0xcf, 0x67,
+-    0x6b, 0xd3, 0x87, 0x3f, 0xca, 0x4c, 0xb7, 0x9f, 0x47, 0x36, 0xa5, 0xd7,
+-    0xd3, 0x70, 0xf7, 0xc4, 0x9f, 0x7d, 0xbd, 0xe4, 0xc6, 0xec, 0x7b, 0x03,
+-    0xca, 0xb0, 0x78, 0x06, 0xa3, 0xf1, 0xd0, 0x98, 0xdf, 0x1c, 0x60, 0x90,
+-    0x61, 0xcb, 0x7b, 0x68, 0xd2, 0x8e, 0x24, 0x76, 0x7b, 0xf6, 0x2f, 0xf3,
+-    0x7b, 0x96, 0x2d, 0x80, 0x6f, 0xae, 0xc5, 0x2b, 0xe9, 0xad, 0x78, 0x25,
+-    0x78, 0x4e, 0xd7, 0x81, 0xb7, 0x60, 0x20, 0x0c, 0x20, 0x46, 0xb4, 0x88,
+-    0xfe, 0x12, 0x0a, 0x8d, 0x7a, 0x9a, 0x0b, 0xdd, 0x6d, 0x37, 0xb3, 0xa5,
+-    0x99, 0x1d, 0xf2, 0xd4, 0xa6, 0x79, 0x1e, 0x89, 0x1a, 0xda, 0xe8, 0x83,
+-    0x24, 0xc9, 0xd9, 0x1f, 0x76, 0x82, 0xec, 0x64, 0x35, 0x6b, 0x9b, 0xfd,
+-    0x91, 0x31, 0x96, 0xf2, 0x8b, 0x4f, 0x30, 0xbb, 0xd9, 0xcd, 0xe0, 0x66,
+-    0x73, 0xfd, 0xd7, 0x05, 0x16, 0x7c, 0xed, 0x94, 0xc0, 0xa0, 0x73, 0x9e,
+-    0xe7, 0x85, 0xac, 0x0e, 0x20, 0xd1, 0x5e, 0x66, 0x7a, 0xef, 0x93, 0x20,
+-    0xd7, 0x3f, 0xb5, 0xbd, 0xb7, 0xb7, 0xcb, 0x64, 0xc8, 0xde, 0x2f, 0xd9,
+-    0x92, 0x5f, 0xa1, 0xb6, 0xbd, 0xd0, 0xe6, 0xb4, 0x55, 0xf4, 0xa1, 0xa8,
+-    0x51, 0x5e, 0x00, 0x6f, 0xaa, 0x09, 0xff, 0x56, 0xb4, 0xbc, 0xdf, 0xc1,
+-    0x20, 0x13, 0xc4, 0x3c, 0x48, 0xb1, 0x6d, 0xeb, 0x19, 0xb8, 0xbf, 0x4f,
+-    0x3d, 0x35, 0x96, 0x14, 0xc3, 0xc3, 0xef, 0x8e, 0x0b, 0x95, 0xbc, 0x78,
+-    0x47, 0x6a, 0x6c, 0x24, 0x10, 0xbd, 0x06, 0x13, 0x5c, 0x69, 0x7b, 0xb5,
+-    0x53, 0x43, 0xd1, 0x7a, 0x1d, 0x9a, 0x7f, 0x57, 0xcd, 0x81, 0xc5, 0x3f,
+-    0xde, 0x98, 0xb5, 0x73, 0x95, 0xd2, 0x10, 0xcf, 0x4f, 0x6a, 0xce, 0xac,
+-    0x35, 0x49, 0x4d, 0xf3, 0xbe, 0xbf, 0x38, 0xf2, 0xcf, 0x1b, 0x1c, 0x19,
+-    0x27, 0xa3, 0x3f, 0xd9, 0x35, 0xfe, 0xc2, 0xe5, 0x49, 0x16, 0x28, 0xd0,
+-    0x8e, 0xb9, 0x34, 0x6e, 0x8b, 0xa5, 0xe2, 0x9c, 0xbe, 0xad, 0xa1, 0x43,
+-    0x61, 0x2e, 0x48, 0x65, 0xb3, 0x20, 0xe7, 0x1d, 0x65, 0x00, 0x9d, 0x6e,
+-    0x71, 0xe7, 0x79, 0x44, 0xac, 0x0c, 0x38, 0x5a, 0x1d, 0x40, 0x06, 0x30,
+-    0xd0, 0xe8, 0xbe, 0x95, 0x16, 0xaf, 0xd8, 0x5f, 0x67, 0xd3, 0xb0, 0x6a,
+-    0xa3, 0x7c, 0xc1, 0x9b, 0x3f, 0xc7, 0xae, 0x27, 0xb1, 0xc1, 0xb5, 0xce,
+-    0xdf, 0xbb, 0xa4, 0x4f, 0xb4, 0x58, 0xa1, 0xb9, 0x7c, 0x9c, 0x5f, 0x26,
+-    0x4f, 0x13, 0xfa, 0x7c, 0x1a, 0xb7, 0x1b, 0x69, 0xd6, 0x0e, 0x1b, 0x92,
+-    0x31, 0x4b, 0xb4, 0x71, 0x12, 0xc8, 0xc4, 0xbd, 0x99, 0xe3, 0xc8, 0x9d,
+-    0x68, 0xb3, 0x38, 0x35, 0x3f, 0x16, 0xd8, 0xde, 0x01, 0x71, 0xf6, 0x66,
+-    0x77, 0xcb, 0xbd, 0xe2, 0x97, 0x10, 0x91, 0x41, 0x00, 0xa1, 0x0d, 0x9d,
+-    0x40, 0x0b, 0xfc, 0x25, 0xc8, 0x44, 0xc3, 0x78, 0xaa, 0x89, 0xd5, 0x59,
+-    0xe4, 0xa2, 0x9e, 0xd0, 0x85, 0xa2, 0xdd, 0x80, 0x3b, 0x35, 0x5a, 0x50,
+-    0x86, 0xcd, 0x72, 0xf4, 0x9d, 0x69, 0x0e, 0x2d, 0x97, 0x42, 0x09, 0x5e,
+-    0xa6, 0x86, 0xf7, 0x35, 0xcf, 0x9b, 0x42, 0xa7, 0x60, 0xa0, 0x71, 0x41,
+-    0x28, 0x35, 0x22, 0xd6, 0x55, 0xe1, 0xdb, 0xb3, 0x8e, 0x0d, 0x47, 0xb7,
+-    0xd6, 0x02, 0x0f, 0xb1, 0xdf, 0xb8, 0xfb, 0xd8, 0x20, 0xcf, 0x6a, 0x47,
+-    0x3f, 0x8a, 0x91, 0x08, 0x64, 0x08, 0xba, 0x19, 0x10, 0x1f, 0xcf, 0xe5,
+-    0x34, 0xf1, 0x32, 0x49, 0x3b, 0xaf, 0x18, 0x67, 0x96, 0x47, 0x7f, 0x21,
+-    0x8a, 0x37, 0x15, 0x5c, 0xc0, 0xe8, 0x7b, 0xd6, 0x08, 0x5b, 0x45, 0x10,
+-    0x1f, 0x1c, 0x7f, 0xce, 0x3b, 0x88, 0xe5, 0x0e, 0xd9, 0x00, 0xce, 0xe5,
+-    0x9b, 0x4b, 0x25, 0xc7, 0x11, 0x8a, 0x4f, 0x22, 0xa7, 0x31, 0x25, 0x30,
+-    0x23, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x15,
+-    0x31, 0x16, 0x04, 0x14, 0xad, 0x7f, 0xeb, 0xe6, 0xb2, 0x6c, 0xf4, 0xdc,
+-    0x9f, 0x4d, 0x52, 0x40, 0x07, 0x15, 0xd9, 0xe8, 0xbc, 0x0d, 0x4e, 0xd7,
+-    0x30, 0x31, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02,
+-    0x1a, 0x05, 0x00, 0x04, 0x14, 0xa4, 0xac, 0xdb, 0xa8, 0x4c, 0xe9, 0x7a,
+-    0x02, 0x9d, 0x07, 0x39, 0x21, 0xf0, 0x71, 0xae, 0x46, 0x5a, 0xd8, 0x13,
+-    0x51, 0x04, 0x08, 0xa1, 0x52, 0xdd, 0x64, 0x46, 0xe9, 0x9e, 0x3e, 0x02,
+-    0x02, 0x08, 0x00};
+-
+-class PK12ImportTest : public ::testing::Test {};
+-
+-TEST_F(PK12ImportTest, ImportPK12With2P7) {
+-  SECItem password = {siBuffer, nullptr, 0};
+-  ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
+-  ScopedSEC_PKCS12DecoderContext dcx(
+-      SEC_PKCS12DecoderStart(&password, slot.get(), nullptr, nullptr, nullptr,
+-                             nullptr, nullptr, nullptr));
+-  ASSERT_TRUE(dcx);
+-  SECStatus rv = SEC_PKCS12DecoderUpdate(
+-      dcx.get(), const_cast<uint8_t *>(cert_p12), sizeof(cert_p12));
+-  ASSERT_EQ(SECSuccess, rv);
+-  rv = SEC_PKCS12DecoderVerify(dcx.get());
+-  // NSS can't properly decode this P12. But it shouldn't crash.
+-  ASSERT_EQ(SECFailure, rv);
+-}
+-
+-}  // namespace nss_test
+diff --git a/security/nss/gtests/freebl_gtest/blake2b_unittest.cc b/security/nss/gtests/freebl_gtest/blake2b_unittest.cc
+--- a/security/nss/gtests/freebl_gtest/blake2b_unittest.cc
++++ b/security/nss/gtests/freebl_gtest/blake2b_unittest.cc
+@@ -45,17 +45,17 @@ TEST_P(Blake2BKATUnkeyed, Unkeyed) {
+       BLAKE2B_HashBuf(values.data(), kat_data.data(), std::get<0>(GetParam()));
+   ASSERT_EQ(SECSuccess, rv);
+   EXPECT_EQ(values, std::get<1>(GetParam()));
+ }
+ 
+ TEST_P(Blake2BKATKeyed, Keyed) {
+   std::vector<uint8_t> values(BLAKE2B512_LENGTH);
+   SECStatus rv = BLAKE2B_MAC_HashBuf(values.data(), kat_data.data(),
+-                                     std::get<0>(GetParam()), key.data(),
++                                     std::get<0>(GetParam()), kat_key.data(),
+                                      BLAKE2B_KEY_SIZE);
+   ASSERT_EQ(SECSuccess, rv);
+   EXPECT_EQ(values, std::get<1>(GetParam()));
+ }
+ 
+ INSTANTIATE_TEST_CASE_P(UnkeyedKAT, Blake2BKATUnkeyed,
+                         ::testing::ValuesIn(TestcasesUnkeyed));
+ INSTANTIATE_TEST_CASE_P(KeyedKAT, Blake2BKATKeyed,
+@@ -134,17 +134,17 @@ TEST_F(Blake2BTests, CloneTest) {
+ 
+ TEST_F(Blake2BTests, NullTest) {
+   std::vector<uint8_t> digest(BLAKE2B512_LENGTH);
+   SECStatus rv = BLAKE2B_HashBuf(digest.data(), nullptr, 0);
+   ASSERT_EQ(SECSuccess, rv);
+   EXPECT_EQ(std::get<1>(TestcasesUnkeyed[0]), digest);
+ 
+   digest = std::vector<uint8_t>(BLAKE2B512_LENGTH);
+-  rv = BLAKE2B_MAC_HashBuf(digest.data(), nullptr, 0, key.data(),
++  rv = BLAKE2B_MAC_HashBuf(digest.data(), nullptr, 0, kat_key.data(),
+                            BLAKE2B_KEY_SIZE);
+   ASSERT_EQ(SECSuccess, rv);
+   EXPECT_EQ(std::get<1>(TestcasesKeyed[0]), digest);
+ }
+ 
+ TEST_F(Blake2BTests, HashTest) {
+   ScopedBLAKE2BContext ctx(BLAKE2B_NewContext());
+   ASSERT_TRUE(ctx) << "BLAKE2B_NewContext failed!";
+diff --git a/security/nss/gtests/freebl_gtest/kat/blake2b_kat.h b/security/nss/gtests/freebl_gtest/kat/blake2b_kat.h
+--- a/security/nss/gtests/freebl_gtest/kat/blake2b_kat.h
++++ b/security/nss/gtests/freebl_gtest/kat/blake2b_kat.h
+@@ -2,17 +2,17 @@
+  * 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/. */
+ 
+ /* https://github.com/BLAKE2/BLAKE2/blob/master/testvectors/blake2b-kat.txt */
+ 
+ #include <vector>
+ #include <stdint.h>
+ 
+-const std::vector<uint8_t> key = {
++const std::vector<uint8_t> kat_key = {
+     0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15,
+     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
+     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63};
+ 
+ const std::vector<uint8_t> kat_data = {
+     0,   1,   2,   3,   4,   5,   6,   7,   8,   9,   10,  11,  12,  13,  14,
+     15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25,  26,  27,  28,  29,
+diff --git a/security/nss/gtests/freebl_gtest/mpi_unittest.cc b/security/nss/gtests/freebl_gtest/mpi_unittest.cc
+--- a/security/nss/gtests/freebl_gtest/mpi_unittest.cc
++++ b/security/nss/gtests/freebl_gtest/mpi_unittest.cc
+@@ -10,17 +10,17 @@
+ #ifdef __MACH__
+ #include <mach/clock.h>
+ #include <mach/mach.h>
+ #endif
+ 
+ #include "mpi.h"
+ namespace nss_test {
+ 
+-void gettime(struct timespec* tp) {
++void gettime(struct timespec *tp) {
+ #ifdef __MACH__
+   clock_serv_t cclock;
+   mach_timespec_t mts;
+ 
+   host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
+   clock_get_time(cclock, &mts);
+   mach_port_deallocate(mach_task_self(), cclock);
+ 
+@@ -64,49 +64,16 @@ class MPITest : public ::testing::Test {
+     mp_read_radix(&c, result.c_str(), 16);
+     EXPECT_EQ(MP_OKAY, mp_div(&a, &b, &a, &b));
+     EXPECT_EQ(0, mp_cmp(&a, &c));
+ 
+     mp_clear(&a);
+     mp_clear(&b);
+     mp_clear(&c);
+   }
+-
+-  void dump(const std::string& prefix, const uint8_t* buf, size_t len) {
+-    auto flags = std::cerr.flags();
+-    std::cerr << prefix << ": [" << std::dec << len << "] ";
+-    for (size_t i = 0; i < len; ++i) {
+-      std::cerr << std::hex << std::setw(2) << std::setfill('0')
+-                << static_cast<int>(buf[i]);
+-    }
+-    std::cerr << std::endl << std::resetiosflags(flags);
+-  }
+-
+-  void TestToFixedOctets(const std::vector<uint8_t>& ref, size_t len) {
+-    mp_int a;
+-    ASSERT_EQ(MP_OKAY, mp_init(&a));
+-    ASSERT_EQ(MP_OKAY, mp_read_unsigned_octets(&a, ref.data(), ref.size()));
+-    uint8_t buf[len];
+-    ASSERT_EQ(MP_OKAY, mp_to_fixlen_octets(&a, buf, len));
+-    size_t compare;
+-    if (len > ref.size()) {
+-      for (size_t i = 0; i < len - ref.size(); ++i) {
+-        ASSERT_EQ(0U, buf[i]) << "index " << i << " should be zero";
+-      }
+-      compare = ref.size();
+-    } else {
+-      compare = len;
+-    }
+-    dump("value", ref.data(), ref.size());
+-    dump("output", buf, len);
+-    ASSERT_EQ(0, memcmp(buf + len - compare, ref.data() + ref.size() - compare,
+-                        compare))
+-        << "comparing " << compare << " octets";
+-    mp_clear(&a);
+-  }
+ };
+ 
+ TEST_F(MPITest, MpiCmp01Test) { TestCmp("0", "1", -1); }
+ TEST_F(MPITest, MpiCmp10Test) { TestCmp("1", "0", 1); }
+ TEST_F(MPITest, MpiCmp00Test) { TestCmp("0", "0", 0); }
+ TEST_F(MPITest, MpiCmp11Test) { TestCmp("1", "1", 0); }
+ TEST_F(MPITest, MpiDiv32ErrorTest) {
+   TestDiv("FFFF00FFFFFFFF000000000000", "FFFF00FFFFFFFFFF", "FFFFFFFFFF");
+@@ -141,82 +108,41 @@ TEST_F(MPITest, MpiCmpUnalignedTest) {
+   ASSERT_TRUE(strncmp(c_tmp, "feffffffffffffff100000000000000", 31));
+ 
+   mp_clear(&a);
+   mp_clear(&b);
+   mp_clear(&c);
+ }
+ #endif
+ 
+-TEST_F(MPITest, MpiFixlenOctetsZero) {
+-  std::vector<uint8_t> zero = {0};
+-  TestToFixedOctets(zero, 1);
+-  TestToFixedOctets(zero, 2);
+-  TestToFixedOctets(zero, sizeof(mp_digit));
+-  TestToFixedOctets(zero, sizeof(mp_digit) + 1);
+-}
+-
+-TEST_F(MPITest, MpiFixlenOctetsVarlen) {
+-  std::vector<uint8_t> packed;
+-  for (size_t i = 0; i < sizeof(mp_digit) * 2; ++i) {
+-    packed.push_back(0xa4);  // Any non-zero value will do.
+-    TestToFixedOctets(packed, packed.size());
+-    TestToFixedOctets(packed, packed.size() + 1);
+-    TestToFixedOctets(packed, packed.size() + sizeof(mp_digit));
+-  }
+-}
+-
+-TEST_F(MPITest, MpiFixlenOctetsTooSmall) {
+-  uint8_t buf[sizeof(mp_digit) * 3];
+-  std::vector<uint8_t> ref;
+-  for (size_t i = 0; i < sizeof(mp_digit) * 2; i++) {
+-    ref.push_back(3);  // Any non-zero value will do.
+-    dump("ref", ref.data(), ref.size());
+-
+-    mp_int a;
+-    ASSERT_EQ(MP_OKAY, mp_init(&a));
+-    ASSERT_EQ(MP_OKAY, mp_read_unsigned_octets(&a, ref.data(), ref.size()));
+-#ifdef DEBUG
+-    // ARGCHK maps to assert() in a debug build.
+-    EXPECT_DEATH(mp_to_fixlen_octets(&a, buf, ref.size() - 1), "");
+-#else
+-    EXPECT_EQ(MP_BADARG, mp_to_fixlen_octets(&a, buf, ref.size() - 1));
+-#endif
+-    ASSERT_EQ(MP_OKAY, mp_to_fixlen_octets(&a, buf, ref.size()));
+-    ASSERT_EQ(0, memcmp(buf, ref.data(), ref.size()));
+-
+-    mp_clear(&a);
+-  }
+-}
+-
+ // This test is slow. Disable it by default so we can run these tests on CI.
+ class DISABLED_MPITest : public ::testing::Test {};
+ 
+ TEST_F(DISABLED_MPITest, MpiCmpConstTest) {
+   mp_int a, b, c;
+   MP_DIGITS(&a) = 0;
+   MP_DIGITS(&b) = 0;
+   MP_DIGITS(&c) = 0;
+   ASSERT_EQ(MP_OKAY, mp_init(&a));
+   ASSERT_EQ(MP_OKAY, mp_init(&b));
+   ASSERT_EQ(MP_OKAY, mp_init(&c));
+ 
+   mp_read_radix(
+       &a,
+-      const_cast<char*>(
++      const_cast<char *>(
+           "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"),
+       16);
+   mp_read_radix(
+       &b,
+-      const_cast<char*>(
++      const_cast<char *>(
+           "FF0FFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"),
+       16);
+   mp_read_radix(
+       &c,
+-      const_cast<char*>(
++      const_cast<char *>(
+           "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632550"),
+       16);
+ 
+ #ifdef CT_VERIF
+   mp_taint(&b);
+   mp_taint(&c);
+ #endif
+ 
+diff --git a/security/nss/gtests/freebl_gtest/rsa_unittest.cc b/security/nss/gtests/freebl_gtest/rsa_unittest.cc
+--- a/security/nss/gtests/freebl_gtest/rsa_unittest.cc
++++ b/security/nss/gtests/freebl_gtest/rsa_unittest.cc
+@@ -16,82 +16,46 @@ struct ScopedDelete {
+       PORT_FreeArena(ptr->arena, PR_TRUE);
+     }
+   }
+ };
+ 
+ typedef std::unique_ptr<RSAPrivateKey, ScopedDelete<RSAPrivateKey>>
+     ScopedRSAPrivateKey;
+ 
+-class RSATest : public ::testing::Test {
++class RSANewKeyTest : public ::testing::Test {
+  protected:
+   RSAPrivateKey* CreateKeyWithExponent(int keySizeInBits,
+                                        unsigned char publicExponent) {
+     SECItem exp = {siBuffer, 0, 0};
+     unsigned char pubExp[1] = {publicExponent};
+     exp.data = pubExp;
+     exp.len = 1;
+ 
+     return RSA_NewKey(keySizeInBits, &exp);
+   }
+ };
+ 
+-TEST_F(RSATest, expOneTest) {
++TEST_F(RSANewKeyTest, expOneTest) {
+   ScopedRSAPrivateKey key(CreateKeyWithExponent(2048, 0x01));
+   ASSERT_TRUE(key == nullptr);
+ }
+-TEST_F(RSATest, expTwoTest) {
++TEST_F(RSANewKeyTest, expTwoTest) {
+   ScopedRSAPrivateKey key(CreateKeyWithExponent(2048, 0x02));
+   ASSERT_TRUE(key == nullptr);
+ }
+-TEST_F(RSATest, expFourTest) {
++TEST_F(RSANewKeyTest, expFourTest) {
+   ScopedRSAPrivateKey key(CreateKeyWithExponent(2048, 0x04));
+   ASSERT_TRUE(key == nullptr);
+ }
+-TEST_F(RSATest, WrongKeysizeTest) {
++TEST_F(RSANewKeyTest, WrongKeysizeTest) {
+   ScopedRSAPrivateKey key(CreateKeyWithExponent(2047, 0x03));
+   ASSERT_TRUE(key == nullptr);
+ }
+ 
+-TEST_F(RSATest, expThreeTest) {
++TEST_F(RSANewKeyTest, expThreeTest) {
+   ScopedRSAPrivateKey key(CreateKeyWithExponent(2048, 0x03));
+ #ifdef NSS_FIPS_DISABLED
+   ASSERT_TRUE(key != nullptr);
+ #else
+   ASSERT_TRUE(key == nullptr);
+ #endif
+ }
+-
+-TEST_F(RSATest, DecryptBlockTestErrors) {
+-  unsigned char pubExp[3] = {0x01, 0x00, 0x01};
+-  SECItem exp = {siBuffer, pubExp, 3};
+-  ScopedRSAPrivateKey key(RSA_NewKey(2048, &exp));
+-  ASSERT_TRUE(key);
+-  uint8_t out[10] = {0};
+-  uint8_t in_small[100] = {0};
+-  unsigned int outputLen = 0;
+-  unsigned int maxOutputLen = sizeof(out);
+-
+-  // This should fail because input the same size as the modulus (256).
+-  SECStatus rv = RSA_DecryptBlock(key.get(), out, &outputLen, maxOutputLen,
+-                                  in_small, sizeof(in_small));
+-  EXPECT_EQ(SECFailure, rv);
+-
+-  uint8_t in[256] = {0};
+-  // This should fail because the padding checks will fail.
+-  rv = RSA_DecryptBlock(key.get(), out, &outputLen, maxOutputLen, in,
+-                        sizeof(in));
+-  EXPECT_EQ(SECFailure, rv);
+-  // outputLen should be maxOutputLen.
+-  EXPECT_EQ(maxOutputLen, outputLen);
+-
+-  // This should fail because the padding checks will fail.
+-  uint8_t out_long[260] = {0};
+-  maxOutputLen = sizeof(out_long);
+-  rv = RSA_DecryptBlock(key.get(), out_long, &outputLen, maxOutputLen, in,
+-                        sizeof(in));
+-  EXPECT_EQ(SECFailure, rv);
+-  // outputLen should <= 256-11=245.
+-  EXPECT_LE(outputLen, 245u);
+-  // Everything over 256 must be 0 in the output.
+-  uint8_t out_long_test[4] = {0};
+-  EXPECT_EQ(0, memcmp(out_long_test, &out_long[256], 4));
+-}
+diff --git a/security/nss/gtests/nss_bogo_shim/config.cc b/security/nss/gtests/nss_bogo_shim/config.cc
+--- a/security/nss/gtests/nss_bogo_shim/config.cc
++++ b/security/nss/gtests/nss_bogo_shim/config.cc
+@@ -4,36 +4,47 @@
+  * 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/. */
+ #include "config.h"
+ 
+ #include <cstdlib>
+ #include <queue>
+ #include <string>
+ 
+-bool ConfigEntryBase::ParseInternal(std::queue<const char *> *args,
+-                                    std::string *out) {
+-  if (args->empty()) return false;
+-  *out = args->front();
+-  args->pop();
+-  return true;
+-}
+-
+-bool ConfigEntryBase::ParseInternal(std::queue<const char *> *args, int *out) {
+-  if (args->empty()) return false;
++bool ConfigEntryBase::ParseInternal(std::queue<const char *> &args,
++                                    std::vector<int> &out) {
++  if (args.empty()) return false;
+ 
+   char *endptr;
+-  *out = strtol(args->front(), &endptr, 10);
+-  args->pop();
++  out.push_back(strtol(args.front(), &endptr, 10));
++  args.pop();
+ 
+   return !*endptr;
+ }
+ 
+-bool ConfigEntryBase::ParseInternal(std::queue<const char *> *args, bool *out) {
+-  *out = true;
++bool ConfigEntryBase::ParseInternal(std::queue<const char *> &args,
++                                    std::string &out) {
++  if (args.empty()) return false;
++  out = args.front();
++  args.pop();
++  return true;
++}
++
++bool ConfigEntryBase::ParseInternal(std::queue<const char *> &args, int &out) {
++  if (args.empty()) return false;
++
++  char *endptr;
++  out = strtol(args.front(), &endptr, 10);
++  args.pop();
++
++  return !*endptr;
++}
++
++bool ConfigEntryBase::ParseInternal(std::queue<const char *> &args, bool &out) {
++  out = true;
+   return true;
+ }
+ 
+ std::string Config::XformFlag(const std::string &arg) {
+   if (arg.empty()) return "";
+ 
+   if (arg[0] != '-') return "";
+ 
+@@ -46,13 +57,13 @@ Config::Status Config::ParseArgs(int arg
+     args.push(argv[i]);
+   }
+   while (!args.empty()) {
+     auto e = entries_.find(XformFlag(args.front()));
+     args.pop();
+     if (e == entries_.end()) {
+       return kUnknownFlag;
+     }
+-    if (!e->second->Parse(&args)) return kMalformedArgument;
++    if (!e->second->Parse(args)) return kMalformedArgument;
+   }
+ 
+   return kOK;
+ }
+diff --git a/security/nss/gtests/nss_bogo_shim/config.h b/security/nss/gtests/nss_bogo_shim/config.h
+--- a/security/nss/gtests/nss_bogo_shim/config.h
++++ b/security/nss/gtests/nss_bogo_shim/config.h
+@@ -18,43 +18,44 @@
+ #include <memory>
+ #include <queue>
+ #include <string>
+ #include <typeinfo>
+ 
+ // Abstract base class for a given config flag.
+ class ConfigEntryBase {
+  public:
+-  ConfigEntryBase(const std::string& name, const std::string& type)
+-      : name_(name), type_(type) {}
++  ConfigEntryBase(const std::string& nm, const std::string& typ)
++      : name_(nm), type_(typ) {}
+ 
+   virtual ~ConfigEntryBase() {}
+ 
+   const std::string& type() const { return type_; }
+-  virtual bool Parse(std::queue<const char*>* args) = 0;
++  virtual bool Parse(std::queue<const char*>& args) = 0;
+ 
+  protected:
+-  bool ParseInternal(std::queue<const char*>* args, std::string* out);
+-  bool ParseInternal(std::queue<const char*>* args, int* out);
+-  bool ParseInternal(std::queue<const char*>* args, bool* out);
++  bool ParseInternal(std::queue<const char*>& args, std::vector<int>& out);
++  bool ParseInternal(std::queue<const char*>& args, std::string& out);
++  bool ParseInternal(std::queue<const char*>& args, int& out);
++  bool ParseInternal(std::queue<const char*>& args, bool& out);
+ 
+   const std::string name_;
+   const std::string type_;
+ };
+ 
+ // Template specializations for the concrete flag types.
+ template <typename T>
+ class ConfigEntry : public ConfigEntryBase {
+  public:
+   ConfigEntry(const std::string& name, T init)
+       : ConfigEntryBase(name, typeid(T).name()), value_(init) {}
+   T get() const { return value_; }
+ 
+-  bool Parse(std::queue<const char*>* args) {
+-    return ParseInternal(args, &value_);
++  bool Parse(std::queue<const char*>& args) {
++    return ParseInternal(args, value_);
+   }
+ 
+  private:
+   T value_;
+ };
+ 
+ // The overall configuration (I.e., the total set of flags).
+ class Config {
+diff --git a/security/nss/gtests/nss_bogo_shim/config.json b/security/nss/gtests/nss_bogo_shim/config.json
+--- a/security/nss/gtests/nss_bogo_shim/config.json
++++ b/security/nss/gtests/nss_bogo_shim/config.json
+@@ -1,74 +1,21 @@
+ {
+     "DisabledTests": {
+         "### These tests break whenever we rev versions, so just leave them here for easy uncommenting":"",
+-        "SendWarningAlerts-Pass":"BoringSSL updated",
+-        "SendBogusAlertType":"BoringSSL updated",
+-        "SendEmptyRecords-Pass":"BoringSSL updated",
+-        "ExtraCompressionMethods-TLS12":"BoringSSL updated",
+-        "SendSNIWarningAlert":"BoringSSL updated",
+-        "NoNullCompression-TLS12":"BoringSSL updated",
+-        "InvalidCompressionMethod":"BoringSSL updated",
+-        "SupportTicketsWithSessionID":"BoringSSL updated",
+-        "NoSharedCipher":"BoringSSL updated",
+-        "ServerHelloBogusCipher":"BoringSSL updated",
+-        "ClientHelloVersionTooHigh":"BoringSSL updated",
+-        "ServerAuth-SignatureType":"BoringSSL updated",
+-        "ECDSACurveMismatch-Verify-TLS12":"BoringSSL updated",
+-        "UnknownExtension-Client":"BoringSSL updated",
+-        "UnofferedExtension-Client":"BoringSSL updated",
+-        "SendClientVersion-RSA":"BoringSSL updated",
+-        "SupportedCurves-ServerHello-TLS12":"BoringSSL updated",
+-        "Basic-Client*Sync":"BoringSSL updated",
+-        "Resume-Client-CipherMismatch":"BoringSSL updated",
+-        "ClientAuth-SignatureType":"BoringSSL updated",
+-        "Agree-Digest-Default":"BoringSSL updated",
+-        "Basic-Server*Sync":"BoringSSL updated",
+-        "ClientAuth-*-Sync":"BoringSSL updated",
+-        "RSA-PSS-Default*":"BoringSSL updated",
+-        "Renegotiate-Server-NoExt*":"BoringSSL updated",
+-        "Downgrade-TLS12*":"BoringSSL updated",
+-        "MaxCBCPadding":"BoringSSL updated",
+-        "UnknownCipher":"BoringSSL updated",
+-        "LargeMessage":"BoringSSL updated",
+-        "NoCommonCurves":"BoringSSL updated",
+-        "UnknownCurve":"BoringSSL updated",
+-        "SessionTicketsDisabled*":"BoringSSL updated",
+-        "BadFinished-*":"BoringSSL updated",
+-        "ServerSkipCertificateVerify":"BoringSSL updated",
+-        "*VersionTolerance":"BoringSSL updated",
+-        "ConflictingVersionNegotiation*":"BoringSSL updated",
+-        "Ed25519DefaultDisable*":"BoringSSL updated",
+-        "*SHA1-Fallback*":"BoringSSL updated",
+-        "ExtendedMasterSecret-NoToNo*":"BoringSSL updated",
+-        "ServerNameExtensionClientMissing*":"BoringSSL updated",
+-        "NoClientCertificate*":"BoringSSL updated",
+-        "ServerCipherFilter*":"BoringSSL updated",
+-        "*FallbackSCSV*":"BoringSSL updated",
+-        "LooseInitialRecordVersion*":"BoringSSL updated",
+-        "ALPNClient*":"BoringSSL updated",
+-        "MinimumVersion*":"BoringSSL updated",
+-        "VersionNegotiation*":"BoringSSL updated",
+-        "*Client-ClientAuth*":"BoringSSL updated",
+-        "*Server-ClientAuth*":"BoringSSL updated",
+-        "NoExtendedMasterSecret*":"BoringSSL updated",
+-        "PointFormat*":"BoringSSL updated",
+-        "*Sync-SplitHandshakeRecords*":"BoringSSL updated",
+-        "*Sync-PackHandshakeFlight*":"BoringSSL updated",
+-        "TicketSessionIDLength*":"BoringSSL updated",
+-        "*LargeRecord*":"BoringSSL updated",
+-        "WrongMessageType-NewSessionTicket":"BoringSSL updated",
+-        "WrongMessageType*Certificate*":"BoringSSL updated",
+-        "WrongMessageType*Client*":"BoringSSL updated",
+-        "WrongMessageType*Server*":"BoringSSL updated",
+-        "WrongMessageType*DTLS":"BoringSSL updated",
+-        "GarbageCertificate*":"BoringSSL updated",
+-        "EmptyExtensions*":"BoringSSL updated",
+-        "*OmitExtensions*":"BoringSSL updated",
++        "ServerBogusVersion":"Check that SH.legacy_version=TLS12 when the server picks TLS 1.3 (Bug 1443761)",
++        "DummyPQPadding-Server*":"Boring is testing a dummy PQ padding extension",
++        "VerifyPreferences-Enforced":"NSS sends alerts in response to errors in protected handshake messages in the clear",
++        "Draft-Downgrade-Server":"Boring implements a draft downgrade sentinel used for measurements.",
++        "FilterExtraAlgorithms":"NSS doesn't allow sending unsupported signature algorithms",
++        "SendBogusAlertType":"Unexpected TLS alerts should abort connections (Bug 1438263)",
++        "VerifyPreferences-Ed25519":"Add Ed25519 support (Bug 1325335)",
++        "Ed25519DefaultDisable*":"Add Ed25519 support (Bug 1325335)",
++        "ServerCipherFilter*":"Add Ed25519 support (Bug 1325335)",
++        "GarbageCertificate*":"Send bad_certificate alert when certificate parsing fails (Bug 1441565)",
+         "SupportedVersionSelection-TLS12":"Should maybe reject TLS 1.2 in SH.supported_versions (Bug 1438266)",
+         "*TLS13*":"(NSS=19, BoGo=18)",
+         "*HelloRetryRequest*":"(NSS=19, BoGo=18)",
+         "*KeyShare*":"(NSS=19, BoGo=18)",
+         "*EncryptedExtensions*":"(NSS=19, BoGo=18)",
+         "*SecondClientHello*":"(NSS=19, BoGo=18)",
+         "*IgnoreClientVersionOrder*":"(NSS=19, BoGo=18)",
+         "SkipEarlyData*":"(NSS=19, BoGo=18)",
+@@ -103,17 +50,16 @@
+         "FragmentedClientVersion":"received a malformed Client Hello handshake message",
+         "UnofferedExtension-Client-TLS13":"nss updated/broken",
+         "UnknownExtension-Client-TLS13":"nss updated/broken",
+         "WrongMessageType-TLS13-EncryptedExtensions":"nss updated/broken",
+         "WrongMessageType-TLS13-CertificateRequest":"nss updated/broken",
+         "WrongMessageType-TLS13-ServerCertificateVerify":"nss updated/broken",
+         "WrongMessageType-TLS13-ServerCertificate":"nss updated/broken",
+         "WrongMessageType-TLS13-ServerFinished":"nss updated/broken",
+-        "EncryptedExtensionsWithKeyShare":"nss updated/broken",
+         "EmptyEncryptedExtensions":"nss updated/broken",
+         "TrailingMessageData-*": "Bug 1304575",
+         "DuplicateKeyShares":"Bug 1304578",
+         "Resume-Server-TLS13-TLS13":"Bug 1314351",
+         "SkipEarlyData-Interleaved":"Bug 1336916",
+         "ECDSAKeyUsage-TLS1*":"Bug 1338194",
+         "PointFormat-Client-MissingUncompressed":"We ignore ec_point_formats extensions sent by servers.",
+         "SkipEarlyData-SecondClientHelloEarlyData":"Boring doesn't reject early_data in the 2nd CH but fails later with bad_record_mac.",
+diff --git a/security/nss/gtests/nss_bogo_shim/nss_bogo_shim.cc b/security/nss/gtests/nss_bogo_shim/nss_bogo_shim.cc
+--- a/security/nss/gtests/nss_bogo_shim/nss_bogo_shim.cc
++++ b/security/nss/gtests/nss_bogo_shim/nss_bogo_shim.cc
+@@ -1,15 +1,16 @@
+ /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+ /* vim: set ts=2 et sw=2 tw=80: */
+ /* This Source Code Form is subject to the terms of the Mozilla Public
+  * 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/. */
+ #include "config.h"
+ 
++#include <algorithm>
+ #include <cstdlib>
+ #include <iostream>
+ #include <memory>
+ #include "nspr.h"
+ #include "nss.h"
+ #include "prio.h"
+ #include "prnetdb.h"
+ #include "secerr.h"
+@@ -85,19 +86,24 @@ class TestAgent {
+ 
+     return true;
+   }
+ 
+   bool ConnectTcp() {
+     PRStatus prv;
+     PRNetAddr addr;
+ 
+-    prv = PR_StringToNetAddr("127.0.0.1", &addr);
++    // Try IPv6 first.
++    prv = PR_StringToNetAddr("::1", &addr);
+     if (prv != PR_SUCCESS) {
+-      return false;
++      // If that fails, try IPv4.
++      prv = PR_StringToNetAddr("127.0.0.1", &addr);
++      if (prv != PR_SUCCESS) {
++        return false;
++      }
+     }
+     addr.inet.port = PR_htons(cfg_.get<int>("port"));
+ 
+     pr_fd_ = PR_OpenTCPSocket(addr.raw.family);
+     if (!pr_fd_) return false;
+ 
+     prv = PR_Connect(pr_fd_, &addr, PR_INTERVAL_NO_TIMEOUT);
+     if (prv != PR_SUCCESS) {
+@@ -251,17 +257,21 @@ class TestAgent {
+ 
+     if (!found_min) {
+       std::cerr << "All versions disabled.\n";
+     }
+     return found_min;
+   }
+ 
+   bool SetupOptions() {
+-    SECStatus rv = SSL_OptionSet(ssl_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
++    SECStatus rv =
++        SSL_OptionSet(ssl_fd_, SSL_ENABLE_TLS13_COMPAT_MODE, PR_TRUE);
++    if (rv != SECSuccess) return false;
++
++    rv = SSL_OptionSet(ssl_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
+     if (rv != SECSuccess) return false;
+ 
+     SSLVersionRange vrange;
+     if (!GetVersionRange(&vrange, ssl_variant_stream)) return false;
+ 
+     rv = SSL_VersionRangeSet(ssl_fd_, &vrange);
+     if (rv != SECSuccess) return false;
+ 
+@@ -282,16 +292,36 @@ class TestAgent {
+       if (rv != SECSuccess) return false;
+ 
+       rv = SSL_SetNextProtoNego(
+           ssl_fd_, reinterpret_cast<const unsigned char*>(alpn.c_str()),
+           alpn.size());
+       if (rv != SECSuccess) return false;
+     }
+ 
++    // Set supported signature schemes.
++    auto sign_prefs = cfg_.get<std::vector<int>>("signing-prefs");
++    auto verify_prefs = cfg_.get<std::vector<int>>("verify-prefs");
++    if (sign_prefs.empty()) {
++      sign_prefs = verify_prefs;
++    } else if (!verify_prefs.empty()) {
++      return false;  // Both shouldn't be set.
++    }
++    if (!sign_prefs.empty()) {
++      std::vector<SSLSignatureScheme> sig_schemes;
++      std::transform(
++          sign_prefs.begin(), sign_prefs.end(), std::back_inserter(sig_schemes),
++          [](int scheme) { return static_cast<SSLSignatureScheme>(scheme); });
++
++      rv = SSL_SignatureSchemePrefSet(
++          ssl_fd_, sig_schemes.data(),
++          static_cast<unsigned int>(sig_schemes.size()));
++      if (rv != SECSuccess) return false;
++    }
++
+     if (cfg_.get<bool>("fallback-scsv")) {
+       rv = SSL_OptionSet(ssl_fd_, SSL_ENABLE_FALLBACK_SCSV, PR_TRUE);
+       if (rv != SECSuccess) return false;
+     }
+ 
+     if (cfg_.get<bool>("false-start")) {
+       rv = SSL_OptionSet(ssl_fd_, SSL_ENABLE_FALSE_START, PR_TRUE);
+       if (rv != SECSuccess) return false;
+@@ -405,17 +435,17 @@ class TestAgent {
+     if (rv != sizeof(block)) {
+       std::cerr << "Write failure\n";
+       PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+       return SECFailure;
+     }
+ 
+     size_t left = sizeof(block);
+     while (left) {
+-      int32_t rv = PR_Read(ssl_fd_, block, left);
++      rv = PR_Read(ssl_fd_, block, left);
+       if (rv < 0) {
+         std::cerr << "Failure reading\n";
+         return SECFailure;
+       }
+       if (rv == 0) {
+         PORT_SetError(SEC_ERROR_INPUT_LEN);
+         return SECFailure;
+       }
+@@ -476,16 +506,34 @@ class TestAgent {
+ 
+       assert(chosen_len <= sizeof(chosen));
+       if (std::string(chosen, chosen_len) != alpn) {
+         std::cerr << "Unexpected ALPN selection" << std::endl;
+         return SECFailure;
+       }
+     }
+ 
++    auto sig_alg = cfg_.get<int>("expect-peer-signature-algorithm");
++    if (sig_alg) {
++      SSLChannelInfo info;
++      rv = SSL_GetChannelInfo(ssl_fd_, &info, sizeof(info));
++      if (rv != SECSuccess) {
++        PRErrorCode err = PR_GetError();
++        std::cerr << "SSL_GetChannelInfo failed with error=" << FormatError(err)
++                  << std::endl;
++        return SECFailure;
++      }
++
++      auto expected = static_cast<SSLSignatureScheme>(sig_alg);
++      if (info.signatureScheme != expected) {
++        std::cerr << "Unexpected signature scheme" << std::endl;
++        return SECFailure;
++      }
++    }
++
+     return SECSuccess;
+   }
+ 
+  private:
+   const Config& cfg_;
+   PRFileDesc* pr_fd_;
+   PRFileDesc* ssl_fd_;
+   CERTCertificate* cert_;
+@@ -508,16 +556,19 @@ std::unique_ptr<const Config> ReadConfig
+   cfg->AddEntry<bool>("fallback-scsv", false);
+   cfg->AddEntry<bool>("false-start", false);
+   cfg->AddEntry<bool>("enable-ocsp-stapling", false);
+   cfg->AddEntry<bool>("write-then-read", false);
+   cfg->AddEntry<bool>("require-any-client-certificate", false);
+   cfg->AddEntry<bool>("verify-peer", false);
+   cfg->AddEntry<std::string>("advertise-alpn", "");
+   cfg->AddEntry<std::string>("expect-alpn", "");
++  cfg->AddEntry<std::vector<int>>("signing-prefs", std::vector<int>());
++  cfg->AddEntry<std::vector<int>>("verify-prefs", std::vector<int>());
++  cfg->AddEntry<int>("expect-peer-signature-algorithm", 0);
+ 
+   auto rv = cfg->ParseArgs(argc, argv);
+   switch (rv) {
+     case Config::kOK:
+       break;
+     case Config::kUnknownFlag:
+       exitCodeUnimplemented = true;
+     default:
+diff --git a/security/nss/gtests/pk11_gtest/pk11_curve25519_unittest.cc b/security/nss/gtests/pk11_gtest/pk11_curve25519_unittest.cc
+--- a/security/nss/gtests/pk11_gtest/pk11_curve25519_unittest.cc
++++ b/security/nss/gtests/pk11_gtest/pk11_curve25519_unittest.cc
+@@ -71,19 +71,16 @@ class Pkcs11Curve25519Test : public ::te
+     ScopedSECKEYPrivateKey privKey(key);
+     ASSERT_TRUE(privKey);
+ 
+     SECItem spkiItem = {siBuffer, toUcharPtr(spki),
+                         static_cast<unsigned int>(spki_len)};
+ 
+     ScopedCERTSubjectPublicKeyInfo certSpki(
+         SECKEY_DecodeDERSubjectPublicKeyInfo(&spkiItem));
+-    if (!expect_success && !certSpki) {
+-      return;
+-    }
+     ASSERT_TRUE(certSpki);
+ 
+     ScopedSECKEYPublicKey pubKey(SECKEY_ExtractPublicKey(certSpki.get()));
+     ASSERT_TRUE(pubKey);
+ 
+     ScopedPK11SymKey symKey(PK11_PubDeriveWithKDF(
+         privKey.get(), pubKey.get(), false, nullptr, nullptr, CKM_ECDH1_DERIVE,
+         CKM_SHA512_HMAC, CKA_DERIVE, 0, CKD_NULL, nullptr, nullptr));
+diff --git a/security/nss/gtests/pk11_gtest/pk11_signature_test.h b/security/nss/gtests/pk11_gtest/pk11_signature_test.h
+--- a/security/nss/gtests/pk11_gtest/pk11_signature_test.h
++++ b/security/nss/gtests/pk11_gtest/pk11_signature_test.h
+@@ -20,18 +20,18 @@ struct Pkcs11SignatureTestParams {
+   const DataBuffer pkcs8_;
+   const DataBuffer spki_;
+   const DataBuffer data_;
+   const DataBuffer signature_;
+ };
+ 
+ class Pk11SignatureTest : public ::testing::Test {
+  protected:
+-  Pk11SignatureTest(CK_MECHANISM_TYPE mechanism, SECOidTag hash_oid)
+-      : mechanism_(mechanism), hash_oid_(hash_oid) {}
++  Pk11SignatureTest(CK_MECHANISM_TYPE mech, SECOidTag hash_oid)
++      : mechanism_(mech), hash_oid_(hash_oid) {}
+ 
+   virtual const SECItem* parameters() const { return nullptr; }
+   CK_MECHANISM_TYPE mechanism() const { return mechanism_; }
+ 
+   ScopedSECKEYPrivateKey ImportPrivateKey(const DataBuffer& pkcs8) {
+     ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
+     if (!slot) {
+       ADD_FAILURE() << "No slot";
+diff --git a/security/nss/gtests/ssl_gtest/ssl_auth_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_auth_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_auth_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_auth_unittest.cc
+@@ -150,18 +150,18 @@ TEST_P(TlsConnectTls12, ClientAuthBigRsa
+   Connect();
+   CheckKeys();
+   CheckSigScheme(capture_cert_verify, 0, server_, ssl_sig_rsa_pss_rsae_sha256,
+                  2048);
+ }
+ 
+ class TlsZeroCertificateRequestSigAlgsFilter : public TlsHandshakeFilter {
+  public:
+-  TlsZeroCertificateRequestSigAlgsFilter(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsHandshakeFilter(agent, {kTlsHandshakeCertificateRequest}) {}
++  TlsZeroCertificateRequestSigAlgsFilter(const std::shared_ptr<TlsAgent>& a)
++      : TlsHandshakeFilter(a, {kTlsHandshakeCertificateRequest}) {}
+   virtual PacketFilter::Action FilterHandshake(
+       const TlsHandshakeFilter::HandshakeHeader& header,
+       const DataBuffer& input, DataBuffer* output) {
+     TlsParser parser(input);
+     std::cerr << "Zeroing CertReq.supported_signature_algorithms" << std::endl;
+ 
+     DataBuffer cert_types;
+     if (!parser.ReadVariable(&cert_types, 1)) {
+diff --git a/security/nss/gtests/ssl_gtest/ssl_dhe_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_dhe_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_dhe_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_dhe_unittest.cc
+@@ -98,18 +98,18 @@ TEST_P(TlsConnectGenericPre13, ConnectFf
+     ConnectExpectAlert(server_, kTlsAlertHandshakeFailure);
+     client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP);
+     server_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP);
+   }
+ }
+ 
+ class TlsDheServerKeyExchangeDamager : public TlsHandshakeFilter {
+  public:
+-  TlsDheServerKeyExchangeDamager(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsHandshakeFilter(agent, {kTlsHandshakeServerKeyExchange}) {}
++  TlsDheServerKeyExchangeDamager(const std::shared_ptr<TlsAgent>& a)
++      : TlsHandshakeFilter(a, {kTlsHandshakeServerKeyExchange}) {}
+   virtual PacketFilter::Action FilterHandshake(
+       const TlsHandshakeFilter::HandshakeHeader& header,
+       const DataBuffer& input, DataBuffer* output) {
+     // Damage the first octet of dh_p.  Anything other than the known prime will
+     // be rejected as "weak" when we have SSL_REQUIRE_DH_NAMED_GROUPS enabled.
+     *output = input;
+     output->data()[3] ^= 73;
+     return CHANGE;
+@@ -136,19 +136,19 @@ class TlsDheSkeChangeY : public TlsHands
+     kYZero,
+     kYOne,
+     kYPMinusOne,
+     kYGreaterThanP,
+     kYTooLarge,
+     kYZeroPad
+   };
+ 
+-  TlsDheSkeChangeY(const std::shared_ptr<TlsAgent>& agent,
+-                   uint8_t handshake_type, ChangeYTo change)
+-      : TlsHandshakeFilter(agent, {handshake_type}), change_Y_(change) {}
++  TlsDheSkeChangeY(const std::shared_ptr<TlsAgent>& a, uint8_t handshake_type,
++                   ChangeYTo change)
++      : TlsHandshakeFilter(a, {handshake_type}), change_Y_(change) {}
+ 
+  protected:
+   void ChangeY(const DataBuffer& input, DataBuffer* output, size_t offset,
+                const DataBuffer& prime) {
+     static const uint8_t kExtraZero = 0;
+     static const uint8_t kTooLargeExtra = 1;
+ 
+     uint32_t dh_Ys_len;
+@@ -203,19 +203,19 @@ class TlsDheSkeChangeY : public TlsHands
+   }
+ 
+  private:
+   ChangeYTo change_Y_;
+ };
+ 
+ class TlsDheSkeChangeYServer : public TlsDheSkeChangeY {
+  public:
+-  TlsDheSkeChangeYServer(const std::shared_ptr<TlsAgent>& agent,
+-                         ChangeYTo change, bool modify)
+-      : TlsDheSkeChangeY(agent, kTlsHandshakeServerKeyExchange, change),
++  TlsDheSkeChangeYServer(const std::shared_ptr<TlsAgent>& a, ChangeYTo change,
++                         bool modify)
++      : TlsDheSkeChangeY(a, kTlsHandshakeServerKeyExchange, change),
+         modify_(modify),
+         p_() {}
+ 
+   const DataBuffer& prime() const { return p_; }
+ 
+  protected:
+   virtual PacketFilter::Action FilterHandshake(
+       const TlsHandshakeFilter::HandshakeHeader& header,
+@@ -242,19 +242,19 @@ class TlsDheSkeChangeYServer : public Tl
+  private:
+   bool modify_;
+   DataBuffer p_;
+ };
+ 
+ class TlsDheSkeChangeYClient : public TlsDheSkeChangeY {
+  public:
+   TlsDheSkeChangeYClient(
+-      const std::shared_ptr<TlsAgent>& agent, ChangeYTo change,
++      const std::shared_ptr<TlsAgent>& a, ChangeYTo change,
+       std::shared_ptr<const TlsDheSkeChangeYServer> server_filter)
+-      : TlsDheSkeChangeY(agent, kTlsHandshakeClientKeyExchange, change),
++      : TlsDheSkeChangeY(a, kTlsHandshakeClientKeyExchange, change),
+         server_filter_(server_filter) {}
+ 
+  protected:
+   virtual PacketFilter::Action FilterHandshake(
+       const TlsHandshakeFilter::HandshakeHeader& header,
+       const DataBuffer& input, DataBuffer* output) override {
+     ChangeY(input, output, 0, server_filter_->prime());
+     return CHANGE;
+@@ -352,18 +352,18 @@ INSTANTIATE_TEST_CASE_P(
+                        TlsConnectTestBase::kTlsV10ToV12, kAllY, kTrueFalse));
+ INSTANTIATE_TEST_CASE_P(
+     DamageYDatagram, TlsDamageDHYTest,
+     ::testing::Combine(TlsConnectTestBase::kTlsVariantsDatagram,
+                        TlsConnectTestBase::kTlsV11V12, kAllY, kTrueFalse));
+ 
+ class TlsDheSkeMakePEven : public TlsHandshakeFilter {
+  public:
+-  TlsDheSkeMakePEven(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsHandshakeFilter(agent, {kTlsHandshakeServerKeyExchange}) {}
++  TlsDheSkeMakePEven(const std::shared_ptr<TlsAgent>& a)
++      : TlsHandshakeFilter(a, {kTlsHandshakeServerKeyExchange}) {}
+ 
+   virtual PacketFilter::Action FilterHandshake(
+       const TlsHandshakeFilter::HandshakeHeader& header,
+       const DataBuffer& input, DataBuffer* output) {
+     // Find the end of dh_p
+     uint32_t dh_len = 0;
+     EXPECT_TRUE(input.Read(0, 2, &dh_len));
+     EXPECT_GT(input.len(), 2 + dh_len) << "enough space for dh_p";
+@@ -385,18 +385,18 @@ TEST_P(TlsConnectGenericPre13, MakeDhePE
+   ConnectExpectAlert(client_, kTlsAlertIllegalParameter);
+ 
+   client_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
+   server_->CheckErrorCode(SSL_ERROR_ILLEGAL_PARAMETER_ALERT);
+ }
+ 
+ class TlsDheSkeZeroPadP : public TlsHandshakeFilter {
+  public:
+-  TlsDheSkeZeroPadP(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsHandshakeFilter(agent, {kTlsHandshakeServerKeyExchange}) {}
++  TlsDheSkeZeroPadP(const std::shared_ptr<TlsAgent>& a)
++      : TlsHandshakeFilter(a, {kTlsHandshakeServerKeyExchange}) {}
+ 
+   virtual PacketFilter::Action FilterHandshake(
+       const TlsHandshakeFilter::HandshakeHeader& header,
+       const DataBuffer& input, DataBuffer* output) {
+     *output = input;
+     uint32_t dh_len = 0;
+     EXPECT_TRUE(input.Read(0, 2, &dh_len));
+     static const uint8_t kZeroPad = 0;
+@@ -541,19 +541,19 @@ TEST_P(TlsConnectTls13, ResumeFfdhe) {
+   CheckKeys(ssl_kea_dh, ssl_grp_ffdhe_2048, ssl_auth_rsa_sign,
+             ssl_sig_rsa_pss_rsae_sha256);
+   ASSERT_LT(0UL, clientCapture->extension().len());
+   ASSERT_LT(0UL, serverCapture->extension().len());
+ }
+ 
+ class TlsDheSkeChangeSignature : public TlsHandshakeFilter {
+  public:
+-  TlsDheSkeChangeSignature(const std::shared_ptr<TlsAgent>& agent,
+-                           uint16_t version, const uint8_t* data, size_t len)
+-      : TlsHandshakeFilter(agent, {kTlsHandshakeServerKeyExchange}),
++  TlsDheSkeChangeSignature(const std::shared_ptr<TlsAgent>& a, uint16_t version,
++                           const uint8_t* data, size_t len)
++      : TlsHandshakeFilter(a, {kTlsHandshakeServerKeyExchange}),
+         version_(version),
+         data_(data),
+         len_(len) {}
+ 
+  protected:
+   virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
+                                                const DataBuffer& input,
+                                                DataBuffer* output) {
+diff --git a/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc
+@@ -187,18 +187,18 @@ TEST_P(TlsConnectGenericPre13, P384Prior
+   Connect();
+ 
+   CheckKeys(ssl_kea_ecdh, ssl_grp_ec_secp384r1, ssl_auth_rsa_sign,
+             ssl_sig_rsa_pss_rsae_sha256);
+ }
+ 
+ class TlsKeyExchangeGroupCapture : public TlsHandshakeFilter {
+  public:
+-  TlsKeyExchangeGroupCapture(const std::shared_ptr<TlsAgent> &agent)
+-      : TlsHandshakeFilter(agent, {kTlsHandshakeServerKeyExchange}),
++  TlsKeyExchangeGroupCapture(const std::shared_ptr<TlsAgent> &a)
++      : TlsHandshakeFilter(a, {kTlsHandshakeServerKeyExchange}),
+         group_(ssl_grp_none) {}
+ 
+   SSLNamedGroup group() const { return group_; }
+ 
+  protected:
+   virtual PacketFilter::Action FilterHandshake(const HandshakeHeader &header,
+                                                const DataBuffer &input,
+                                                DataBuffer *output) {
+diff --git a/security/nss/gtests/ssl_gtest/ssl_extension_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_extension_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_extension_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_extension_unittest.cc
+@@ -14,19 +14,19 @@
+ #include "tls_connect.h"
+ #include "tls_filter.h"
+ #include "tls_parser.h"
+ 
+ namespace nss_test {
+ 
+ class TlsExtensionTruncator : public TlsExtensionFilter {
+  public:
+-  TlsExtensionTruncator(const std::shared_ptr<TlsAgent>& agent,
+-                        uint16_t extension, size_t length)
+-      : TlsExtensionFilter(agent), extension_(extension), length_(length) {}
++  TlsExtensionTruncator(const std::shared_ptr<TlsAgent>& a, uint16_t extension,
++                        size_t length)
++      : TlsExtensionFilter(a), extension_(extension), length_(length) {}
+   virtual PacketFilter::Action FilterExtension(uint16_t extension_type,
+                                                const DataBuffer& input,
+                                                DataBuffer* output) {
+     if (extension_type != extension_) {
+       return KEEP;
+     }
+     if (input.len() <= length_) {
+       return KEEP;
+@@ -38,19 +38,19 @@ class TlsExtensionTruncator : public Tls
+ 
+  private:
+   uint16_t extension_;
+   size_t length_;
+ };
+ 
+ class TlsExtensionDamager : public TlsExtensionFilter {
+  public:
+-  TlsExtensionDamager(const std::shared_ptr<TlsAgent>& agent,
+-                      uint16_t extension, size_t index)
+-      : TlsExtensionFilter(agent), extension_(extension), index_(index) {}
++  TlsExtensionDamager(const std::shared_ptr<TlsAgent>& a, uint16_t extension,
++                      size_t index)
++      : TlsExtensionFilter(a), extension_(extension), index_(index) {}
+   virtual PacketFilter::Action FilterExtension(uint16_t extension_type,
+                                                const DataBuffer& input,
+                                                DataBuffer* output) {
+     if (extension_type != extension_) {
+       return KEEP;
+     }
+ 
+     *output = input;
+@@ -60,21 +60,19 @@ class TlsExtensionDamager : public TlsEx
+ 
+  private:
+   uint16_t extension_;
+   size_t index_;
+ };
+ 
+ class TlsExtensionAppender : public TlsHandshakeFilter {
+  public:
+-  TlsExtensionAppender(const std::shared_ptr<TlsAgent>& agent,
++  TlsExtensionAppender(const std::shared_ptr<TlsAgent>& a,
+                        uint8_t handshake_type, uint16_t ext, DataBuffer& data)
+-      : TlsHandshakeFilter(agent, {handshake_type}),
+-        extension_(ext),
+-        data_(data) {}
++      : TlsHandshakeFilter(a, {handshake_type}), extension_(ext), data_(data) {}
+ 
+   virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
+                                                const DataBuffer& input,
+                                                DataBuffer* output) {
+     TlsParser parser(input);
+     if (!TlsExtensionFilter::FindExtensions(&parser, header)) {
+       return KEEP;
+     }
+@@ -623,22 +621,19 @@ struct PskIdentity {
+ 
+ class TlsPreSharedKeyReplacer;
+ 
+ typedef std::function<void(TlsPreSharedKeyReplacer*)>
+     TlsPreSharedKeyReplacerFunc;
+ 
+ class TlsPreSharedKeyReplacer : public TlsExtensionFilter {
+  public:
+-  TlsPreSharedKeyReplacer(const std::shared_ptr<TlsAgent>& agent,
++  TlsPreSharedKeyReplacer(const std::shared_ptr<TlsAgent>& a,
+                           TlsPreSharedKeyReplacerFunc function)
+-      : TlsExtensionFilter(agent),
+-        identities_(),
+-        binders_(),
+-        function_(function) {}
++      : TlsExtensionFilter(a), identities_(), binders_(), function_(function) {}
+ 
+   static size_t CopyAndMaybeReplace(TlsParser* parser, size_t size,
+                                     const std::unique_ptr<DataBuffer>& replace,
+                                     size_t index, DataBuffer* output) {
+     DataBuffer tmp;
+     bool ret = parser->ReadVariable(&tmp, size);
+     EXPECT_EQ(true, ret);
+     if (!ret) return 0;
+diff --git a/security/nss/gtests/ssl_gtest/ssl_fuzz_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_fuzz_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_fuzz_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_fuzz_unittest.cc
+@@ -22,18 +22,18 @@ namespace nss_test {
+ const uint8_t kShortEmptyFinished[8] = {0};
+ const uint8_t kLongEmptyFinished[128] = {0};
+ 
+ class TlsFuzzTest : public ::testing::Test {};
+ 
+ // Record the application data stream.
+ class TlsApplicationDataRecorder : public TlsRecordFilter {
+  public:
+-  TlsApplicationDataRecorder(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsRecordFilter(agent), buffer_() {}
++  TlsApplicationDataRecorder(const std::shared_ptr<TlsAgent>& a)
++      : TlsRecordFilter(a), buffer_() {}
+ 
+   virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+                                             const DataBuffer& input,
+                                             DataBuffer* output) {
+     if (header.content_type() == kTlsApplicationDataType) {
+       buffer_.Append(input);
+     }
+ 
+diff --git a/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc
+@@ -64,18 +64,18 @@ TEST_P(TlsConnectTls13, HelloRetryReques
+   EXPECT_FALSE(capture_early_data->captured());
+ }
+ 
+ // This filter only works for DTLS 1.3 where there is exactly one handshake
+ // packet. If the record is split into two packets, or there are multiple
+ // handshake packets, this will break.
+ class CorrectMessageSeqAfterHrrFilter : public TlsRecordFilter {
+  public:
+-  CorrectMessageSeqAfterHrrFilter(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsRecordFilter(agent) {}
++  CorrectMessageSeqAfterHrrFilter(const std::shared_ptr<TlsAgent>& a)
++      : TlsRecordFilter(a) {}
+ 
+  protected:
+   PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+                                     const DataBuffer& record, size_t* offset,
+                                     DataBuffer* output) {
+     if (filtered_packets() > 0 || header.content_type() != content_handshake) {
+       return KEEP;
+     }
+@@ -146,18 +146,18 @@ TEST_P(TlsConnectTls13, SecondClientHell
+ 
+   ExpectAlert(server_, kTlsAlertUnsupportedExtension);
+   Handshake();
+   client_->CheckErrorCode(SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT);
+ }
+ 
+ class KeyShareReplayer : public TlsExtensionFilter {
+  public:
+-  KeyShareReplayer(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsExtensionFilter(agent) {}
++  KeyShareReplayer(const std::shared_ptr<TlsAgent>& a)
++      : TlsExtensionFilter(a) {}
+ 
+   virtual PacketFilter::Action FilterExtension(uint16_t extension_type,
+                                                const DataBuffer& input,
+                                                DataBuffer* output) {
+     if (extension_type != ssl_tls13_key_share_xtn) {
+       return KEEP;
+     }
+ 
+diff --git a/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc
+@@ -51,18 +51,18 @@ TEST_P(TlsConnectGeneric, CipherSuiteMis
+   }
+   ConnectExpectAlert(server_, kTlsAlertHandshakeFailure);
+   client_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP);
+   server_->CheckErrorCode(SSL_ERROR_NO_CYPHER_OVERLAP);
+ }
+ 
+ class TlsAlertRecorder : public TlsRecordFilter {
+  public:
+-  TlsAlertRecorder(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsRecordFilter(agent), level_(255), description_(255) {}
++  TlsAlertRecorder(const std::shared_ptr<TlsAgent>& a)
++      : TlsRecordFilter(a), level_(255), description_(255) {}
+ 
+   PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+                                     const DataBuffer& input,
+                                     DataBuffer* output) override {
+     if (level_ != 255) {  // Already captured.
+       return KEEP;
+     }
+     if (header.content_type() != kTlsAlertType) {
+@@ -82,19 +82,19 @@ class TlsAlertRecorder : public TlsRecor
+ 
+  private:
+   uint8_t level_;
+   uint8_t description_;
+ };
+ 
+ class HelloTruncator : public TlsHandshakeFilter {
+  public:
+-  HelloTruncator(const std::shared_ptr<TlsAgent>& agent)
++  HelloTruncator(const std::shared_ptr<TlsAgent>& a)
+       : TlsHandshakeFilter(
+-            agent, {kTlsHandshakeClientHello, kTlsHandshakeServerHello}) {}
++            a, {kTlsHandshakeClientHello, kTlsHandshakeServerHello}) {}
+   PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
+                                        const DataBuffer& input,
+                                        DataBuffer* output) override {
+     output->Assign(input.data(), input.len() - 1);
+     return CHANGE;
+   }
+ };
+ 
+@@ -166,18 +166,18 @@ TEST_P(TlsConnectDatagram, ConnectSrtp) 
+ 
+ TEST_P(TlsConnectGeneric, ConnectSendReceive) {
+   Connect();
+   SendReceive();
+ }
+ 
+ class SaveTlsRecord : public TlsRecordFilter {
+  public:
+-  SaveTlsRecord(const std::shared_ptr<TlsAgent>& agent, size_t index)
+-      : TlsRecordFilter(agent), index_(index), count_(0), contents_() {}
++  SaveTlsRecord(const std::shared_ptr<TlsAgent>& a, size_t index)
++      : TlsRecordFilter(a), index_(index), count_(0), contents_() {}
+ 
+   const DataBuffer& contents() const { return contents_; }
+ 
+  protected:
+   PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+                                     const DataBuffer& data,
+                                     DataBuffer* changed) override {
+     if (count_++ == index_) {
+@@ -222,18 +222,18 @@ TEST_F(TlsConnectStreamTls13, DecryptRec
+   static const uint8_t data[] = {0xde, 0xad, 0xd5};
+   DataBuffer buf(data, sizeof(data));
+   server_->SendBuffer(buf);
+   EXPECT_EQ(buf, saved->contents());
+ }
+ 
+ class DropTlsRecord : public TlsRecordFilter {
+  public:
+-  DropTlsRecord(const std::shared_ptr<TlsAgent>& agent, size_t index)
+-      : TlsRecordFilter(agent), index_(index), count_(0) {}
++  DropTlsRecord(const std::shared_ptr<TlsAgent>& a, size_t index)
++      : TlsRecordFilter(a), index_(index), count_(0) {}
+ 
+  protected:
+   PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+                                     const DataBuffer& data,
+                                     DataBuffer* changed) override {
+     if (count_++ == index_) {
+       return DROP;
+     }
+@@ -368,18 +368,18 @@ TEST_P(TlsHolddownTest, TestDtlsHolddown
+   RunAllTimersDown();
+   SendReceive();
+   // One for send, one for receive.
+   EXPECT_EQ(2, SSLInt_CountCipherSpecs(client_->ssl_fd()));
+ }
+ 
+ class TlsPreCCSHeaderInjector : public TlsRecordFilter {
+  public:
+-  TlsPreCCSHeaderInjector(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsRecordFilter(agent) {}
++  TlsPreCCSHeaderInjector(const std::shared_ptr<TlsAgent>& a)
++      : TlsRecordFilter(a) {}
+   virtual PacketFilter::Action FilterRecord(
+       const TlsRecordHeader& record_header, const DataBuffer& input,
+       size_t* offset, DataBuffer* output) override {
+     if (record_header.content_type() != kTlsChangeCipherSpecType) return KEEP;
+ 
+     std::cerr << "Injecting Finished header before CCS\n";
+     const uint8_t hhdr[] = {kTlsHandshakeFinished, 0x00, 0x00, 0x0c};
+     DataBuffer hhdr_buf(hhdr, sizeof(hhdr));
+diff --git a/security/nss/gtests/ssl_gtest/ssl_record_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_record_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_record_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_record_unittest.cc
+@@ -98,18 +98,18 @@ TEST_P(TlsPaddingTest, LastByteOfPadWron
+     plaintext_.Write(plaintext_.len() - 2,
+                      plaintext_.data()[plaintext_.len() - 1] + 1, 1);
+     Unpad(false);
+   }
+ }
+ 
+ class RecordReplacer : public TlsRecordFilter {
+  public:
+-  RecordReplacer(const std::shared_ptr<TlsAgent>& agent, size_t size)
+-      : TlsRecordFilter(agent), enabled_(false), size_(size) {}
++  RecordReplacer(const std::shared_ptr<TlsAgent>& a, size_t size)
++      : TlsRecordFilter(a), enabled_(false), size_(size) {}
+ 
+   PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+                                     const DataBuffer& data,
+                                     DataBuffer* changed) override {
+     if (!enabled_) {
+       return KEEP;
+     }
+ 
+diff --git a/security/nss/gtests/ssl_gtest/ssl_resumption_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_resumption_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_resumption_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_resumption_unittest.cc
+@@ -479,20 +479,18 @@ TEST_P(TlsConnectStream, TestResumptionO
+     server_->CheckErrorCode(SSL_ERROR_BAD_MAC_READ);
+   } else {
+     server_->CheckErrorCode(SSL_ERROR_HANDSHAKE_FAILURE_ALERT);
+   }
+ }
+ 
+ class SelectedVersionReplacer : public TlsHandshakeFilter {
+  public:
+-  SelectedVersionReplacer(const std::shared_ptr<TlsAgent>& agent,
+-                          uint16_t version)
+-      : TlsHandshakeFilter(agent, {kTlsHandshakeServerHello}),
+-        version_(version) {}
++  SelectedVersionReplacer(const std::shared_ptr<TlsAgent>& a, uint16_t version)
++      : TlsHandshakeFilter(a, {kTlsHandshakeServerHello}), version_(version) {}
+ 
+  protected:
+   PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
+                                        const DataBuffer& input,
+                                        DataBuffer* output) override {
+     *output = input;
+     output->Write(0, static_cast<uint32_t>(version_), 2);
+     return CHANGE;
+diff --git a/security/nss/gtests/ssl_gtest/ssl_skip_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_skip_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_skip_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_skip_unittest.cc
+@@ -17,21 +17,19 @@
+  * See <https://www.smacktls.com/smack.pdf> for a description of the problems
+  * that this sort of attack can enable.
+  */
+ namespace nss_test {
+ 
+ class TlsHandshakeSkipFilter : public TlsRecordFilter {
+  public:
+   // A TLS record filter that skips handshake messages of the identified type.
+-  TlsHandshakeSkipFilter(const std::shared_ptr<TlsAgent>& agent,
++  TlsHandshakeSkipFilter(const std::shared_ptr<TlsAgent>& a,
+                          uint8_t handshake_type)
+-      : TlsRecordFilter(agent),
+-        handshake_type_(handshake_type),
+-        skipped_(false) {}
++      : TlsRecordFilter(a), handshake_type_(handshake_type), skipped_(false) {}
+ 
+  protected:
+   // Takes a record; if it is a handshake record, it removes the first handshake
+   // message that is of handshake_type_ type.
+   virtual PacketFilter::Action FilterRecord(
+       const TlsRecordHeader& record_header, const DataBuffer& input,
+       DataBuffer* output) {
+     if (record_header.content_type() != kTlsHandshakeType) {
+diff --git a/security/nss/gtests/ssl_gtest/ssl_tls13compat_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_tls13compat_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_tls13compat_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_tls13compat_unittest.cc
+@@ -339,25 +339,9 @@ TEST_F(TlsConnectDatagram13, CompatModeD
+               server_records->record(i).header.content_type());
+   }
+ 
+   uint32_t session_id_len = 0;
+   EXPECT_TRUE(server_hello->buffer().Read(2 + 32, 1, &session_id_len));
+   EXPECT_EQ(0U, session_id_len);
+ }
+ 
+-TEST_F(Tls13CompatTest, ConnectWith12ThenAttemptToResume13CompatMode) {
+-  ConfigureSessionCache(RESUME_SESSIONID, RESUME_SESSIONID);
+-  ConfigureVersion(SSL_LIBRARY_VERSION_TLS_1_2);
+-  Connect();
+-
+-  Reset();
+-  ExpectResumption(RESUME_NONE);
+-  version_ = SSL_LIBRARY_VERSION_TLS_1_3;
+-  client_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_2,
+-                           SSL_LIBRARY_VERSION_TLS_1_3);
+-  server_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_2,
+-                           SSL_LIBRARY_VERSION_TLS_1_3);
+-  EnableCompatMode();
+-  Connect();
+-}
+-
+ }  // namespace nss_test
+diff --git a/security/nss/gtests/ssl_gtest/ssl_versionpolicy_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_versionpolicy_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_versionpolicy_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_versionpolicy_unittest.cc
+@@ -45,22 +45,22 @@ std::string GetSSLVersionString(uint16_t
+ inline std::ostream& operator<<(std::ostream& stream,
+                                 const SSLVersionRange& vr) {
+   return stream << GetSSLVersionString(vr.min) << ","
+                 << GetSSLVersionString(vr.max);
+ }
+ 
+ class VersionRangeWithLabel {
+  public:
+-  VersionRangeWithLabel(const std::string& label, const SSLVersionRange& vr)
+-      : label_(label), vr_(vr) {}
+-  VersionRangeWithLabel(const std::string& label, uint16_t min, uint16_t max)
+-      : label_(label) {
+-    vr_.min = min;
+-    vr_.max = max;
++  VersionRangeWithLabel(const std::string& txt, const SSLVersionRange& vr)
++      : label_(txt), vr_(vr) {}
++  VersionRangeWithLabel(const std::string& txt, uint16_t start, uint16_t end)
++      : label_(txt) {
++    vr_.min = start;
++    vr_.max = end;
+   }
+   VersionRangeWithLabel(const std::string& label) : label_(label) {
+     vr_.min = vr_.max = SSL_LIBRARY_VERSION_NONE;
+   }
+ 
+   void WriteStream(std::ostream& stream) const {
+     stream << " " << label_ << ": " << vr_;
+   }
+diff --git a/security/nss/gtests/ssl_gtest/test_io.cc b/security/nss/gtests/ssl_gtest/test_io.cc
+--- a/security/nss/gtests/ssl_gtest/test_io.cc
++++ b/security/nss/gtests/ssl_gtest/test_io.cc
+@@ -94,41 +94,41 @@ int32_t DummyPrSocket::Recv(PRFileDesc *
+ }
+ 
+ int32_t DummyPrSocket::Write(PRFileDesc *f, const void *buf, int32_t length) {
+   if (write_error_) {
+     PR_SetError(write_error_, 0);
+     return -1;
+   }
+ 
+-  auto peer = peer_.lock();
+-  if (!peer) {
++  auto dst = peer_.lock();
++  if (!dst) {
+     PR_SetError(PR_IO_ERROR, 0);
+     return -1;
+   }
+ 
+   DataBuffer packet(static_cast<const uint8_t *>(buf),
+                     static_cast<size_t>(length));
+   DataBuffer filtered;
+   PacketFilter::Action action = PacketFilter::KEEP;
+   if (filter_) {
+     action = filter_->Process(packet, &filtered);
+   }
+   switch (action) {
+     case PacketFilter::CHANGE:
+       LOG("Original packet: " << packet);
+       LOG("Filtered packet: " << filtered);
+-      peer->PacketReceived(filtered);
++      dst->PacketReceived(filtered);
+       break;
+     case PacketFilter::DROP:
+       LOG("Droppped packet: " << packet);
+       break;
+     case PacketFilter::KEEP:
+       LOGV("Packet: " << packet);
+-      peer->PacketReceived(packet);
++      dst->PacketReceived(packet);
+       break;
+   }
+   // libssl can't handle it if this reports something other than the length
+   // of what was passed in (or less, but we're not doing partial writes).
+   return static_cast<int32_t>(packet.len());
+ }
+ 
+ Poller *Poller::instance;
+diff --git a/security/nss/gtests/ssl_gtest/test_io.h b/security/nss/gtests/ssl_gtest/test_io.h
+--- a/security/nss/gtests/ssl_gtest/test_io.h
++++ b/security/nss/gtests/ssl_gtest/test_io.h
+@@ -54,31 +54,31 @@ class PacketFilter {
+   virtual Action Filter(const DataBuffer& input, DataBuffer* output) = 0;
+ 
+  private:
+   bool enabled_;
+ };
+ 
+ class DummyPrSocket : public DummyIOLayerMethods {
+  public:
+-  DummyPrSocket(const std::string& name, SSLProtocolVariant variant)
++  DummyPrSocket(const std::string& name, SSLProtocolVariant var)
+       : name_(name),
+-        variant_(variant),
++        variant_(var),
+         peer_(),
+         input_(),
+         filter_(nullptr),
+         write_error_(0) {}
+   virtual ~DummyPrSocket() {}
+ 
+   // Create a file descriptor that will reference this object.  The fd must not
+   // live longer than this adapter; call PR_Close() before.
+   ScopedPRFileDesc CreateFD();
+ 
+   std::weak_ptr<DummyPrSocket>& peer() { return peer_; }
+-  void SetPeer(const std::shared_ptr<DummyPrSocket>& peer) { peer_ = peer; }
++  void SetPeer(const std::shared_ptr<DummyPrSocket>& p) { peer_ = p; }
+   void SetPacketFilter(const std::shared_ptr<PacketFilter>& filter) {
+     filter_ = filter;
+   }
+   // Drops peer, packet filter and any outstanding packets.
+   void Reset();
+ 
+   void PacketReceived(const DataBuffer& data);
+   int32_t Read(PRFileDesc* f, void* data, int32_t len) override;
+diff --git a/security/nss/gtests/ssl_gtest/tls_agent.cc b/security/nss/gtests/ssl_gtest/tls_agent.cc
+--- a/security/nss/gtests/ssl_gtest/tls_agent.cc
++++ b/security/nss/gtests/ssl_gtest/tls_agent.cc
+@@ -39,23 +39,22 @@ const std::string TlsAgent::kServerRsaPs
+ const std::string TlsAgent::kServerRsaDecrypt = "rsa_decrypt";
+ const std::string TlsAgent::kServerEcdsa256 = "ecdsa256";
+ const std::string TlsAgent::kServerEcdsa384 = "ecdsa384";
+ const std::string TlsAgent::kServerEcdsa521 = "ecdsa521";
+ const std::string TlsAgent::kServerEcdhRsa = "ecdh_rsa";
+ const std::string TlsAgent::kServerEcdhEcdsa = "ecdh_ecdsa";
+ const std::string TlsAgent::kServerDsa = "dsa";
+ 
+-TlsAgent::TlsAgent(const std::string& name, Role role,
+-                   SSLProtocolVariant variant)
+-    : name_(name),
+-      variant_(variant),
+-      role_(role),
++TlsAgent::TlsAgent(const std::string& nm, Role rl, SSLProtocolVariant var)
++    : name_(nm),
++      variant_(var),
++      role_(rl),
+       server_key_bits_(0),
+-      adapter_(new DummyPrSocket(role_str(), variant)),
++      adapter_(new DummyPrSocket(role_str(), var)),
+       ssl_fd_(nullptr),
+       state_(STATE_INIT),
+       timer_handle_(nullptr),
+       falsestart_enabled_(false),
+       expected_version_(0),
+       expected_cipher_suite_(0),
+       expect_resumption_(false),
+       expect_client_auth_(false),
+@@ -98,42 +97,42 @@ TlsAgent::~TlsAgent() {
+     ADD_FAILURE() << "Wrong expected_received_alert status: " << role_str();
+   }
+   if (expected_sent_alert_ != kTlsAlertCloseNotify ||
+       expected_sent_alert_level_ != kTlsAlertWarning) {
+     ADD_FAILURE() << "Wrong expected_sent_alert status: " << role_str();
+   }
+ }
+ 
+-void TlsAgent::SetState(State state) {
+-  if (state_ == state) return;
++void TlsAgent::SetState(State s) {
++  if (state_ == s) return;
+ 
+-  LOG("Changing state from " << state_ << " to " << state);
+-  state_ = state;
++  LOG("Changing state from " << state_ << " to " << s);
++  state_ = s;
+ }
+ 
+ /*static*/ bool TlsAgent::LoadCertificate(const std::string& name,
+                                           ScopedCERTCertificate* cert,
+                                           ScopedSECKEYPrivateKey* priv) {
+   cert->reset(PK11_FindCertFromNickname(name.c_str(), nullptr));
+   EXPECT_NE(nullptr, cert->get());
+   if (!cert->get()) return false;
+ 
+   priv->reset(PK11_FindKeyByAnyCert(cert->get(), nullptr));
+   EXPECT_NE(nullptr, priv->get());
+   if (!priv->get()) return false;
+ 
+   return true;
+ }
+ 
+-bool TlsAgent::ConfigServerCert(const std::string& name, bool updateKeyBits,
++bool TlsAgent::ConfigServerCert(const std::string& id, bool updateKeyBits,
+                                 const SSLExtraServerCertData* serverCertData) {
+   ScopedCERTCertificate cert;
+   ScopedSECKEYPrivateKey priv;
+-  if (!TlsAgent::LoadCertificate(name, &cert, &priv)) {
++  if (!TlsAgent::LoadCertificate(id, &cert, &priv)) {
+     return false;
+   }
+ 
+   if (updateKeyBits) {
+     ScopedSECKEYPublicKey pub(CERT_ExtractPublicKey(cert.get()));
+     EXPECT_NE(nullptr, pub.get());
+     if (!pub.get()) return false;
+     server_key_bits_ = SECKEY_PublicKeyStrengthInBits(pub.get());
+@@ -277,18 +276,18 @@ bool TlsAgent::GetPeerChainLength(size_t
+     ++(*count);
+   }
+ 
+   CERT_DestroyCertList(chain);
+ 
+   return true;
+ }
+ 
+-void TlsAgent::CheckCipherSuite(uint16_t cipher_suite) {
+-  EXPECT_EQ(csinfo_.cipherSuite, cipher_suite);
++void TlsAgent::CheckCipherSuite(uint16_t suite) {
++  EXPECT_EQ(csinfo_.cipherSuite, suite);
+ }
+ 
+ void TlsAgent::RequestClientAuth(bool requireAuth) {
+   ASSERT_EQ(SERVER, role_);
+ 
+   SetOption(SSL_REQUEST_CERTIFICATE, PR_TRUE);
+   SetOption(SSL_REQUIRE_CERTIFICATE, requireAuth ? PR_TRUE : PR_FALSE);
+ 
+@@ -437,19 +436,17 @@ void TlsAgent::SetResumptionTokenCallbac
+   EXPECT_EQ(SECSuccess, rv);
+ }
+ 
+ void TlsAgent::GetVersionRange(uint16_t* minver, uint16_t* maxver) {
+   *minver = vrange_.min;
+   *maxver = vrange_.max;
+ }
+ 
+-void TlsAgent::SetExpectedVersion(uint16_t version) {
+-  expected_version_ = version;
+-}
++void TlsAgent::SetExpectedVersion(uint16_t ver) { expected_version_ = ver; }
+ 
+ void TlsAgent::SetServerKeyBits(uint16_t bits) { server_key_bits_ = bits; }
+ 
+ void TlsAgent::ExpectReadWriteError() { expect_readwrite_error_ = true; }
+ 
+ void TlsAgent::SkipVersionChecks() { skip_version_checks_ = true; }
+ 
+ void TlsAgent::SetSignatureSchemes(const SSLSignatureScheme* schemes,
+@@ -486,20 +483,20 @@ void TlsAgent::SetSignatureSchemes(const
+   for (unsigned int j = 0; j < count && i < configuredCount; ++j) {
+     if (i < configuredCount && schemes[j] == configuredSchemes[i]) {
+       ++i;
+     }
+   }
+   EXPECT_EQ(i, configuredCount) << "schemes in use were all set";
+ }
+ 
+-void TlsAgent::CheckKEA(SSLKEAType kea_type, SSLNamedGroup kea_group,
++void TlsAgent::CheckKEA(SSLKEAType kea, SSLNamedGroup kea_group,
+                         size_t kea_size) const {
+   EXPECT_EQ(STATE_CONNECTED, state_);
+-  EXPECT_EQ(kea_type, info_.keaType);
++  EXPECT_EQ(kea, info_.keaType);
+   if (kea_size == 0) {
+     switch (kea_group) {
+       case ssl_grp_ec_curve25519:
+         kea_size = 255;
+         break;
+       case ssl_grp_ec_secp256r1:
+         kea_size = 256;
+         break;
+@@ -510,17 +507,17 @@ void TlsAgent::CheckKEA(SSLKEAType kea_t
+         kea_size = 2048;
+         break;
+       case ssl_grp_ffdhe_3072:
+         kea_size = 3072;
+         break;
+       case ssl_grp_ffdhe_custom:
+         break;
+       default:
+-        if (kea_type == ssl_kea_rsa) {
++        if (kea == ssl_kea_rsa) {
+           kea_size = server_key_bits_;
+         } else {
+           EXPECT_TRUE(false) << "need to update group sizes";
+         }
+     }
+   }
+   if (kea_group != ssl_grp_ffdhe_custom) {
+     EXPECT_EQ(kea_size, info_.keaKeyBits);
+@@ -529,23 +526,23 @@ void TlsAgent::CheckKEA(SSLKEAType kea_t
+ }
+ 
+ void TlsAgent::CheckOriginalKEA(SSLNamedGroup kea_group) const {
+   if (kea_group != ssl_grp_ffdhe_custom) {
+     EXPECT_EQ(kea_group, info_.originalKeaGroup);
+   }
+ }
+ 
+-void TlsAgent::CheckAuthType(SSLAuthType auth_type,
++void TlsAgent::CheckAuthType(SSLAuthType auth,
+                              SSLSignatureScheme sig_scheme) const {
+   EXPECT_EQ(STATE_CONNECTED, state_);
+-  EXPECT_EQ(auth_type, info_.authType);
++  EXPECT_EQ(auth, info_.authType);
+   EXPECT_EQ(server_key_bits_, info_.authKeyBits);
+   if (expected_version_ < SSL_LIBRARY_VERSION_TLS_1_2) {
+-    switch (auth_type) {
++    switch (auth) {
+       case ssl_auth_rsa_sign:
+         sig_scheme = ssl_sig_rsa_pkcs1_sha1md5;
+         break;
+       case ssl_auth_ecdsa:
+         sig_scheme = ssl_sig_ecdsa_sha1;
+         break;
+       default:
+         break;
+@@ -553,33 +550,32 @@ void TlsAgent::CheckAuthType(SSLAuthType
+   }
+   EXPECT_EQ(sig_scheme, info_.signatureScheme);
+ 
+   if (info_.protocolVersion >= SSL_LIBRARY_VERSION_TLS_1_3) {
+     return;
+   }
+ 
+   // Check authAlgorithm, which is the old value for authType.  This is a second
+-  // switch
+-  // statement because default label is different.
+-  switch (auth_type) {
++  // switch statement because default label is different.
++  switch (auth) {
+     case ssl_auth_rsa_sign:
+       EXPECT_EQ(ssl_auth_rsa_decrypt, csinfo_.authAlgorithm)
+           << "authAlgorithm for RSA is always decrypt";
+       break;
+     case ssl_auth_ecdh_rsa:
+       EXPECT_EQ(ssl_auth_rsa_decrypt, csinfo_.authAlgorithm)
+           << "authAlgorithm for ECDH_RSA is RSA decrypt (i.e., wrong)";
+       break;
+     case ssl_auth_ecdh_ecdsa:
+       EXPECT_EQ(ssl_auth_ecdsa, csinfo_.authAlgorithm)
+           << "authAlgorithm for ECDH_ECDSA is ECDSA (i.e., wrong)";
+       break;
+     default:
+-      EXPECT_EQ(auth_type, csinfo_.authAlgorithm)
++      EXPECT_EQ(auth, csinfo_.authAlgorithm)
+           << "authAlgorithm is (usually) the same as authType";
+       break;
+   }
+ }
+ 
+ void TlsAgent::EnableFalseStart() {
+   EXPECT_TRUE(EnsureTlsSetup());
+ 
+@@ -595,25 +591,25 @@ void TlsAgent::EnableAlpn(const uint8_t*
+   EXPECT_TRUE(EnsureTlsSetup());
+ 
+   SetOption(SSL_ENABLE_ALPN, PR_TRUE);
+   EXPECT_EQ(SECSuccess, SSL_SetNextProtoNego(ssl_fd(), val, len));
+ }
+ 
+ void TlsAgent::CheckAlpn(SSLNextProtoState expected_state,
+                          const std::string& expected) const {
+-  SSLNextProtoState state;
++  SSLNextProtoState npn_state;
+   char chosen[10];
+   unsigned int chosen_len;
+-  SECStatus rv = SSL_GetNextProto(ssl_fd(), &state,
++  SECStatus rv = SSL_GetNextProto(ssl_fd(), &npn_state,
+                                   reinterpret_cast<unsigned char*>(chosen),
+                                   &chosen_len, sizeof(chosen));
+   EXPECT_EQ(SECSuccess, rv);
+-  EXPECT_EQ(expected_state, state);
+-  if (state == SSL_NEXT_PROTO_NO_SUPPORT) {
++  EXPECT_EQ(expected_state, npn_state);
++  if (npn_state == SSL_NEXT_PROTO_NO_SUPPORT) {
+     EXPECT_EQ("", expected);
+   } else {
+     EXPECT_NE("", expected);
+     EXPECT_EQ(expected, std::string(chosen, chosen_len));
+   }
+ }
+ 
+ void TlsAgent::EnableSrtp() {
+@@ -835,20 +831,20 @@ void TlsAgent::CheckEarlyDataAccepted(bo
+   ASSERT_EQ(expected, info_.earlyDataAccepted != PR_FALSE)
+       << "unexpected early data state for " << name_;
+ }
+ 
+ void TlsAgent::CheckSecretsDestroyed() {
+   ASSERT_EQ(PR_TRUE, SSLInt_CheckSecretsDestroyed(ssl_fd()));
+ }
+ 
+-void TlsAgent::SetDowngradeCheckVersion(uint16_t version) {
++void TlsAgent::SetDowngradeCheckVersion(uint16_t ver) {
+   ASSERT_TRUE(EnsureTlsSetup());
+ 
+-  SECStatus rv = SSL_SetDowngradeCheckVersion(ssl_fd(), version);
++  SECStatus rv = SSL_SetDowngradeCheckVersion(ssl_fd(), ver);
+   ASSERT_EQ(SECSuccess, rv);
+ }
+ 
+ void TlsAgent::Handshake() {
+   LOGV("Handshake");
+   SECStatus rv = SSL_ForceHandshake(ssl_fd());
+   if (rv == SECSuccess) {
+     Connected();
+diff --git a/security/nss/gtests/ssl_gtest/tls_agent.h b/security/nss/gtests/ssl_gtest/tls_agent.h
+--- a/security/nss/gtests/ssl_gtest/tls_agent.h
++++ b/security/nss/gtests/ssl_gtest/tls_agent.h
+@@ -204,45 +204,45 @@ class TlsAgent : public PollTarget {
+   uint16_t server_key_bits() const { return server_key_bits_; }
+   uint16_t min_version() const { return vrange_.min; }
+   uint16_t max_version() const { return vrange_.max; }
+   uint16_t version() const {
+     EXPECT_EQ(STATE_CONNECTED, state_);
+     return info_.protocolVersion;
+   }
+ 
+-  bool cipher_suite(uint16_t* cipher_suite) const {
++  bool cipher_suite(uint16_t* suite) const {
+     if (state_ != STATE_CONNECTED) return false;
+ 
+-    *cipher_suite = info_.cipherSuite;
++    *suite = info_.cipherSuite;
+     return true;
+   }
+ 
+   std::string cipher_suite_name() const {
+     if (state_ != STATE_CONNECTED) return "UNKNOWN";
+ 
+     return csinfo_.cipherSuiteName;
+   }
+ 
+   std::vector<uint8_t> session_id() const {
+     return std::vector<uint8_t>(info_.sessionID,
+                                 info_.sessionID + info_.sessionIDLength);
+   }
+ 
+-  bool auth_type(SSLAuthType* auth_type) const {
++  bool auth_type(SSLAuthType* a) const {
+     if (state_ != STATE_CONNECTED) return false;
+ 
+-    *auth_type = info_.authType;
++    *a = info_.authType;
+     return true;
+   }
+ 
+-  bool kea_type(SSLKEAType* kea_type) const {
++  bool kea_type(SSLKEAType* k) const {
+     if (state_ != STATE_CONNECTED) return false;
+ 
+-    *kea_type = info_.keaType;
++    *k = info_.keaType;
+     return true;
+   }
+ 
+   size_t received_bytes() const { return recv_ctr_; }
+   PRErrorCode error_code() const { return error_code_; }
+ 
+   bool can_falsestart_hook_called() const {
+     return can_falsestart_hook_called_;
+diff --git a/security/nss/gtests/ssl_gtest/tls_filter.cc b/security/nss/gtests/ssl_gtest/tls_filter.cc
+--- a/security/nss/gtests/ssl_gtest/tls_filter.cc
++++ b/security/nss/gtests/ssl_gtest/tls_filter.cc
+@@ -174,41 +174,41 @@ PacketFilter::Action TlsRecordFilter::Fi
+   EXPECT_TRUE(rv);
+   if (!rv) {
+     return KEEP;
+   }
+   *offset = out_header.Write(output, *offset, ciphertext);
+   return CHANGE;
+ }
+ 
+-bool TlsRecordHeader::Parse(uint64_t sequence_number, TlsParser* parser,
++bool TlsRecordHeader::Parse(uint64_t seqno, TlsParser* parser,
+                             DataBuffer* body) {
+   if (!parser->Read(&content_type_)) {
+     return false;
+   }
+ 
+-  uint32_t version;
+-  if (!parser->Read(&version, 2)) {
++  uint32_t ver;
++  if (!parser->Read(&ver, 2)) {
+     return false;
+   }
+-  version_ = version;
++  version_ = ver;
+ 
+   // If this is DTLS, overwrite the sequence number.
+-  if (IsDtls(version)) {
++  if (IsDtls(ver)) {
+     uint32_t tmp;
+     if (!parser->Read(&tmp, 4)) {
+       return false;
+     }
+     sequence_number_ = static_cast<uint64_t>(tmp) << 32;
+     if (!parser->Read(&tmp, 4)) {
+       return false;
+     }
+     sequence_number_ |= static_cast<uint64_t>(tmp);
+   } else {
+-    sequence_number_ = sequence_number;
++    sequence_number_ = seqno;
+   }
+   return parser->ReadVariable(body, 2);
+ }
+ 
+ size_t TlsRecordHeader::Write(DataBuffer* buffer, size_t offset,
+                               const DataBuffer& body) const {
+   offset = buffer->Write(offset, content_type_, 1);
+   offset = buffer->Write(offset, version_, 2);
+@@ -482,20 +482,20 @@ PacketFilter::Action TlsRecordRecorder::
+ 
+ PacketFilter::Action TlsConversationRecorder::FilterRecord(
+     const TlsRecordHeader& header, const DataBuffer& input,
+     DataBuffer* output) {
+   buffer_.Append(input);
+   return KEEP;
+ }
+ 
+-PacketFilter::Action TlsHeaderRecorder::FilterRecord(
+-    const TlsRecordHeader& header, const DataBuffer& input,
+-    DataBuffer* output) {
+-  headers_.push_back(header);
++PacketFilter::Action TlsHeaderRecorder::FilterRecord(const TlsRecordHeader& hdr,
++                                                     const DataBuffer& input,
++                                                     DataBuffer* output) {
++  headers_.push_back(hdr);
+   return KEEP;
+ }
+ 
+ const TlsRecordHeader* TlsHeaderRecorder::header(size_t index) {
+   if (index > headers_.size() + 1) {
+     return nullptr;
+   }
+   return &headers_[index];
+diff --git a/security/nss/gtests/ssl_gtest/tls_filter.h b/security/nss/gtests/ssl_gtest/tls_filter.h
+--- a/security/nss/gtests/ssl_gtest/tls_filter.h
++++ b/security/nss/gtests/ssl_gtest/tls_filter.h
+@@ -23,35 +23,32 @@ extern "C" {
+ 
+ namespace nss_test {
+ 
+ class TlsCipherSpec;
+ 
+ class TlsVersioned {
+  public:
+   TlsVersioned() : version_(0) {}
+-  explicit TlsVersioned(uint16_t version) : version_(version) {}
++  explicit TlsVersioned(uint16_t v) : version_(v) {}
+ 
+   bool is_dtls() const { return IsDtls(version_); }
+   uint16_t version() const { return version_; }
+ 
+   void WriteStream(std::ostream& stream) const;
+ 
+  protected:
+   uint16_t version_;
+ };
+ 
+ class TlsRecordHeader : public TlsVersioned {
+  public:
+   TlsRecordHeader() : TlsVersioned(), content_type_(0), sequence_number_(0) {}
+-  TlsRecordHeader(uint16_t version, uint8_t content_type,
+-                  uint64_t sequence_number)
+-      : TlsVersioned(version),
+-        content_type_(content_type),
+-        sequence_number_(sequence_number) {}
++  TlsRecordHeader(uint16_t ver, uint8_t ct, uint64_t seqno)
++      : TlsVersioned(ver), content_type_(ct), sequence_number_(seqno) {}
+ 
+   uint8_t content_type() const { return content_type_; }
+   uint64_t sequence_number() const { return sequence_number_; }
+   uint16_t epoch() const {
+     return static_cast<uint16_t>(sequence_number_ >> 48);
+   }
+   size_t header_length() const { return is_dtls() ? 13 : 5; }
+ 
+@@ -78,18 +75,18 @@ inline std::shared_ptr<T> MakeTlsFilter(
+   auto filter = std::make_shared<T>(agent, std::forward<Args>(args)...);
+   agent->SetFilter(filter);
+   return filter;
+ }
+ 
+ // Abstract filter that operates on entire (D)TLS records.
+ class TlsRecordFilter : public PacketFilter {
+  public:
+-  TlsRecordFilter(const std::shared_ptr<TlsAgent>& agent)
+-      : agent_(agent),
++  TlsRecordFilter(const std::shared_ptr<TlsAgent>& a)
++      : agent_(a),
+         count_(0),
+         cipher_spec_(),
+         dropped_record_(false),
+         in_sequence_number_(0),
+         out_sequence_number_(0) {}
+ 
+   std::shared_ptr<TlsAgent> agent() const { return agent_.lock(); }
+ 
+@@ -178,23 +175,21 @@ inline std::ostream& operator<<(std::ost
+   return stream << ' ' << std::hex << hdr.sequence_number() << std::dec;
+ }
+ 
+ // Abstract filter that operates on handshake messages rather than records.
+ // This assumes that the handshake messages are written in a block as entire
+ // records and that they don't span records or anything crazy like that.
+ class TlsHandshakeFilter : public TlsRecordFilter {
+  public:
+-  TlsHandshakeFilter(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsRecordFilter(agent), handshake_types_(), preceding_fragment_() {}
+-  TlsHandshakeFilter(const std::shared_ptr<TlsAgent>& agent,
++  TlsHandshakeFilter(const std::shared_ptr<TlsAgent>& a)
++      : TlsRecordFilter(a), handshake_types_(), preceding_fragment_() {}
++  TlsHandshakeFilter(const std::shared_ptr<TlsAgent>& a,
+                      const std::set<uint8_t>& types)
+-      : TlsRecordFilter(agent),
+-        handshake_types_(types),
+-        preceding_fragment_() {}
++      : TlsRecordFilter(a), handshake_types_(types), preceding_fragment_() {}
+ 
+   // This filter can be set to be selective based on handshake message type.  If
+   // this function isn't used (or the set is empty), then all handshake messages
+   // will be filtered.
+   void SetHandshakeTypes(const std::set<uint8_t>& types) {
+     handshake_types_ = types;
+   }
+ 
+@@ -238,58 +233,58 @@ class TlsHandshakeFilter : public TlsRec
+ 
+   std::set<uint8_t> handshake_types_;
+   DataBuffer preceding_fragment_;
+ };
+ 
+ // Make a copy of the first instance of a handshake message.
+ class TlsHandshakeRecorder : public TlsHandshakeFilter {
+  public:
+-  TlsHandshakeRecorder(const std::shared_ptr<TlsAgent>& agent,
++  TlsHandshakeRecorder(const std::shared_ptr<TlsAgent>& a,
+                        uint8_t handshake_type)
+-      : TlsHandshakeFilter(agent, {handshake_type}), buffer_() {}
+-  TlsHandshakeRecorder(const std::shared_ptr<TlsAgent>& agent,
++      : TlsHandshakeFilter(a, {handshake_type}), buffer_() {}
++  TlsHandshakeRecorder(const std::shared_ptr<TlsAgent>& a,
+                        const std::set<uint8_t>& handshake_types)
+-      : TlsHandshakeFilter(agent, handshake_types), buffer_() {}
++      : TlsHandshakeFilter(a, handshake_types), buffer_() {}
+ 
+   virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
+                                                const DataBuffer& input,
+                                                DataBuffer* output);
+ 
+   void Reset() { buffer_.Truncate(0); }
+ 
+   const DataBuffer& buffer() const { return buffer_; }
+ 
+  private:
+   DataBuffer buffer_;
+ };
+ 
+ // Replace all instances of a handshake message.
+ class TlsInspectorReplaceHandshakeMessage : public TlsHandshakeFilter {
+  public:
+-  TlsInspectorReplaceHandshakeMessage(const std::shared_ptr<TlsAgent>& agent,
++  TlsInspectorReplaceHandshakeMessage(const std::shared_ptr<TlsAgent>& a,
+                                       uint8_t handshake_type,
+                                       const DataBuffer& replacement)
+-      : TlsHandshakeFilter(agent, {handshake_type}), buffer_(replacement) {}
++      : TlsHandshakeFilter(a, {handshake_type}), buffer_(replacement) {}
+ 
+   virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
+                                                const DataBuffer& input,
+                                                DataBuffer* output);
+ 
+  private:
+   DataBuffer buffer_;
+ };
+ 
+ // Make a copy of each record of a given type.
+ class TlsRecordRecorder : public TlsRecordFilter {
+  public:
+-  TlsRecordRecorder(const std::shared_ptr<TlsAgent>& agent, uint8_t ct)
+-      : TlsRecordFilter(agent), filter_(true), ct_(ct), records_() {}
+-  TlsRecordRecorder(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsRecordFilter(agent),
++  TlsRecordRecorder(const std::shared_ptr<TlsAgent>& a, uint8_t ct)
++      : TlsRecordFilter(a), filter_(true), ct_(ct), records_() {}
++  TlsRecordRecorder(const std::shared_ptr<TlsAgent>& a)
++      : TlsRecordFilter(a),
+         filter_(false),
+         ct_(content_handshake),  // dummy (<optional> is C++14)
+         records_() {}
+   virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+                                             const DataBuffer& input,
+                                             DataBuffer* output);
+ 
+   size_t count() const { return records_.size(); }
+@@ -301,33 +296,32 @@ class TlsRecordRecorder : public TlsReco
+   bool filter_;
+   uint8_t ct_;
+   std::vector<TlsRecord> records_;
+ };
+ 
+ // Make a copy of the complete conversation.
+ class TlsConversationRecorder : public TlsRecordFilter {
+  public:
+-  TlsConversationRecorder(const std::shared_ptr<TlsAgent>& agent,
++  TlsConversationRecorder(const std::shared_ptr<TlsAgent>& a,
+                           DataBuffer& buffer)
+-      : TlsRecordFilter(agent), buffer_(buffer) {}
++      : TlsRecordFilter(a), buffer_(buffer) {}
+ 
+   virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+                                             const DataBuffer& input,
+                                             DataBuffer* output);
+ 
+  private:
+   DataBuffer buffer_;
+ };
+ 
+ // Make a copy of the records
+ class TlsHeaderRecorder : public TlsRecordFilter {
+  public:
+-  TlsHeaderRecorder(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsRecordFilter(agent) {}
++  TlsHeaderRecorder(const std::shared_ptr<TlsAgent>& a) : TlsRecordFilter(a) {}
+   virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+                                             const DataBuffer& input,
+                                             DataBuffer* output);
+   const TlsRecordHeader* header(size_t index);
+ 
+  private:
+   std::vector<TlsRecordHeader> headers_;
+ };
+@@ -354,25 +348,25 @@ class ChainedPacketFilter : public Packe
+   std::vector<std::shared_ptr<PacketFilter>> filters_;
+ };
+ 
+ typedef std::function<bool(TlsParser* parser, const TlsVersioned& header)>
+     TlsExtensionFinder;
+ 
+ class TlsExtensionFilter : public TlsHandshakeFilter {
+  public:
+-  TlsExtensionFilter(const std::shared_ptr<TlsAgent>& agent)
+-      : TlsHandshakeFilter(agent,
++  TlsExtensionFilter(const std::shared_ptr<TlsAgent>& a)
++      : TlsHandshakeFilter(a,
+                            {kTlsHandshakeClientHello, kTlsHandshakeServerHello,
+                             kTlsHandshakeHelloRetryRequest,
+                             kTlsHandshakeEncryptedExtensions}) {}
+ 
+-  TlsExtensionFilter(const std::shared_ptr<TlsAgent>& agent,
++  TlsExtensionFilter(const std::shared_ptr<TlsAgent>& a,
+                      const std::set<uint8_t>& types)
+-      : TlsHandshakeFilter(agent, types) {}
++      : TlsHandshakeFilter(a, types) {}
+ 
+   static bool FindExtensions(TlsParser* parser, const HandshakeHeader& header);
+ 
+  protected:
+   PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
+                                        const DataBuffer& input,
+                                        DataBuffer* output) override;
+ 
+@@ -383,19 +377,19 @@ class TlsExtensionFilter : public TlsHan
+  private:
+   PacketFilter::Action FilterExtensions(TlsParser* parser,
+                                         const DataBuffer& input,
+                                         DataBuffer* output);
+ };
+ 
+ class TlsExtensionCapture : public TlsExtensionFilter {
+  public:
+-  TlsExtensionCapture(const std::shared_ptr<TlsAgent>& agent, uint16_t ext,
++  TlsExtensionCapture(const std::shared_ptr<TlsAgent>& a, uint16_t ext,
+                       bool last = false)
+-      : TlsExtensionFilter(agent),
++      : TlsExtensionFilter(a),
+         extension_(ext),
+         captured_(false),
+         last_(last),
+         data_() {}
+ 
+   const DataBuffer& extension() const { return data_; }
+   bool captured() const { return captured_; }
+ 
+@@ -408,57 +402,55 @@ class TlsExtensionCapture : public TlsEx
+   const uint16_t extension_;
+   bool captured_;
+   bool last_;
+   DataBuffer data_;
+ };
+ 
+ class TlsExtensionReplacer : public TlsExtensionFilter {
+  public:
+-  TlsExtensionReplacer(const std::shared_ptr<TlsAgent>& agent,
+-                       uint16_t extension, const DataBuffer& data)
+-      : TlsExtensionFilter(agent), extension_(extension), data_(data) {}
++  TlsExtensionReplacer(const std::shared_ptr<TlsAgent>& a, uint16_t extension,
++                       const DataBuffer& data)
++      : TlsExtensionFilter(a), extension_(extension), data_(data) {}
+   PacketFilter::Action FilterExtension(uint16_t extension_type,
+                                        const DataBuffer& input,
+                                        DataBuffer* output) override;
+ 
+  private:
+   const uint16_t extension_;
+   const DataBuffer data_;
+ };
+ 
+ class TlsExtensionDropper : public TlsExtensionFilter {
+  public:
+-  TlsExtensionDropper(const std::shared_ptr<TlsAgent>& agent,
+-                      uint16_t extension)
+-      : TlsExtensionFilter(agent), extension_(extension) {}
++  TlsExtensionDropper(const std::shared_ptr<TlsAgent>& a, uint16_t extension)
++      : TlsExtensionFilter(a), extension_(extension) {}
+   PacketFilter::Action FilterExtension(uint16_t extension_type,
+                                        const DataBuffer&, DataBuffer*) override;
+ 
+  private:
+   uint16_t extension_;
+ };
+ 
+ class TlsExtensionInjector : public TlsHandshakeFilter {
+  public:
+-  TlsExtensionInjector(const std::shared_ptr<TlsAgent>& agent, uint16_t ext,
++  TlsExtensionInjector(const std::shared_ptr<TlsAgent>& a, uint16_t ext,
+                        const DataBuffer& data)
+-      : TlsHandshakeFilter(agent), extension_(ext), data_(data) {}
++      : TlsHandshakeFilter(a), extension_(ext), data_(data) {}
+ 
+  protected:
+   PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
+                                        const DataBuffer& input,
+                                        DataBuffer* output) override;
+ 
+  private:
+   const uint16_t extension_;
+   const DataBuffer data_;
+ };
+ 
+-class TlsAgent;
+ typedef std::function<void(void)> VoidFunction;
+ 
+ class AfterRecordN : public TlsRecordFilter {
+  public:
+   AfterRecordN(const std::shared_ptr<TlsAgent>& src,
+                const std::shared_ptr<TlsAgent>& dest, unsigned int record,
+                VoidFunction func)
+       : TlsRecordFilter(src),
+@@ -510,26 +502,26 @@ class SelectiveDropFilter : public Packe
+   uint8_t counter_;
+ };
+ 
+ // This class selectively drops complete records. The difference from
+ // SelectiveDropFilter is that if multiple DTLS records are in the same
+ // datagram, we just drop one.
+ class SelectiveRecordDropFilter : public TlsRecordFilter {
+  public:
+-  SelectiveRecordDropFilter(const std::shared_ptr<TlsAgent>& agent,
++  SelectiveRecordDropFilter(const std::shared_ptr<TlsAgent>& a,
+                             uint32_t pattern, bool enabled = true)
+-      : TlsRecordFilter(agent), pattern_(pattern), counter_(0) {
++      : TlsRecordFilter(a), pattern_(pattern), counter_(0) {
+     if (!enabled) {
+       Disable();
+     }
+   }
+-  SelectiveRecordDropFilter(const std::shared_ptr<TlsAgent>& agent,
++  SelectiveRecordDropFilter(const std::shared_ptr<TlsAgent>& a,
+                             std::initializer_list<size_t> records)
+-      : SelectiveRecordDropFilter(agent, ToPattern(records), true) {}
++      : SelectiveRecordDropFilter(a, ToPattern(records), true) {}
+ 
+   void Reset(uint32_t pattern) {
+     counter_ = 0;
+     PacketFilter::Enable();
+     pattern_ = pattern;
+   }
+ 
+   void Reset(std::initializer_list<size_t> records) {
+@@ -546,34 +538,33 @@ class SelectiveRecordDropFilter : public
+ 
+   uint32_t pattern_;
+   uint8_t counter_;
+ };
+ 
+ // Set the version number in the ClientHello.
+ class TlsClientHelloVersionSetter : public TlsHandshakeFilter {
+  public:
+-  TlsClientHelloVersionSetter(const std::shared_ptr<TlsAgent>& agent,
++  TlsClientHelloVersionSetter(const std::shared_ptr<TlsAgent>& a,
+                               uint16_t version)
+-      : TlsHandshakeFilter(agent, {kTlsHandshakeClientHello}),
+-        version_(version) {}
++      : TlsHandshakeFilter(a, {kTlsHandshakeClientHello}), version_(version) {}
+ 
+   virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
+                                                const DataBuffer& input,
+                                                DataBuffer* output);
+ 
+  private:
+   uint16_t version_;
+ };
+ 
+ // Damages the last byte of a handshake message.
+ class TlsLastByteDamager : public TlsHandshakeFilter {
+  public:
+-  TlsLastByteDamager(const std::shared_ptr<TlsAgent>& agent, uint8_t type)
+-      : TlsHandshakeFilter(agent), type_(type) {}
++  TlsLastByteDamager(const std::shared_ptr<TlsAgent>& a, uint8_t type)
++      : TlsHandshakeFilter(a), type_(type) {}
+   PacketFilter::Action FilterHandshake(
+       const TlsHandshakeFilter::HandshakeHeader& header,
+       const DataBuffer& input, DataBuffer* output) override {
+     if (header.handshake_type() != type_) {
+       return KEEP;
+     }
+ 
+     *output = input;
+@@ -583,19 +574,19 @@ class TlsLastByteDamager : public TlsHan
+   }
+ 
+  private:
+   uint8_t type_;
+ };
+ 
+ class SelectedCipherSuiteReplacer : public TlsHandshakeFilter {
+  public:
+-  SelectedCipherSuiteReplacer(const std::shared_ptr<TlsAgent>& agent,
++  SelectedCipherSuiteReplacer(const std::shared_ptr<TlsAgent>& a,
+                               uint16_t suite)
+-      : TlsHandshakeFilter(agent, {kTlsHandshakeServerHello}),
++      : TlsHandshakeFilter(a, {kTlsHandshakeServerHello}),
+         cipher_suite_(suite) {}
+ 
+  protected:
+   PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
+                                        const DataBuffer& input,
+                                        DataBuffer* output) override;
+ 
+  private:
+diff --git a/security/nss/gtests/ssl_gtest/tls_protect.cc b/security/nss/gtests/ssl_gtest/tls_protect.cc
+--- a/security/nss/gtests/ssl_gtest/tls_protect.cc
++++ b/security/nss/gtests/ssl_gtest/tls_protect.cc
+@@ -86,19 +86,19 @@ bool AeadCipherChacha20Poly1305::Aead(bo
+   aeadParams.ulAADLen = 0;
+   aeadParams.ulTagLen = 16;
+ 
+   FormatNonce(seq, nonce);
+   return AeadInner(decrypt, (unsigned char *)&aeadParams, sizeof(aeadParams),
+                    in, inlen, out, outlen, maxlen);
+ }
+ 
+-bool TlsCipherSpec::Init(uint16_t epoch, SSLCipherAlgorithm cipher,
++bool TlsCipherSpec::Init(uint16_t epoc, SSLCipherAlgorithm cipher,
+                          PK11SymKey *key, const uint8_t *iv) {
+-  epoch_ = epoch;
++  epoch_ = epoc;
+   switch (cipher) {
+     case ssl_calg_aes_gcm:
+       aead_.reset(new AeadCipherAesGcm());
+       break;
+     case ssl_calg_chacha20:
+       aead_.reset(new AeadCipherChacha20Poly1305());
+       break;
+     default:
+diff --git a/security/nss/lib/base/error.c b/security/nss/lib/base/error.c
+--- a/security/nss/lib/base/error.c
++++ b/security/nss/lib/base/error.c
+@@ -10,20 +10,16 @@
+  */
+ 
+ #ifndef BASE_H
+ #include "base.h"
+ #endif              /* BASE_H */
+ #include <limits.h> /* for UINT_MAX */
+ #include <string.h> /* for memmove */
+ 
+-#if defined(__MINGW32__)
+-#include <windows.h>
+-#endif
+-
+ #define NSS_MAX_ERROR_STACK_COUNT 16 /* error codes */
+ 
+ /*
+  * The stack itself has a header, and a sequence of integers.
+  * The header records the amount of space (as measured in stack
+  * slots) already allocated for the stack, and the count of the
+  * number of records currently being used.
+  */
+@@ -64,42 +60,17 @@ static const PRCallOnceType error_call_a
+ /*
+  * error_once_function
+  *
+  * This is the once-called callback.
+  */
+ static PRStatus
+ error_once_function(void)
+ {
+-
+-/*
+- * This #ifdef function is redundant. It performs the same thing as the
+- * else case.
+- *
+- * However, the MinGW version looks up the function from nss3's export
+- * table, and on MinGW _that_ behaves differently than passing a
+- * function pointer in a different module because MinGW has
+- * -mnop-fun-dllimport specified, which generates function thunks for
+- * cross-module calls. And when a module (like nssckbi) gets unloaded,
+- * and you try to call into that thunk (which is now missing) you'll
+- * crash. So we do this bit of ugly to avoid that crash. Fortunately
+- * this is the only place we've had to do this.
+- */
+-#if defined(__MINGW32__)
+-    HMODULE nss3 = GetModuleHandleW(L"nss3");
+-    if (nss3) {
+-        FARPROC freePtr = GetProcAddress(nss3, "PR_Free");
+-        if (freePtr) {
+-            return PR_NewThreadPrivateIndex(&error_stack_index, freePtr);
+-        }
+-    }
+     return PR_NewThreadPrivateIndex(&error_stack_index, PR_Free);
+-#else
+-    return PR_NewThreadPrivateIndex(&error_stack_index, PR_Free);
+-#endif
+ }
+ 
+ /*
+  * error_get_my_stack
+  *
+  * This routine returns the calling thread's error stack, creating
+  * it if necessary.  It may return NULL upon error, which implicitly
+  * means that it ran out of memory.
+diff --git a/security/nss/lib/certdb/crl.c b/security/nss/lib/certdb/crl.c
+--- a/security/nss/lib/certdb/crl.c
++++ b/security/nss/lib/certdb/crl.c
+@@ -893,23 +893,23 @@ PreFreeEntry(void* pool, PLHashEntry* he
+ }
+ 
+ /* methods required for PL hash table functions */
+ static PLHashAllocOps preAllocOps = { PreAllocTable, PreFreeTable,
+                                       PreAllocEntry, PreFreeEntry };
+ 
+ /* destructor for PreAllocator object */
+ void
+-PreAllocator_Destroy(PreAllocator* PreAllocator)
++PreAllocator_Destroy(PreAllocator* allocator)
+ {
+-    if (!PreAllocator) {
++    if (!allocator) {
+         return;
+     }
+-    if (PreAllocator->arena) {
+-        PORT_FreeArena(PreAllocator->arena, PR_TRUE);
++    if (allocator->arena) {
++        PORT_FreeArena(allocator->arena, PR_TRUE);
+     }
+ }
+ 
+ /* constructor for PreAllocator object */
+ PreAllocator*
+ PreAllocator_Create(PRSize size)
+ {
+     PLArenaPool* arena = NULL;
+diff --git a/security/nss/lib/ckfw/session.c b/security/nss/lib/ckfw/session.c
+--- a/security/nss/lib/ckfw/session.c
++++ b/security/nss/lib/ckfw/session.c
+@@ -1414,19 +1414,18 @@ nssCKFWSession_CopyObject(
+             }
+         }
+ 
+         return rv;
+     } else {
+         /* use create object */
+         NSSArena *tmpArena;
+         CK_ATTRIBUTE_PTR newTemplate;
+-        CK_ULONG i, j, n, newLength, k;
++        CK_ULONG j, n, newLength, k;
+         CK_ATTRIBUTE_TYPE_PTR oldTypes;
+-        NSSCKFWObject *rv;
+ 
+         n = nssCKFWObject_GetAttributeCount(fwObject, pError);
+         if ((0 == n) && (CKR_OK != *pError)) {
+             return (NSSCKFWObject *)NULL;
+         }
+ 
+         tmpArena = NSSArena_Create();
+         if (!tmpArena) {
+diff --git a/security/nss/lib/cryptohi/seckey.c b/security/nss/lib/cryptohi/seckey.c
+--- a/security/nss/lib/cryptohi/seckey.c
++++ b/security/nss/lib/cryptohi/seckey.c
+@@ -634,21 +634,16 @@ seckey_ExtractPublicKey(const CERTSubjec
+ 
+                 rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_DHParamKeyTemplate,
+                                             &newParms);
+ 
+                 if (rv == SECSuccess)
+                     return pubk;
+                 break;
+             case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
+-                /* A basic sanity check on inputs. */
+-                if (spki->algorithm.parameters.len == 0 || newOs.len == 0) {
+-                    PORT_SetError(SEC_ERROR_INPUT_LEN);
+-                    break;
+-                }
+                 pubk->keyType = ecKey;
+                 pubk->u.ec.size = 0;
+ 
+                 /* Since PKCS#11 directly takes the DER encoding of EC params
+                  * and public value, we don't need any decoding here.
+                  */
+                 rv = SECITEM_CopyItem(arena, &pubk->u.ec.DEREncodedParams,
+                                       &spki->algorithm.parameters);
+diff --git a/security/nss/lib/dev/devslot.c b/security/nss/lib/dev/devslot.c
+--- a/security/nss/lib/dev/devslot.c
++++ b/security/nss/lib/dev/devslot.c
+@@ -91,26 +91,20 @@ nssSlot_ResetDelay(
+     NSSSlot *slot)
+ {
+     PZ_Lock(slot->isPresentLock);
+     slot->lastTokenPingState = nssSlotLastPingState_Reset;
+     PZ_Unlock(slot->isPresentLock);
+ }
+ 
+ static PRBool
+-token_status_checked(const NSSSlot *slot)
++within_token_delay_period(const NSSSlot *slot)
+ {
+     PRIntervalTime time;
+     int lastPingState = slot->lastTokenPingState;
+-    /* When called from the same thread, that means
+-     * nssSlot_IsTokenPresent() is called recursively through
+-     * nssSlot_Refresh(). Return immediately in that case. */
+-    if (slot->isPresentThread == PR_GetCurrentThread()) {
+-        return PR_TRUE;
+-    }
+     /* Set the delay time for checking the token presence */
+     if (s_token_delay_time == 0) {
+         s_token_delay_time = PR_SecondsToInterval(NSSSLOT_TOKEN_DELAY_TIME);
+     }
+     time = PR_IntervalNow();
+     if ((lastPingState == nssSlotLastPingState_Valid) && ((time - slot->lastTokenPingTime) < s_token_delay_time)) {
+         return PR_TRUE;
+     }
+@@ -131,46 +125,46 @@ nssSlot_IsTokenPresent(
+ 
+     /* permanent slots are always present unless they're disabled */
+     if (nssSlot_IsPermanent(slot)) {
+         return !PK11_IsDisabled(slot->pk11slot);
+     }
+ 
+     /* avoid repeated calls to check token status within set interval */
+     PZ_Lock(slot->isPresentLock);
+-    if (token_status_checked(slot)) {
++    if (within_token_delay_period(slot)) {
+         CK_FLAGS ckFlags = slot->ckFlags;
+         PZ_Unlock(slot->isPresentLock);
+         return ((ckFlags & CKF_TOKEN_PRESENT) != 0);
+     }
+     PZ_Unlock(slot->isPresentLock);
+ 
+     /* First obtain the slot epv before we set up the condition
+      * variable, so we can just return if we couldn't get it. */
+     epv = slot->epv;
+     if (!epv) {
+         return PR_FALSE;
+     }
+ 
+     /* set up condition so only one thread is active in this part of the code at a time */
+     PZ_Lock(slot->isPresentLock);
+-    while (slot->isPresentThread) {
+-        PR_WaitCondVar(slot->isPresentCondition, PR_INTERVAL_NO_TIMEOUT);
++    while (slot->inIsPresent) {
++        PR_WaitCondVar(slot->isPresentCondition, 0);
+     }
+     /* if we were one of multiple threads here, the first thread will have
+      * given us the answer, no need to make more queries of the token. */
+-    if (token_status_checked(slot)) {
++    if (within_token_delay_period(slot)) {
+         CK_FLAGS ckFlags = slot->ckFlags;
+         PZ_Unlock(slot->isPresentLock);
+         return ((ckFlags & CKF_TOKEN_PRESENT) != 0);
+     }
+     /* this is the winning thread, block all others until we've determined
+      * if the token is present and that it needs initialization. */
+     slot->lastTokenPingState = nssSlotLastPingState_Update;
+-    slot->isPresentThread = PR_GetCurrentThread();
++    slot->inIsPresent = PR_TRUE;
+ 
+     PZ_Unlock(slot->isPresentLock);
+ 
+     nssSlot_EnterMonitor(slot);
+     ckrv = CKAPI(epv)->C_GetSlotInfo(slot->slotID, &slotInfo);
+     nssSlot_ExitMonitor(slot);
+     if (ckrv != CKR_OK) {
+         slot->token->base.name[0] = 0; /* XXX */
+@@ -258,17 +252,17 @@ done:
+      */
+     PZ_Lock(slot->isPresentLock);
+     /* don't update the time if we were reset while we were
+      * getting the token state */
+     if (slot->lastTokenPingState == nssSlotLastPingState_Update) {
+         slot->lastTokenPingTime = PR_IntervalNow();
+         slot->lastTokenPingState = nssSlotLastPingState_Valid;
+     }
+-    slot->isPresentThread = NULL;
++    slot->inIsPresent = PR_FALSE;
+     PR_NotifyAllCondVar(slot->isPresentCondition);
+     PZ_Unlock(slot->isPresentLock);
+     return isPresent;
+ }
+ 
+ NSS_IMPLEMENT void *
+ nssSlot_GetCryptokiEPV(
+     NSSSlot *slot)
+diff --git a/security/nss/lib/dev/devt.h b/security/nss/lib/dev/devt.h
+--- a/security/nss/lib/dev/devt.h
++++ b/security/nss/lib/dev/devt.h
+@@ -87,17 +87,17 @@ struct NSSSlotStr {
+     struct nssSlotAuthInfoStr authInfo;
+     PRIntervalTime lastTokenPingTime;
+     nssSlotLastPingState lastTokenPingState;
+     PZLock *lock;
+     void *epv;
+     PK11SlotInfo *pk11slot;
+     PZLock *isPresentLock;
+     PRCondVar *isPresentCondition;
+-    PRThread *isPresentThread;
++    PRBool inIsPresent;
+ };
+ 
+ struct nssSessionStr {
+     PZLock *lock;
+     CK_SESSION_HANDLE handle;
+     NSSSlot *slot;
+     PRBool isRW;
+     PRBool ownLock;
+diff --git a/security/nss/lib/freebl/Makefile b/security/nss/lib/freebl/Makefile
+--- a/security/nss/lib/freebl/Makefile
++++ b/security/nss/lib/freebl/Makefile
+@@ -512,23 +512,23 @@ ifndef HAVE_INT128_SUPPORT
+     DEFINES += -DKRML_NOUINT128
+ endif
+ 
+ ifndef NSS_DISABLE_CHACHAPOLY
+     ifeq ($(CPU_ARCH),x86_64)
+         ifdef HAVE_INT128_SUPPORT
+             EXTRA_SRCS += Hacl_Poly1305_64.c
+         else
+-            EXTRA_SRCS += poly1305.c
++            EXTRA_SRCS += Hacl_Poly1305_32.c
+         endif
+     else
+         ifeq ($(CPU_ARCH),aarch64)
+             EXTRA_SRCS += Hacl_Poly1305_64.c
+         else
+-            EXTRA_SRCS += poly1305.c
++            EXTRA_SRCS += Hacl_Poly1305_32.c
+         endif
+     endif # x86_64
+ 
+     VERIFIED_SRCS += Hacl_Chacha20.c
+     VERIFIED_SRCS += Hacl_Chacha20_Vec128.c
+ endif # NSS_DISABLE_CHACHAPOLY
+ 
+ ifeq (,$(filter-out i386 x386 x86 x86_64 aarch64,$(CPU_ARCH)))
+diff --git a/security/nss/lib/freebl/chacha20poly1305.c b/security/nss/lib/freebl/chacha20poly1305.c
+--- a/security/nss/lib/freebl/chacha20poly1305.c
++++ b/security/nss/lib/freebl/chacha20poly1305.c
+@@ -19,103 +19,89 @@
+ // Forward declaration from "Hacl_Chacha20_Vec128.h".
+ extern void Hacl_Chacha20_Vec128_chacha20(uint8_t *output, uint8_t *plain,
+                                           uint32_t len, uint8_t *k, uint8_t *n1,
+                                           uint32_t ctr);
+ // Forward declaration from "Hacl_Chacha20.h".
+ extern void Hacl_Chacha20_chacha20(uint8_t *output, uint8_t *plain, uint32_t len,
+                                    uint8_t *k, uint8_t *n1, uint32_t ctr);
+ 
+-/* Poly1305Do writes the Poly1305 authenticator of the given additional data
+- * and ciphertext to |out|. */
+ #if defined(HAVE_INT128_SUPPORT) && (defined(NSS_X86_OR_X64) || defined(__aarch64__))
+ /* Use HACL* Poly1305 on 64-bit Intel and ARM */
+ #include "verified/Hacl_Poly1305_64.h"
++#define NSS_POLY1305_64 1
++#define Hacl_Poly1305_update Hacl_Poly1305_64_update
++#define Hacl_Poly1305_mk_state Hacl_Poly1305_64_mk_state
++#define Hacl_Poly1305_init Hacl_Poly1305_64_init
++#define Hacl_Poly1305_finish Hacl_Poly1305_64_finish
++typedef Hacl_Impl_Poly1305_64_State_poly1305_state Hacl_Impl_Poly1305_State_poly1305_state;
++#else
++/* All other platforms get the 32-bit poly1305 HACL* implementation. */
++#include "verified/Hacl_Poly1305_32.h"
++#define NSS_POLY1305_32 1
++#define Hacl_Poly1305_update Hacl_Poly1305_32_update
++#define Hacl_Poly1305_mk_state Hacl_Poly1305_32_mk_state
++#define Hacl_Poly1305_init Hacl_Poly1305_32_init
++#define Hacl_Poly1305_finish Hacl_Poly1305_32_finish
++typedef Hacl_Impl_Poly1305_32_State_poly1305_state Hacl_Impl_Poly1305_State_poly1305_state;
++#endif /* HAVE_INT128_SUPPORT */
+ 
+ static void
+-Poly1305PadUpdate(Hacl_Impl_Poly1305_64_State_poly1305_state state,
++Poly1305PadUpdate(Hacl_Impl_Poly1305_State_poly1305_state state,
+                   unsigned char *block, const unsigned char *p,
+                   const unsigned int pLen)
+ {
+     unsigned int pRemLen = pLen % 16;
+-    Hacl_Poly1305_64_update(state, (uint8_t *)p, (pLen / 16));
++    Hacl_Poly1305_update(state, (uint8_t *)p, (pLen / 16));
+     if (pRemLen > 0) {
+         memcpy(block, p + (pLen - pRemLen), pRemLen);
+-        Hacl_Poly1305_64_update(state, block, 1);
++        Hacl_Poly1305_update(state, block, 1);
+     }
+ }
+ 
++/* Poly1305Do writes the Poly1305 authenticator of the given additional data
++ * and ciphertext to |out|. */
+ static void
+ Poly1305Do(unsigned char *out, const unsigned char *ad, unsigned int adLen,
+            const unsigned char *ciphertext, unsigned int ciphertextLen,
+            const unsigned char key[32])
+ {
+-    uint64_t tmp1[6U] = { 0U };
+-    Hacl_Impl_Poly1305_64_State_poly1305_state state =
+-        Hacl_Poly1305_64_mk_state(tmp1, tmp1 + 3);
++#ifdef NSS_POLY1305_64
++    uint64_t stateStack[6U] = { 0U };
++    size_t offset = 3;
++#elif defined NSS_POLY1305_32
++    uint32_t stateStack[10U] = { 0U };
++    size_t offset = 5;
++#else
++#error "This can't happen."
++#endif
++    Hacl_Impl_Poly1305_State_poly1305_state state =
++        Hacl_Poly1305_mk_state(stateStack, stateStack + offset);
+ 
+     unsigned char block[16] = { 0 };
+-    Hacl_Poly1305_64_init(state, (uint8_t *)key);
++    Hacl_Poly1305_init(state, (uint8_t *)key);
+ 
+     Poly1305PadUpdate(state, block, ad, adLen);
+     memset(block, 0, 16);
+     Poly1305PadUpdate(state, block, ciphertext, ciphertextLen);
+ 
+     unsigned int i;
+     unsigned int j;
+     for (i = 0, j = adLen; i < 8; i++, j >>= 8) {
+         block[i] = j;
+     }
+     for (i = 8, j = ciphertextLen; i < 16; i++, j >>= 8) {
+         block[i] = j;
+     }
+ 
+-    Hacl_Poly1305_64_update(state, block, 1);
+-    Hacl_Poly1305_64_finish(state, out, (uint8_t *)(key + 16));
++    Hacl_Poly1305_update(state, block, 1);
++    Hacl_Poly1305_finish(state, out, (uint8_t *)(key + 16));
++#undef NSS_POLY1305_64
++#undef NSS_POLY1305_32
+ }
+-#else
+-/* All other platforms get the 32-bit poly1305 reference implementation. */
+-#include "poly1305.h"
+-
+-static void
+-Poly1305Do(unsigned char *out, const unsigned char *ad, unsigned int adLen,
+-           const unsigned char *ciphertext, unsigned int ciphertextLen,
+-           const unsigned char key[32])
+-{
+-    poly1305_state state;
+-    unsigned int j;
+-    unsigned char lengthBytes[8];
+-    static const unsigned char zeros[15];
+-    unsigned int i;
+-
+-    Poly1305Init(&state, key);
+-    Poly1305Update(&state, ad, adLen);
+-    if (adLen % 16 > 0) {
+-        Poly1305Update(&state, zeros, 16 - adLen % 16);
+-    }
+-    Poly1305Update(&state, ciphertext, ciphertextLen);
+-    if (ciphertextLen % 16 > 0) {
+-        Poly1305Update(&state, zeros, 16 - ciphertextLen % 16);
+-    }
+-    j = adLen;
+-    for (i = 0; i < sizeof(lengthBytes); i++) {
+-        lengthBytes[i] = j;
+-        j >>= 8;
+-    }
+-    Poly1305Update(&state, lengthBytes, sizeof(lengthBytes));
+-    j = ciphertextLen;
+-    for (i = 0; i < sizeof(lengthBytes); i++) {
+-        lengthBytes[i] = j;
+-        j >>= 8;
+-    }
+-    Poly1305Update(&state, lengthBytes, sizeof(lengthBytes));
+-    Poly1305Finish(&state, out);
+-}
+-
+-#endif /* HAVE_INT128_SUPPORT */
+ #endif /* NSS_DISABLE_CHACHAPOLY */
+ 
+ SECStatus
+ ChaCha20Poly1305_InitContext(ChaCha20Poly1305Context *ctx,
+                              const unsigned char *key, unsigned int keyLen,
+                              unsigned int tagLen)
+ {
+ #ifdef NSS_DISABLE_CHACHAPOLY
+diff --git a/security/nss/lib/freebl/dh.c b/security/nss/lib/freebl/dh.c
+--- a/security/nss/lib/freebl/dh.c
++++ b/security/nss/lib/freebl/dh.c
+@@ -205,18 +205,17 @@ DH_Derive(SECItem *publicValue,
+           SECItem *derivedSecret,
+           unsigned int outBytes)
+ {
+     mp_int p, Xa, Yb, ZZ, psub1;
+     mp_err err = MP_OKAY;
+     unsigned int len = 0;
+     unsigned int nb;
+     unsigned char *secret = NULL;
+-    if (!publicValue || !publicValue->len || !prime || !prime->len ||
+-        !privateValue || !privateValue->len || !derivedSecret) {
++    if (!publicValue || !prime || !privateValue || !derivedSecret) {
+         PORT_SetError(SEC_ERROR_INVALID_ARGS);
+         return SECFailure;
+     }
+     memset(derivedSecret, 0, sizeof *derivedSecret);
+     MP_DIGITS(&p) = 0;
+     MP_DIGITS(&Xa) = 0;
+     MP_DIGITS(&Yb) = 0;
+     MP_DIGITS(&ZZ) = 0;
+diff --git a/security/nss/lib/freebl/ec.c b/security/nss/lib/freebl/ec.c
+--- a/security/nss/lib/freebl/ec.c
++++ b/security/nss/lib/freebl/ec.c
+@@ -197,18 +197,18 @@ ec_NewKey(ECParams *ecParams, ECPrivateK
+     mp_err err = MP_OKAY;
+     int len;
+ 
+ #if EC_DEBUG
+     printf("ec_NewKey called\n");
+ #endif
+     MP_DIGITS(&k) = 0;
+ 
+-    if (!ecParams || ecParams->name == ECCurve_noName ||
+-        !privKey || !privKeyBytes || privKeyLen <= 0) {
++    if (!ecParams || !privKey || !privKeyBytes || (privKeyLen < 0) ||
++        !ecParams->name) {
+         PORT_SetError(SEC_ERROR_INVALID_ARGS);
+         return SECFailure;
+     }
+ 
+     /* Initialize an arena for the EC key. */
+     if (!(arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE)))
+         return SECFailure;
+ 
+@@ -386,17 +386,17 @@ cleanup:
+  */
+ SECStatus
+ EC_NewKey(ECParams *ecParams, ECPrivateKey **privKey)
+ {
+     SECStatus rv = SECFailure;
+     int len;
+     unsigned char *privKeyBytes = NULL;
+ 
+-    if (!ecParams || ecParams->name == ECCurve_noName || !privKey) {
++    if (!ecParams) {
+         PORT_SetError(SEC_ERROR_INVALID_ARGS);
+         return SECFailure;
+     }
+ 
+     len = ecParams->order.len;
+     privKeyBytes = ec_GenerateRandomPrivateKey(ecParams->order.data, len);
+     if (privKeyBytes == NULL)
+         goto cleanup;
+@@ -425,18 +425,17 @@ SECStatus
+ EC_ValidatePublicKey(ECParams *ecParams, SECItem *publicValue)
+ {
+     mp_int Px, Py;
+     ECGroup *group = NULL;
+     SECStatus rv = SECFailure;
+     mp_err err = MP_OKAY;
+     int len;
+ 
+-    if (!ecParams || ecParams->name == ECCurve_noName ||
+-        !publicValue || !publicValue->len) {
++    if (!ecParams || !publicValue || !ecParams->name) {
+         PORT_SetError(SEC_ERROR_INVALID_ARGS);
+         return SECFailure;
+     }
+ 
+     /* Uses curve specific code for point validation. */
+     if (ecParams->fieldID.type == ec_field_plain) {
+         const ECMethod *method = ec_get_method_from_name(ecParams->name);
+         if (method == NULL || method->validate == NULL) {
+@@ -532,19 +531,18 @@ ECDH_Derive(SECItem *publicValue,
+     SECItem pointQ = { siBuffer, NULL, 0 };
+     mp_int k; /* to hold the private value */
+     mp_int cofactor;
+     mp_err err = MP_OKAY;
+ #if EC_DEBUG
+     int i;
+ #endif
+ 
+-    if (!publicValue || !publicValue->len ||
+-        !ecParams || ecParams->name == ECCurve_noName ||
+-        !privateValue || !privateValue->len || !derivedSecret) {
++    if (!publicValue || !ecParams || !privateValue || !derivedSecret ||
++        !ecParams->name) {
+         PORT_SetError(SEC_ERROR_INVALID_ARGS);
+         return SECFailure;
+     }
+ 
+     /*
+      * Make sure the point is on the requested curve to avoid
+      * certain small subgroup attacks.
+      */
+diff --git a/security/nss/lib/freebl/ecl/ecp_25519.c b/security/nss/lib/freebl/ecl/ecp_25519.c
+--- a/security/nss/lib/freebl/ecl/ecp_25519.c
++++ b/security/nss/lib/freebl/ecl/ecp_25519.c
+@@ -109,18 +109,15 @@ ec_Curve25519_pt_mul(SECItem *X, SECItem
+         px = basePoint;
+     } else {
+         PORT_Assert(P->len == 32);
+         if (P->len != 32) {
+             return SECFailure;
+         }
+         px = P->data;
+     }
+-    if (k->len != 32) {
+-        return SECFailure;
+-    }
+ 
+     SECStatus rv = ec_Curve25519_mul(X->data, k->data, px);
+     if (NSS_SecureMemcmpZero(X->data, X->len) == 0) {
+         return SECFailure;
+     }
+     return rv;
+ }
+diff --git a/security/nss/lib/freebl/freebl.gyp b/security/nss/lib/freebl/freebl.gyp
+--- a/security/nss/lib/freebl/freebl.gyp
++++ b/security/nss/lib/freebl/freebl.gyp
+@@ -267,19 +267,24 @@
+               'NSS_USE_COMBA',
+               'USE_HW_AES',
+               'INTEL_GCM',
+             ],
+           },
+         },
+       }],
+       [ 'cc_use_gnu_ld==1 and OS=="win" and target_arch=="x64"', {
+-        # mingw x64
+         'defines': [
+           'MP_IS_LITTLE_ENDIAN',
++          'NSS_BEVAND_ARCFOUR',
++          'MPI_AMD64',
++          'MP_ASSEMBLY_MULTIPLY',
++          'NSS_USE_COMBA',
++          'USE_HW_AES',
++          'INTEL_GCM',
+          ],
+       }],
+       [ 'OS!="win"', {
+         'conditions': [
+           [ 'target_arch=="x64" or target_arch=="arm64" or target_arch=="aarch64"', {
+             'defines': [
+               # The Makefile does version-tests on GCC, but we're not doing that here.
+               'HAVE_INT128_SUPPORT',
+diff --git a/security/nss/lib/freebl/freebl_base.gypi b/security/nss/lib/freebl/freebl_base.gypi
+--- a/security/nss/lib/freebl/freebl_base.gypi
++++ b/security/nss/lib/freebl/freebl_base.gypi
+@@ -54,17 +54,18 @@
+     'rijndael.c',
+     'rsa.c',
+     'rsapkcs.c',
+     'seed.c',
+     'sha512.c',
+     'sha_fast.c',
+     'shvfy.c',
+     'sysrand.c',
+-    'tlsprfalg.c'
++    'tlsprfalg.c',
++    'verified/FStar.c',
+   ],
+   'conditions': [
+     [ 'OS=="linux" or OS=="android"', {
+       'conditions': [
+         [ 'target_arch=="x64"', {
+           'sources': [
+             'arcfour-amd64-gas.s',
+             'intel-aes.s',
+@@ -117,35 +118,29 @@
+ 	      [ 'cc_use_gnu_ld!=1 and target_arch!="x64"', {
+           # not x64
+           'sources': [
+             'mpi/mpi_x86_asm.c',
+             'intel-aes-x86-masm.asm',
+             'intel-gcm-x86-masm.asm',
+           ],
+         }],
+-        [ 'cc_use_gnu_ld==1', {
+-          # mingw
+-          'sources': [
+-          ],
+-        }],
+         [ 'cc_is_clang!=1', {
+           # MSVC
+           'sources': [
+             'intel-gcm-wrap.c',
+           ],
+         }],
+       ],
+     }],
+     ['target_arch=="ia32" or target_arch=="x64" or target_arch=="arm64" or target_arch=="aarch64"', {
+       'sources': [
+         # All intel and 64-bit ARM architectures get the 64 bit version.
+         'ecl/curve25519_64.c',
+         'verified/Hacl_Curve25519.c',
+-        'verified/FStar.c',
+       ],
+     }, {
+       'sources': [
+         # All other architectures get the generic 32 bit implementation (slow!)
+         'ecl/curve25519_32.c',
+       ],
+     }],
+     [ 'disable_chachapoly==0', {
+@@ -167,26 +162,26 @@
+               'conditions': [
+                 [ 'target_arch=="arm64" or target_arch=="aarch64"', {
+                   'sources': [
+                     'verified/Hacl_Poly1305_64.c',
+                   ],
+                 }, {
+                   # !Windows & !x64 & !arm64 & !aarch64
+                   'sources': [
+-                    'poly1305.c',
++                    'verified/Hacl_Poly1305_32.c',
+                   ],
+                 }],
+               ],
+             }],
+           ],
+         }, {
+           # Windows
+           'sources': [
+-            'poly1305.c',
++            'verified/Hacl_Poly1305_32.c',
+           ],
+         }],
+       ],
+     }],
+     [ 'fuzz==1', {
+       'sources!': [ 'drbg.c' ],
+       'sources': [ 'det_rng.c' ],
+     }],
+diff --git a/security/nss/lib/freebl/loader.c b/security/nss/lib/freebl/loader.c
+--- a/security/nss/lib/freebl/loader.c
++++ b/security/nss/lib/freebl/loader.c
+@@ -2159,22 +2159,22 @@ BLAKE2B_NewContext(void)
+ {
+     if (!vector && PR_SUCCESS != freebl_RunLoaderOnce()) {
+         return NULL;
+     }
+     return (vector->p_BLAKE2B_NewContext)();
+ }
+ 
+ void
+-BLAKE2B_DestroyContext(BLAKE2BContext *BLAKE2BContext, PRBool freeit)
++BLAKE2B_DestroyContext(BLAKE2BContext *ctx, PRBool freeit)
+ {
+     if (!vector && PR_SUCCESS != freebl_RunLoaderOnce()) {
+         return;
+     }
+-    (vector->p_BLAKE2B_DestroyContext)(BLAKE2BContext, freeit);
++    (vector->p_BLAKE2B_DestroyContext)(ctx, freeit);
+ }
+ 
+ SECStatus
+ BLAKE2B_Begin(BLAKE2BContext *ctx)
+ {
+     if (!vector && PR_SUCCESS != freebl_RunLoaderOnce()) {
+         return SECFailure;
+     }
+diff --git a/security/nss/lib/freebl/mpi/mpi.c b/security/nss/lib/freebl/mpi/mpi.c
+--- a/security/nss/lib/freebl/mpi/mpi.c
++++ b/security/nss/lib/freebl/mpi/mpi.c
+@@ -2058,20 +2058,17 @@ s_mp_almost_inverse(const mp_int *a, con
+                 MP_CHECKOK(mp_sub(&f, &g, &f)); /* f = f - g */
+                 MP_CHECKOK(mp_sub(c, &d, c));   /* c = c - d */
+             } else {
+                 MP_CHECKOK(mp_add(&f, &g, &f)); /* f = f + g */
+                 MP_CHECKOK(mp_add(c, &d, c));   /* c = c + d */
+             }
+         }
+     if (res >= 0) {
+-        if (mp_cmp_mag(c, p) >= 0) {
+-            MP_CHECKOK(mp_div(c, p, NULL, c));
+-        }
+-        if (MP_SIGN(c) != MP_ZPOS) {
++        while (MP_SIGN(c) != MP_ZPOS) {
+             MP_CHECKOK(mp_add(c, p, c));
+         }
+         res = k;
+     }
+ 
+ CLEANUP:
+     mp_clear(&d);
+     mp_clear(&f);
+@@ -2655,20 +2652,20 @@ mp_toradix(mp_int *mp, char *str, int ra
+             str[pos++] = '-';
+ 
+         /* Add trailing NUL to end the string        */
+         str[pos--] = '\0';
+ 
+         /* Reverse the digits and sign indicator     */
+         ix = 0;
+         while (ix < pos) {
+-            char tmp = str[ix];
++            char tmpc = str[ix];
+ 
+             str[ix] = str[pos];
+-            str[pos] = tmp;
++            str[pos] = tmpc;
+             ++ix;
+             --pos;
+         }
+ 
+         mp_clear(&tmp);
+     }
+ 
+     return MP_OKAY;
+@@ -3311,23 +3308,24 @@ s_mp_div_d(mp_int *mp, mp_digit d, mp_di
+     if (d == 1) {
+         if (r)
+             *r = 0;
+         return MP_OKAY;
+     }
+     /* could check for power of 2 here, but mp_div_d does that. */
+     if (MP_USED(mp) == 1) {
+         mp_digit n = MP_DIGIT(mp, 0);
+-        mp_digit rem;
++        mp_digit remdig;
+ 
+         q = n / d;
+-        rem = n % d;
++        remdig = n % d;
+         MP_DIGIT(mp, 0) = q;
+-        if (r)
+-            *r = rem;
++        if (r) {
++            *r = remdig;
++        }
+         return MP_OKAY;
+     }
+ 
+     MP_DIGITS(&rem) = 0;
+     MP_DIGITS(&quot) = 0;
+     /* Make room for the quotient */
+     MP_CHECKOK(mp_init_size(&quot, USED(mp)));
+ 
+@@ -4772,69 +4770,46 @@ mp_to_signed_octets(const mp_int *mp, un
+     }
+     if (!pos)
+         str[pos++] = 0;
+     return pos;
+ } /* end mp_to_signed_octets() */
+ /* }}} */
+ 
+ /* {{{ mp_to_fixlen_octets(mp, str) */
+-/* output a buffer of big endian octets exactly as long as requested.
+-   constant time on the value of mp. */
++/* output a buffer of big endian octets exactly as long as requested. */
+ mp_err
+ mp_to_fixlen_octets(const mp_int *mp, unsigned char *str, mp_size length)
+ {
+-    int ix, jx;
++    int ix, pos = 0;
+     unsigned int bytes;
+ 
+-    ARGCHK(mp != NULL, MP_BADARG);
+-    ARGCHK(str != NULL, MP_BADARG);
+-    ARGCHK(!SIGN(mp), MP_BADARG);
+-    ARGCHK(length > 0, MP_BADARG);
+-
+-    /* Constant time on the value of mp.  Don't use mp_unsigned_octet_size. */
+-    bytes = USED(mp) * MP_DIGIT_SIZE;
+-
+-    /* If the output is shorter than the native size of mp, then check that any
+-     * bytes not written have zero values.  This check isn't constant time on
+-     * the assumption that timing-sensitive callers can guarantee that mp fits
+-     * in the allocated space. */
+-    ix = USED(mp) - 1;
+-    if (bytes > length) {
+-        unsigned int zeros = bytes - length;
+-
+-        while (zeros >= MP_DIGIT_SIZE) {
+-            ARGCHK(DIGIT(mp, ix) == 0, MP_BADARG);
+-            zeros -= MP_DIGIT_SIZE;
+-            ix--;
+-        }
+-
+-        if (zeros > 0) {
+-            mp_digit d = DIGIT(mp, ix);
+-            mp_digit m = ~0ULL << ((MP_DIGIT_SIZE - zeros) * CHAR_BIT);
+-            ARGCHK((d & m) == 0, MP_BADARG);
+-            for (jx = MP_DIGIT_SIZE - zeros - 1; jx >= 0; jx--) {
+-                *str++ = d >> (jx * CHAR_BIT);
+-            }
+-            ix--;
+-        }
+-    } else if (bytes < length) {
+-        /* Place any needed leading zeros. */
+-        unsigned int zeros = length - bytes;
+-        memset(str, 0, zeros);
+-        str += zeros;
++    ARGCHK(mp != NULL && str != NULL && !SIGN(mp), MP_BADARG);
++
++    bytes = mp_unsigned_octet_size(mp);
++    ARGCHK(bytes <= length, MP_BADARG);
++
++    /* place any needed leading zeros */
++    for (; length > bytes; --length) {
++        *str++ = 0;
+     }
+ 
+-    /* Iterate over each whole digit... */
+-    for (; ix >= 0; ix--) {
++    /* Iterate over each digit... */
++    for (ix = USED(mp) - 1; ix >= 0; ix--) {
+         mp_digit d = DIGIT(mp, ix);
++        int jx;
+ 
+         /* Unpack digit bytes, high order first */
+-        for (jx = MP_DIGIT_SIZE - 1; jx >= 0; jx--) {
+-            *str++ = d >> (jx * CHAR_BIT);
++        for (jx = sizeof(mp_digit) - 1; jx >= 0; jx--) {
++            unsigned char x = (unsigned char)(d >> (jx * CHAR_BIT));
++            if (!pos && !x) /* suppress leading zeros */
++                continue;
++            str[pos++] = x;
+         }
+     }
++    if (!pos)
++        str[pos++] = 0;
+     return MP_OKAY;
+ } /* end mp_to_fixlen_octets() */
+ /* }}} */
+ 
+ /*------------------------------------------------------------------------*/
+ /* HERE THERE BE DRAGONS                                                  */
+diff --git a/security/nss/lib/freebl/mpi/mpi.h b/security/nss/lib/freebl/mpi/mpi.h
+--- a/security/nss/lib/freebl/mpi/mpi.h
++++ b/security/nss/lib/freebl/mpi/mpi.h
+@@ -123,18 +123,17 @@ typedef long long mp_sword;
+ #endif /* !defined(MP_NO_MP_WORD) */
+ 
+ #if !defined(MP_WORD_MAX) && defined(MP_DEFINE_SMALL_WORD)
+ typedef unsigned int mp_word;
+ typedef int mp_sword;
+ #define MP_WORD_MAX UINT_MAX
+ #endif
+ 
+-#define MP_DIGIT_SIZE sizeof(mp_digit)
+-#define MP_DIGIT_BIT (CHAR_BIT * MP_DIGIT_SIZE)
++#define MP_DIGIT_BIT (CHAR_BIT * sizeof(mp_digit))
+ #define MP_WORD_BIT (CHAR_BIT * sizeof(mp_word))
+ #define MP_RADIX (1 + (mp_word)MP_DIGIT_MAX)
+ 
+ #define MP_HALF_DIGIT_BIT (MP_DIGIT_BIT / 2)
+ #define MP_HALF_RADIX (1 + (mp_digit)MP_HALF_DIGIT_MAX)
+ /* MP_HALF_RADIX really ought to be called MP_SQRT_RADIX, but it's named
+ ** MP_HALF_RADIX because it's the radix for MP_HALF_DIGITs, and it's
+ ** consistent with the other _HALF_ names.
+diff --git a/security/nss/lib/freebl/poly1305-donna-x64-sse2-incremental-source.c b/security/nss/lib/freebl/poly1305-donna-x64-sse2-incremental-source.c
+deleted file mode 100644
+--- a/security/nss/lib/freebl/poly1305-donna-x64-sse2-incremental-source.c
++++ /dev/null
+@@ -1,881 +0,0 @@
+-/* This Source Code Form is subject to the terms of the Mozilla Public
+- * 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/. */
+-
+-/* This implementation of poly1305 is by Andrew Moon
+- * (https://github.com/floodyberry/poly1305-donna) and released as public
+- * domain. It implements SIMD vectorization based on the algorithm described in
+- * http://cr.yp.to/papers.html#neoncrypto. Unrolled to 2 powers, i.e. 64 byte
+- * block size. */
+-
+-#include <emmintrin.h>
+-#include <stdint.h>
+-
+-#include "poly1305.h"
+-#include "blapii.h"
+-
+-#define ALIGN(x) __attribute__((aligned(x)))
+-#define INLINE inline
+-#define U8TO64_LE(m) (*(uint64_t *)(m))
+-#define U8TO32_LE(m) (*(uint32_t *)(m))
+-#define U64TO8_LE(m, v) (*(uint64_t *)(m)) = v
+-
+-typedef __m128i xmmi;
+-typedef unsigned __int128 uint128_t;
+-
+-static const uint32_t ALIGN(16) poly1305_x64_sse2_message_mask[4] = { (1 << 26) - 1, 0, (1 << 26) - 1, 0 };
+-static const uint32_t ALIGN(16) poly1305_x64_sse2_5[4] = { 5, 0, 5, 0 };
+-static const uint32_t ALIGN(16) poly1305_x64_sse2_1shl128[4] = { (1 << 24), 0, (1 << 24), 0 };
+-
+-static uint128_t INLINE
+-add128(uint128_t a, uint128_t b)
+-{
+-    return a + b;
+-}
+-
+-static uint128_t INLINE
+-add128_64(uint128_t a, uint64_t b)
+-{
+-    return a + b;
+-}
+-
+-static uint128_t INLINE
+-mul64x64_128(uint64_t a, uint64_t b)
+-{
+-    return (uint128_t)a * b;
+-}
+-
+-static uint64_t INLINE
+-lo128(uint128_t a)
+-{
+-    return (uint64_t)a;
+-}
+-
+-static uint64_t INLINE
+-shr128(uint128_t v, const int shift)
+-{
+-    return (uint64_t)(v >> shift);
+-}
+-
+-static uint64_t INLINE
+-shr128_pair(uint64_t hi, uint64_t lo, const int shift)
+-{
+-    return (uint64_t)((((uint128_t)hi << 64) | lo) >> shift);
+-}
+-
+-typedef struct poly1305_power_t {
+-    union {
+-        xmmi v;
+-        uint64_t u[2];
+-        uint32_t d[4];
+-    } R20, R21, R22, R23, R24, S21, S22, S23, S24;
+-} poly1305_power;
+-
+-typedef struct poly1305_state_internal_t {
+-    poly1305_power P[2]; /* 288 bytes, top 32 bit halves unused = 144 bytes of free storage */
+-    union {
+-        xmmi H[5]; /*  80 bytes  */
+-        uint64_t HH[10];
+-    };
+-    /* uint64_t r0,r1,r2;       [24 bytes] */
+-    /* uint64_t pad0,pad1;      [16 bytes] */
+-    uint64_t started;      /*   8 bytes  */
+-    uint64_t leftover;     /*   8 bytes  */
+-    uint8_t buffer[64];    /*  64 bytes  */
+-} poly1305_state_internal; /* 448 bytes total + 63 bytes for alignment = 511 bytes raw */
+-
+-static poly1305_state_internal INLINE
+-    *
+-    poly1305_aligned_state(poly1305_state *state)
+-{
+-    return (poly1305_state_internal *)(((uint64_t)state + 63) & ~63);
+-}
+-
+-/* copy 0-63 bytes */
+-static void INLINE NO_SANITIZE_ALIGNMENT
+-poly1305_block_copy(uint8_t *dst, const uint8_t *src, size_t bytes)
+-{
+-    size_t offset = src - dst;
+-    if (bytes & 32) {
+-        _mm_storeu_si128((xmmi *)(dst + 0), _mm_loadu_si128((xmmi *)(dst + offset + 0)));
+-        _mm_storeu_si128((xmmi *)(dst + 16), _mm_loadu_si128((xmmi *)(dst + offset + 16)));
+-        dst += 32;
+-    }
+-    if (bytes & 16) {
+-        _mm_storeu_si128((xmmi *)dst, _mm_loadu_si128((xmmi *)(dst + offset)));
+-        dst += 16;
+-    }
+-    if (bytes & 8) {
+-        *(uint64_t *)dst = *(uint64_t *)(dst + offset);
+-        dst += 8;
+-    }
+-    if (bytes & 4) {
+-        *(uint32_t *)dst = *(uint32_t *)(dst + offset);
+-        dst += 4;
+-    }
+-    if (bytes & 2) {
+-        *(uint16_t *)dst = *(uint16_t *)(dst + offset);
+-        dst += 2;
+-    }
+-    if (bytes & 1) {
+-        *(uint8_t *)dst = *(uint8_t *)(dst + offset);
+-    }
+-}
+-
+-/* zero 0-15 bytes */
+-static void INLINE
+-poly1305_block_zero(uint8_t *dst, size_t bytes)
+-{
+-    if (bytes & 8) {
+-        *(uint64_t *)dst = 0;
+-        dst += 8;
+-    }
+-    if (bytes & 4) {
+-        *(uint32_t *)dst = 0;
+-        dst += 4;
+-    }
+-    if (bytes & 2) {
+-        *(uint16_t *)dst = 0;
+-        dst += 2;
+-    }
+-    if (bytes & 1) {
+-        *(uint8_t *)dst = 0;
+-    }
+-}
+-
+-static size_t INLINE
+-poly1305_min(size_t a, size_t b)
+-{
+-    return (a < b) ? a : b;
+-}
+-
+-void
+-Poly1305Init(poly1305_state *state, const unsigned char key[32])
+-{
+-    poly1305_state_internal *st = poly1305_aligned_state(state);
+-    poly1305_power *p;
+-    uint64_t r0, r1, r2;
+-    uint64_t t0, t1;
+-
+-    /* clamp key */
+-    t0 = U8TO64_LE(key + 0);
+-    t1 = U8TO64_LE(key + 8);
+-    r0 = t0 & 0xffc0fffffff;
+-    t0 >>= 44;
+-    t0 |= t1 << 20;
+-    r1 = t0 & 0xfffffc0ffff;
+-    t1 >>= 24;
+-    r2 = t1 & 0x00ffffffc0f;
+-
+-    /* store r in un-used space of st->P[1] */
+-    p = &st->P[1];
+-    p->R20.d[1] = (uint32_t)(r0);
+-    p->R20.d[3] = (uint32_t)(r0 >> 32);
+-    p->R21.d[1] = (uint32_t)(r1);
+-    p->R21.d[3] = (uint32_t)(r1 >> 32);
+-    p->R22.d[1] = (uint32_t)(r2);
+-    p->R22.d[3] = (uint32_t)(r2 >> 32);
+-
+-    /* store pad */
+-    p->R23.d[1] = U8TO32_LE(key + 16);
+-    p->R23.d[3] = U8TO32_LE(key + 20);
+-    p->R24.d[1] = U8TO32_LE(key + 24);
+-    p->R24.d[3] = U8TO32_LE(key + 28);
+-
+-    /* H = 0 */
+-    st->H[0] = _mm_setzero_si128();
+-    st->H[1] = _mm_setzero_si128();
+-    st->H[2] = _mm_setzero_si128();
+-    st->H[3] = _mm_setzero_si128();
+-    st->H[4] = _mm_setzero_si128();
+-
+-    st->started = 0;
+-    st->leftover = 0;
+-}
+-
+-static void
+-poly1305_first_block(poly1305_state_internal *st, const uint8_t *m)
+-{
+-    const xmmi MMASK = _mm_load_si128((xmmi *)poly1305_x64_sse2_message_mask);
+-    const xmmi FIVE = _mm_load_si128((xmmi *)poly1305_x64_sse2_5);
+-    const xmmi HIBIT = _mm_load_si128((xmmi *)poly1305_x64_sse2_1shl128);
+-    xmmi T5, T6;
+-    poly1305_power *p;
+-    uint128_t d[3];
+-    uint64_t r0, r1, r2;
+-    uint64_t r20, r21, r22, s22;
+-    uint64_t pad0, pad1;
+-    uint64_t c;
+-    uint64_t i;
+-
+-    /* pull out stored info */
+-    p = &st->P[1];
+-
+-    r0 = ((uint64_t)p->R20.d[3] << 32) | (uint64_t)p->R20.d[1];
+-    r1 = ((uint64_t)p->R21.d[3] << 32) | (uint64_t)p->R21.d[1];
+-    r2 = ((uint64_t)p->R22.d[3] << 32) | (uint64_t)p->R22.d[1];
+-    pad0 = ((uint64_t)p->R23.d[3] << 32) | (uint64_t)p->R23.d[1];
+-    pad1 = ((uint64_t)p->R24.d[3] << 32) | (uint64_t)p->R24.d[1];
+-
+-    /* compute powers r^2,r^4 */
+-    r20 = r0;
+-    r21 = r1;
+-    r22 = r2;
+-    for (i = 0; i < 2; i++) {
+-        s22 = r22 * (5 << 2);
+-
+-        d[0] = add128(mul64x64_128(r20, r20), mul64x64_128(r21 * 2, s22));
+-        d[1] = add128(mul64x64_128(r22, s22), mul64x64_128(r20 * 2, r21));
+-        d[2] = add128(mul64x64_128(r21, r21), mul64x64_128(r22 * 2, r20));
+-
+-        r20 = lo128(d[0]) & 0xfffffffffff;
+-        c = shr128(d[0], 44);
+-        d[1] = add128_64(d[1], c);
+-        r21 = lo128(d[1]) & 0xfffffffffff;
+-        c = shr128(d[1], 44);
+-        d[2] = add128_64(d[2], c);
+-        r22 = lo128(d[2]) & 0x3ffffffffff;
+-        c = shr128(d[2], 42);
+-        r20 += c * 5;
+-        c = (r20 >> 44);
+-        r20 = r20 & 0xfffffffffff;
+-        r21 += c;
+-
+-        p->R20.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)(r20)&0x3ffffff), _MM_SHUFFLE(1, 0, 1, 0));
+-        p->R21.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r20 >> 26) | (r21 << 18)) & 0x3ffffff), _MM_SHUFFLE(1, 0, 1, 0));
+-        p->R22.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r21 >> 8)) & 0x3ffffff), _MM_SHUFFLE(1, 0, 1, 0));
+-        p->R23.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r21 >> 34) | (r22 << 10)) & 0x3ffffff), _MM_SHUFFLE(1, 0, 1, 0));
+-        p->R24.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r22 >> 16))), _MM_SHUFFLE(1, 0, 1, 0));
+-        p->S21.v = _mm_mul_epu32(p->R21.v, FIVE);
+-        p->S22.v = _mm_mul_epu32(p->R22.v, FIVE);
+-        p->S23.v = _mm_mul_epu32(p->R23.v, FIVE);
+-        p->S24.v = _mm_mul_epu32(p->R24.v, FIVE);
+-        p--;
+-    }
+-
+-    /* put saved info back */
+-    p = &st->P[1];
+-    p->R20.d[1] = (uint32_t)(r0);
+-    p->R20.d[3] = (uint32_t)(r0 >> 32);
+-    p->R21.d[1] = (uint32_t)(r1);
+-    p->R21.d[3] = (uint32_t)(r1 >> 32);
+-    p->R22.d[1] = (uint32_t)(r2);
+-    p->R22.d[3] = (uint32_t)(r2 >> 32);
+-    p->R23.d[1] = (uint32_t)(pad0);
+-    p->R23.d[3] = (uint32_t)(pad0 >> 32);
+-    p->R24.d[1] = (uint32_t)(pad1);
+-    p->R24.d[3] = (uint32_t)(pad1 >> 32);
+-
+-    /* H = [Mx,My] */
+-    T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 0)), _mm_loadl_epi64((xmmi *)(m + 16)));
+-    T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 8)), _mm_loadl_epi64((xmmi *)(m + 24)));
+-    st->H[0] = _mm_and_si128(MMASK, T5);
+-    st->H[1] = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+-    T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+-    st->H[2] = _mm_and_si128(MMASK, T5);
+-    st->H[3] = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+-    st->H[4] = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+-}
+-
+-static void
+-poly1305_blocks(poly1305_state_internal *st, const uint8_t *m, size_t bytes)
+-{
+-    const xmmi MMASK = _mm_load_si128((xmmi *)poly1305_x64_sse2_message_mask);
+-    const xmmi FIVE = _mm_load_si128((xmmi *)poly1305_x64_sse2_5);
+-    const xmmi HIBIT = _mm_load_si128((xmmi *)poly1305_x64_sse2_1shl128);
+-
+-    poly1305_power *p;
+-    xmmi H0, H1, H2, H3, H4;
+-    xmmi T0, T1, T2, T3, T4, T5, T6;
+-    xmmi M0, M1, M2, M3, M4;
+-    xmmi C1, C2;
+-
+-    H0 = st->H[0];
+-    H1 = st->H[1];
+-    H2 = st->H[2];
+-    H3 = st->H[3];
+-    H4 = st->H[4];
+-
+-    while (bytes >= 64) {
+-        /* H *= [r^4,r^4] */
+-        p = &st->P[0];
+-        T0 = _mm_mul_epu32(H0, p->R20.v);
+-        T1 = _mm_mul_epu32(H0, p->R21.v);
+-        T2 = _mm_mul_epu32(H0, p->R22.v);
+-        T3 = _mm_mul_epu32(H0, p->R23.v);
+-        T4 = _mm_mul_epu32(H0, p->R24.v);
+-        T5 = _mm_mul_epu32(H1, p->S24.v);
+-        T6 = _mm_mul_epu32(H1, p->R20.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(H2, p->S23.v);
+-        T6 = _mm_mul_epu32(H2, p->S24.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(H3, p->S22.v);
+-        T6 = _mm_mul_epu32(H3, p->S23.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(H4, p->S21.v);
+-        T6 = _mm_mul_epu32(H4, p->S22.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(H1, p->R21.v);
+-        T6 = _mm_mul_epu32(H1, p->R22.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(H2, p->R20.v);
+-        T6 = _mm_mul_epu32(H2, p->R21.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(H3, p->S24.v);
+-        T6 = _mm_mul_epu32(H3, p->R20.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(H4, p->S23.v);
+-        T6 = _mm_mul_epu32(H4, p->S24.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(H1, p->R23.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-        T5 = _mm_mul_epu32(H2, p->R22.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-        T5 = _mm_mul_epu32(H3, p->R21.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-        T5 = _mm_mul_epu32(H4, p->R20.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-
+-        /* H += [Mx,My]*[r^2,r^2] */
+-        T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 0)), _mm_loadl_epi64((xmmi *)(m + 16)));
+-        T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 8)), _mm_loadl_epi64((xmmi *)(m + 24)));
+-        M0 = _mm_and_si128(MMASK, T5);
+-        M1 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+-        T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+-        M2 = _mm_and_si128(MMASK, T5);
+-        M3 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+-        M4 = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+-
+-        p = &st->P[1];
+-        T5 = _mm_mul_epu32(M0, p->R20.v);
+-        T6 = _mm_mul_epu32(M0, p->R21.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(M1, p->S24.v);
+-        T6 = _mm_mul_epu32(M1, p->R20.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(M2, p->S23.v);
+-        T6 = _mm_mul_epu32(M2, p->S24.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(M3, p->S22.v);
+-        T6 = _mm_mul_epu32(M3, p->S23.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(M4, p->S21.v);
+-        T6 = _mm_mul_epu32(M4, p->S22.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(M0, p->R22.v);
+-        T6 = _mm_mul_epu32(M0, p->R23.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(M1, p->R21.v);
+-        T6 = _mm_mul_epu32(M1, p->R22.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(M2, p->R20.v);
+-        T6 = _mm_mul_epu32(M2, p->R21.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(M3, p->S24.v);
+-        T6 = _mm_mul_epu32(M3, p->R20.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(M4, p->S23.v);
+-        T6 = _mm_mul_epu32(M4, p->S24.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(M0, p->R24.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-        T5 = _mm_mul_epu32(M1, p->R23.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-        T5 = _mm_mul_epu32(M2, p->R22.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-        T5 = _mm_mul_epu32(M3, p->R21.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-        T5 = _mm_mul_epu32(M4, p->R20.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-
+-        /* H += [Mx,My] */
+-        T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 32)), _mm_loadl_epi64((xmmi *)(m + 48)));
+-        T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 40)), _mm_loadl_epi64((xmmi *)(m + 56)));
+-        M0 = _mm_and_si128(MMASK, T5);
+-        M1 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+-        T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+-        M2 = _mm_and_si128(MMASK, T5);
+-        M3 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+-        M4 = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+-
+-        T0 = _mm_add_epi64(T0, M0);
+-        T1 = _mm_add_epi64(T1, M1);
+-        T2 = _mm_add_epi64(T2, M2);
+-        T3 = _mm_add_epi64(T3, M3);
+-        T4 = _mm_add_epi64(T4, M4);
+-
+-        /* reduce */
+-        C1 = _mm_srli_epi64(T0, 26);
+-        C2 = _mm_srli_epi64(T3, 26);
+-        T0 = _mm_and_si128(T0, MMASK);
+-        T3 = _mm_and_si128(T3, MMASK);
+-        T1 = _mm_add_epi64(T1, C1);
+-        T4 = _mm_add_epi64(T4, C2);
+-        C1 = _mm_srli_epi64(T1, 26);
+-        C2 = _mm_srli_epi64(T4, 26);
+-        T1 = _mm_and_si128(T1, MMASK);
+-        T4 = _mm_and_si128(T4, MMASK);
+-        T2 = _mm_add_epi64(T2, C1);
+-        T0 = _mm_add_epi64(T0, _mm_mul_epu32(C2, FIVE));
+-        C1 = _mm_srli_epi64(T2, 26);
+-        C2 = _mm_srli_epi64(T0, 26);
+-        T2 = _mm_and_si128(T2, MMASK);
+-        T0 = _mm_and_si128(T0, MMASK);
+-        T3 = _mm_add_epi64(T3, C1);
+-        T1 = _mm_add_epi64(T1, C2);
+-        C1 = _mm_srli_epi64(T3, 26);
+-        T3 = _mm_and_si128(T3, MMASK);
+-        T4 = _mm_add_epi64(T4, C1);
+-
+-        /* H = (H*[r^4,r^4] + [Mx,My]*[r^2,r^2] + [Mx,My]) */
+-        H0 = T0;
+-        H1 = T1;
+-        H2 = T2;
+-        H3 = T3;
+-        H4 = T4;
+-
+-        m += 64;
+-        bytes -= 64;
+-    }
+-
+-    st->H[0] = H0;
+-    st->H[1] = H1;
+-    st->H[2] = H2;
+-    st->H[3] = H3;
+-    st->H[4] = H4;
+-}
+-
+-static size_t
+-poly1305_combine(poly1305_state_internal *st, const uint8_t *m, size_t bytes)
+-{
+-    const xmmi MMASK = _mm_load_si128((xmmi *)poly1305_x64_sse2_message_mask);
+-    const xmmi HIBIT = _mm_load_si128((xmmi *)poly1305_x64_sse2_1shl128);
+-    const xmmi FIVE = _mm_load_si128((xmmi *)poly1305_x64_sse2_5);
+-
+-    poly1305_power *p;
+-    xmmi H0, H1, H2, H3, H4;
+-    xmmi M0, M1, M2, M3, M4;
+-    xmmi T0, T1, T2, T3, T4, T5, T6;
+-    xmmi C1, C2;
+-
+-    uint64_t r0, r1, r2;
+-    uint64_t t0, t1, t2, t3, t4;
+-    uint64_t c;
+-    size_t consumed = 0;
+-
+-    H0 = st->H[0];
+-    H1 = st->H[1];
+-    H2 = st->H[2];
+-    H3 = st->H[3];
+-    H4 = st->H[4];
+-
+-    /* p = [r^2,r^2] */
+-    p = &st->P[1];
+-
+-    if (bytes >= 32) {
+-        /* H *= [r^2,r^2] */
+-        T0 = _mm_mul_epu32(H0, p->R20.v);
+-        T1 = _mm_mul_epu32(H0, p->R21.v);
+-        T2 = _mm_mul_epu32(H0, p->R22.v);
+-        T3 = _mm_mul_epu32(H0, p->R23.v);
+-        T4 = _mm_mul_epu32(H0, p->R24.v);
+-        T5 = _mm_mul_epu32(H1, p->S24.v);
+-        T6 = _mm_mul_epu32(H1, p->R20.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(H2, p->S23.v);
+-        T6 = _mm_mul_epu32(H2, p->S24.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(H3, p->S22.v);
+-        T6 = _mm_mul_epu32(H3, p->S23.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(H4, p->S21.v);
+-        T6 = _mm_mul_epu32(H4, p->S22.v);
+-        T0 = _mm_add_epi64(T0, T5);
+-        T1 = _mm_add_epi64(T1, T6);
+-        T5 = _mm_mul_epu32(H1, p->R21.v);
+-        T6 = _mm_mul_epu32(H1, p->R22.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(H2, p->R20.v);
+-        T6 = _mm_mul_epu32(H2, p->R21.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(H3, p->S24.v);
+-        T6 = _mm_mul_epu32(H3, p->R20.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(H4, p->S23.v);
+-        T6 = _mm_mul_epu32(H4, p->S24.v);
+-        T2 = _mm_add_epi64(T2, T5);
+-        T3 = _mm_add_epi64(T3, T6);
+-        T5 = _mm_mul_epu32(H1, p->R23.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-        T5 = _mm_mul_epu32(H2, p->R22.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-        T5 = _mm_mul_epu32(H3, p->R21.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-        T5 = _mm_mul_epu32(H4, p->R20.v);
+-        T4 = _mm_add_epi64(T4, T5);
+-
+-        /* H += [Mx,My] */
+-        T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 0)), _mm_loadl_epi64((xmmi *)(m + 16)));
+-        T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 8)), _mm_loadl_epi64((xmmi *)(m + 24)));
+-        M0 = _mm_and_si128(MMASK, T5);
+-        M1 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+-        T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+-        M2 = _mm_and_si128(MMASK, T5);
+-        M3 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+-        M4 = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+-
+-        T0 = _mm_add_epi64(T0, M0);
+-        T1 = _mm_add_epi64(T1, M1);
+-        T2 = _mm_add_epi64(T2, M2);
+-        T3 = _mm_add_epi64(T3, M3);
+-        T4 = _mm_add_epi64(T4, M4);
+-
+-        /* reduce */
+-        C1 = _mm_srli_epi64(T0, 26);
+-        C2 = _mm_srli_epi64(T3, 26);
+-        T0 = _mm_and_si128(T0, MMASK);
+-        T3 = _mm_and_si128(T3, MMASK);
+-        T1 = _mm_add_epi64(T1, C1);
+-        T4 = _mm_add_epi64(T4, C2);
+-        C1 = _mm_srli_epi64(T1, 26);
+-        C2 = _mm_srli_epi64(T4, 26);
+-        T1 = _mm_and_si128(T1, MMASK);
+-        T4 = _mm_and_si128(T4, MMASK);
+-        T2 = _mm_add_epi64(T2, C1);
+-        T0 = _mm_add_epi64(T0, _mm_mul_epu32(C2, FIVE));
+-        C1 = _mm_srli_epi64(T2, 26);
+-        C2 = _mm_srli_epi64(T0, 26);
+-        T2 = _mm_and_si128(T2, MMASK);
+-        T0 = _mm_and_si128(T0, MMASK);
+-        T3 = _mm_add_epi64(T3, C1);
+-        T1 = _mm_add_epi64(T1, C2);
+-        C1 = _mm_srli_epi64(T3, 26);
+-        T3 = _mm_and_si128(T3, MMASK);
+-        T4 = _mm_add_epi64(T4, C1);
+-
+-        /* H = (H*[r^2,r^2] + [Mx,My]) */
+-        H0 = T0;
+-        H1 = T1;
+-        H2 = T2;
+-        H3 = T3;
+-        H4 = T4;
+-
+-        consumed = 32;
+-    }
+-
+-    /* finalize, H *= [r^2,r] */
+-    r0 = ((uint64_t)p->R20.d[3] << 32) | (uint64_t)p->R20.d[1];
+-    r1 = ((uint64_t)p->R21.d[3] << 32) | (uint64_t)p->R21.d[1];
+-    r2 = ((uint64_t)p->R22.d[3] << 32) | (uint64_t)p->R22.d[1];
+-
+-    p->R20.d[2] = (uint32_t)(r0)&0x3ffffff;
+-    p->R21.d[2] = (uint32_t)((r0 >> 26) | (r1 << 18)) & 0x3ffffff;
+-    p->R22.d[2] = (uint32_t)((r1 >> 8)) & 0x3ffffff;
+-    p->R23.d[2] = (uint32_t)((r1 >> 34) | (r2 << 10)) & 0x3ffffff;
+-    p->R24.d[2] = (uint32_t)((r2 >> 16));
+-    p->S21.d[2] = p->R21.d[2] * 5;
+-    p->S22.d[2] = p->R22.d[2] * 5;
+-    p->S23.d[2] = p->R23.d[2] * 5;
+-    p->S24.d[2] = p->R24.d[2] * 5;
+-
+-    /* H *= [r^2,r] */
+-    T0 = _mm_mul_epu32(H0, p->R20.v);
+-    T1 = _mm_mul_epu32(H0, p->R21.v);
+-    T2 = _mm_mul_epu32(H0, p->R22.v);
+-    T3 = _mm_mul_epu32(H0, p->R23.v);
+-    T4 = _mm_mul_epu32(H0, p->R24.v);
+-    T5 = _mm_mul_epu32(H1, p->S24.v);
+-    T6 = _mm_mul_epu32(H1, p->R20.v);
+-    T0 = _mm_add_epi64(T0, T5);
+-    T1 = _mm_add_epi64(T1, T6);
+-    T5 = _mm_mul_epu32(H2, p->S23.v);
+-    T6 = _mm_mul_epu32(H2, p->S24.v);
+-    T0 = _mm_add_epi64(T0, T5);
+-    T1 = _mm_add_epi64(T1, T6);
+-    T5 = _mm_mul_epu32(H3, p->S22.v);
+-    T6 = _mm_mul_epu32(H3, p->S23.v);
+-    T0 = _mm_add_epi64(T0, T5);
+-    T1 = _mm_add_epi64(T1, T6);
+-    T5 = _mm_mul_epu32(H4, p->S21.v);
+-    T6 = _mm_mul_epu32(H4, p->S22.v);
+-    T0 = _mm_add_epi64(T0, T5);
+-    T1 = _mm_add_epi64(T1, T6);
+-    T5 = _mm_mul_epu32(H1, p->R21.v);
+-    T6 = _mm_mul_epu32(H1, p->R22.v);
+-    T2 = _mm_add_epi64(T2, T5);
+-    T3 = _mm_add_epi64(T3, T6);
+-    T5 = _mm_mul_epu32(H2, p->R20.v);
+-    T6 = _mm_mul_epu32(H2, p->R21.v);
+-    T2 = _mm_add_epi64(T2, T5);
+-    T3 = _mm_add_epi64(T3, T6);
+-    T5 = _mm_mul_epu32(H3, p->S24.v);
+-    T6 = _mm_mul_epu32(H3, p->R20.v);
+-    T2 = _mm_add_epi64(T2, T5);
+-    T3 = _mm_add_epi64(T3, T6);
+-    T5 = _mm_mul_epu32(H4, p->S23.v);
+-    T6 = _mm_mul_epu32(H4, p->S24.v);
+-    T2 = _mm_add_epi64(T2, T5);
+-    T3 = _mm_add_epi64(T3, T6);
+-    T5 = _mm_mul_epu32(H1, p->R23.v);
+-    T4 = _mm_add_epi64(T4, T5);
+-    T5 = _mm_mul_epu32(H2, p->R22.v);
+-    T4 = _mm_add_epi64(T4, T5);
+-    T5 = _mm_mul_epu32(H3, p->R21.v);
+-    T4 = _mm_add_epi64(T4, T5);
+-    T5 = _mm_mul_epu32(H4, p->R20.v);
+-    T4 = _mm_add_epi64(T4, T5);
+-
+-    C1 = _mm_srli_epi64(T0, 26);
+-    C2 = _mm_srli_epi64(T3, 26);
+-    T0 = _mm_and_si128(T0, MMASK);
+-    T3 = _mm_and_si128(T3, MMASK);
+-    T1 = _mm_add_epi64(T1, C1);
+-    T4 = _mm_add_epi64(T4, C2);
+-    C1 = _mm_srli_epi64(T1, 26);
+-    C2 = _mm_srli_epi64(T4, 26);
+-    T1 = _mm_and_si128(T1, MMASK);
+-    T4 = _mm_and_si128(T4, MMASK);
+-    T2 = _mm_add_epi64(T2, C1);
+-    T0 = _mm_add_epi64(T0, _mm_mul_epu32(C2, FIVE));
+-    C1 = _mm_srli_epi64(T2, 26);
+-    C2 = _mm_srli_epi64(T0, 26);
+-    T2 = _mm_and_si128(T2, MMASK);
+-    T0 = _mm_and_si128(T0, MMASK);
+-    T3 = _mm_add_epi64(T3, C1);
+-    T1 = _mm_add_epi64(T1, C2);
+-    C1 = _mm_srli_epi64(T3, 26);
+-    T3 = _mm_and_si128(T3, MMASK);
+-    T4 = _mm_add_epi64(T4, C1);
+-
+-    /* H = H[0]+H[1] */
+-    H0 = _mm_add_epi64(T0, _mm_srli_si128(T0, 8));
+-    H1 = _mm_add_epi64(T1, _mm_srli_si128(T1, 8));
+-    H2 = _mm_add_epi64(T2, _mm_srli_si128(T2, 8));
+-    H3 = _mm_add_epi64(T3, _mm_srli_si128(T3, 8));
+-    H4 = _mm_add_epi64(T4, _mm_srli_si128(T4, 8));
+-
+-    t0 = _mm_cvtsi128_si32(H0);
+-    c = (t0 >> 26);
+-    t0 &= 0x3ffffff;
+-    t1 = _mm_cvtsi128_si32(H1) + c;
+-    c = (t1 >> 26);
+-    t1 &= 0x3ffffff;
+-    t2 = _mm_cvtsi128_si32(H2) + c;
+-    c = (t2 >> 26);
+-    t2 &= 0x3ffffff;
+-    t3 = _mm_cvtsi128_si32(H3) + c;
+-    c = (t3 >> 26);
+-    t3 &= 0x3ffffff;
+-    t4 = _mm_cvtsi128_si32(H4) + c;
+-    c = (t4 >> 26);
+-    t4 &= 0x3ffffff;
+-    t0 = t0 + (c * 5);
+-    c = (t0 >> 26);
+-    t0 &= 0x3ffffff;
+-    t1 = t1 + c;
+-
+-    st->HH[0] = ((t0) | (t1 << 26)) & 0xfffffffffffull;
+-    st->HH[1] = ((t1 >> 18) | (t2 << 8) | (t3 << 34)) & 0xfffffffffffull;
+-    st->HH[2] = ((t3 >> 10) | (t4 << 16)) & 0x3ffffffffffull;
+-
+-    return consumed;
+-}
+-
+-void
+-Poly1305Update(poly1305_state *state, const unsigned char *m, size_t bytes)
+-{
+-    poly1305_state_internal *st = poly1305_aligned_state(state);
+-    size_t want;
+-
+-    /* need at least 32 initial bytes to start the accelerated branch */
+-    if (!st->started) {
+-        if ((st->leftover == 0) && (bytes > 32)) {
+-            poly1305_first_block(st, m);
+-            m += 32;
+-            bytes -= 32;
+-        } else {
+-            want = poly1305_min(32 - st->leftover, bytes);
+-            poly1305_block_copy(st->buffer + st->leftover, m, want);
+-            bytes -= want;
+-            m += want;
+-            st->leftover += want;
+-            if ((st->leftover < 32) || (bytes == 0))
+-                return;
+-            poly1305_first_block(st, st->buffer);
+-            st->leftover = 0;
+-        }
+-        st->started = 1;
+-    }
+-
+-    /* handle leftover */
+-    if (st->leftover) {
+-        want = poly1305_min(64 - st->leftover, bytes);
+-        poly1305_block_copy(st->buffer + st->leftover, m, want);
+-        bytes -= want;
+-        m += want;
+-        st->leftover += want;
+-        if (st->leftover < 64)
+-            return;
+-        poly1305_blocks(st, st->buffer, 64);
+-        st->leftover = 0;
+-    }
+-
+-    /* process 64 byte blocks */
+-    if (bytes >= 64) {
+-        want = (bytes & ~63);
+-        poly1305_blocks(st, m, want);
+-        m += want;
+-        bytes -= want;
+-    }
+-
+-    if (bytes) {
+-        poly1305_block_copy(st->buffer + st->leftover, m, bytes);
+-        st->leftover += bytes;
+-    }
+-}
+-
+-void
+-Poly1305Finish(poly1305_state *state, unsigned char mac[16])
+-{
+-    poly1305_state_internal *st = poly1305_aligned_state(state);
+-    size_t leftover = st->leftover;
+-    uint8_t *m = st->buffer;
+-    uint128_t d[3];
+-    uint64_t h0, h1, h2;
+-    uint64_t t0, t1;
+-    uint64_t g0, g1, g2, c, nc;
+-    uint64_t r0, r1, r2, s1, s2;
+-    poly1305_power *p;
+-
+-    if (st->started) {
+-        size_t consumed = poly1305_combine(st, m, leftover);
+-        leftover -= consumed;
+-        m += consumed;
+-    }
+-
+-    /* st->HH will either be 0 or have the combined result */
+-    h0 = st->HH[0];
+-    h1 = st->HH[1];
+-    h2 = st->HH[2];
+-
+-    p = &st->P[1];
+-    r0 = ((uint64_t)p->R20.d[3] << 32) | (uint64_t)p->R20.d[1];
+-    r1 = ((uint64_t)p->R21.d[3] << 32) | (uint64_t)p->R21.d[1];
+-    r2 = ((uint64_t)p->R22.d[3] << 32) | (uint64_t)p->R22.d[1];
+-    s1 = r1 * (5 << 2);
+-    s2 = r2 * (5 << 2);
+-
+-    if (leftover < 16)
+-        goto poly1305_donna_atmost15bytes;
+-
+-poly1305_donna_atleast16bytes:
+-    t0 = U8TO64_LE(m + 0);
+-    t1 = U8TO64_LE(m + 8);
+-    h0 += t0 & 0xfffffffffff;
+-    t0 = shr128_pair(t1, t0, 44);
+-    h1 += t0 & 0xfffffffffff;
+-    h2 += (t1 >> 24) | ((uint64_t)1 << 40);
+-
+-poly1305_donna_mul:
+-    d[0] = add128(add128(mul64x64_128(h0, r0), mul64x64_128(h1, s2)), mul64x64_128(h2, s1));
+-    d[1] = add128(add128(mul64x64_128(h0, r1), mul64x64_128(h1, r0)), mul64x64_128(h2, s2));
+-    d[2] = add128(add128(mul64x64_128(h0, r2), mul64x64_128(h1, r1)), mul64x64_128(h2, r0));
+-    h0 = lo128(d[0]) & 0xfffffffffff;
+-    c = shr128(d[0], 44);
+-    d[1] = add128_64(d[1], c);
+-    h1 = lo128(d[1]) & 0xfffffffffff;
+-    c = shr128(d[1], 44);
+-    d[2] = add128_64(d[2], c);
+-    h2 = lo128(d[2]) & 0x3ffffffffff;
+-    c = shr128(d[2], 42);
+-    h0 += c * 5;
+-
+-    m += 16;
+-    leftover -= 16;
+-    if (leftover >= 16)
+-        goto poly1305_donna_atleast16bytes;
+-
+-/* final bytes */
+-poly1305_donna_atmost15bytes:
+-    if (!leftover)
+-        goto poly1305_donna_finish;
+-
+-    m[leftover++] = 1;
+-    poly1305_block_zero(m + leftover, 16 - leftover);
+-    leftover = 16;
+-
+-    t0 = U8TO64_LE(m + 0);
+-    t1 = U8TO64_LE(m + 8);
+-    h0 += t0 & 0xfffffffffff;
+-    t0 = shr128_pair(t1, t0, 44);
+-    h1 += t0 & 0xfffffffffff;
+-    h2 += (t1 >> 24);
+-
+-    goto poly1305_donna_mul;
+-
+-poly1305_donna_finish:
+-    c = (h0 >> 44);
+-    h0 &= 0xfffffffffff;
+-    h1 += c;
+-    c = (h1 >> 44);
+-    h1 &= 0xfffffffffff;
+-    h2 += c;
+-    c = (h2 >> 42);
+-    h2 &= 0x3ffffffffff;
+-    h0 += c * 5;
+-
+-    g0 = h0 + 5;
+-    c = (g0 >> 44);
+-    g0 &= 0xfffffffffff;
+-    g1 = h1 + c;
+-    c = (g1 >> 44);
+-    g1 &= 0xfffffffffff;
+-    g2 = h2 + c - ((uint64_t)1 << 42);
+-
+-    c = (g2 >> 63) - 1;
+-    nc = ~c;
+-    h0 = (h0 & nc) | (g0 & c);
+-    h1 = (h1 & nc) | (g1 & c);
+-    h2 = (h2 & nc) | (g2 & c);
+-
+-    /* pad */
+-    t0 = ((uint64_t)p->R23.d[3] << 32) | (uint64_t)p->R23.d[1];
+-    t1 = ((uint64_t)p->R24.d[3] << 32) | (uint64_t)p->R24.d[1];
+-    h0 += (t0 & 0xfffffffffff);
+-    c = (h0 >> 44);
+-    h0 &= 0xfffffffffff;
+-    t0 = shr128_pair(t1, t0, 44);
+-    h1 += (t0 & 0xfffffffffff) + c;
+-    c = (h1 >> 44);
+-    h1 &= 0xfffffffffff;
+-    t1 = (t1 >> 24);
+-    h2 += (t1) + c;
+-
+-    U64TO8_LE(mac + 0, ((h0) | (h1 << 44)));
+-    U64TO8_LE(mac + 8, ((h1 >> 20) | (h2 << 24)));
+-}
+diff --git a/security/nss/lib/freebl/poly1305.c b/security/nss/lib/freebl/poly1305.c
+deleted file mode 100644
+--- a/security/nss/lib/freebl/poly1305.c
++++ /dev/null
+@@ -1,314 +0,0 @@
+-/* This Source Code Form is subject to the terms of the Mozilla Public
+- * 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/. */
+-
+-/* This implementation of poly1305 is by Andrew Moon
+- * (https://github.com/floodyberry/poly1305-donna) and released as public
+- * domain. */
+-
+-#include <string.h>
+-
+-#include "poly1305.h"
+-
+-#if defined(_MSC_VER) && _MSC_VER < 1600
+-#include "prtypes.h"
+-typedef PRUint32 uint32_t;
+-typedef PRUint64 uint64_t;
+-#else
+-#include <stdint.h>
+-#endif
+-
+-#if defined(NSS_X86) || defined(NSS_X64)
+-/* We can assume little-endian. */
+-static uint32_t
+-U8TO32_LE(const unsigned char *m)
+-{
+-    uint32_t r;
+-    memcpy(&r, m, sizeof(r));
+-    return r;
+-}
+-
+-static void
+-U32TO8_LE(unsigned char *m, uint32_t v)
+-{
+-    memcpy(m, &v, sizeof(v));
+-}
+-#else
+-static uint32_t
+-U8TO32_LE(const unsigned char *m)
+-{
+-    return (uint32_t)m[0] |
+-           (uint32_t)m[1] << 8 |
+-           (uint32_t)m[2] << 16 |
+-           (uint32_t)m[3] << 24;
+-}
+-
+-static void
+-U32TO8_LE(unsigned char *m, uint32_t v)
+-{
+-    m[0] = v;
+-    m[1] = v >> 8;
+-    m[2] = v >> 16;
+-    m[3] = v >> 24;
+-}
+-#endif
+-
+-static uint64_t
+-mul32x32_64(uint32_t a, uint32_t b)
+-{
+-    return (uint64_t)a * b;
+-}
+-
+-struct poly1305_state_st {
+-    uint32_t r0, r1, r2, r3, r4;
+-    uint32_t s1, s2, s3, s4;
+-    uint32_t h0, h1, h2, h3, h4;
+-    unsigned char buf[16];
+-    unsigned int buf_used;
+-    unsigned char key[16];
+-};
+-
+-/* update updates |state| given some amount of input data. This function may
+- * only be called with a |len| that is not a multiple of 16 at the end of the
+- * data. Otherwise the input must be buffered into 16 byte blocks. */
+-static void
+-update(struct poly1305_state_st *state, const unsigned char *in,
+-       size_t len)
+-{
+-    uint32_t t0, t1, t2, t3;
+-    uint64_t t[5];
+-    uint32_t b;
+-    uint64_t c;
+-    size_t j;
+-    unsigned char mp[16];
+-
+-    if (len < 16)
+-        goto poly1305_donna_atmost15bytes;
+-
+-poly1305_donna_16bytes:
+-    t0 = U8TO32_LE(in);
+-    t1 = U8TO32_LE(in + 4);
+-    t2 = U8TO32_LE(in + 8);
+-    t3 = U8TO32_LE(in + 12);
+-
+-    in += 16;
+-    len -= 16;
+-
+-    state->h0 += t0 & 0x3ffffff;
+-    state->h1 += ((((uint64_t)t1 << 32) | t0) >> 26) & 0x3ffffff;
+-    state->h2 += ((((uint64_t)t2 << 32) | t1) >> 20) & 0x3ffffff;
+-    state->h3 += ((((uint64_t)t3 << 32) | t2) >> 14) & 0x3ffffff;
+-    state->h4 += (t3 >> 8) | (1 << 24);
+-
+-poly1305_donna_mul:
+-    t[0] = mul32x32_64(state->h0, state->r0) +
+-           mul32x32_64(state->h1, state->s4) +
+-           mul32x32_64(state->h2, state->s3) +
+-           mul32x32_64(state->h3, state->s2) +
+-           mul32x32_64(state->h4, state->s1);
+-    t[1] = mul32x32_64(state->h0, state->r1) +
+-           mul32x32_64(state->h1, state->r0) +
+-           mul32x32_64(state->h2, state->s4) +
+-           mul32x32_64(state->h3, state->s3) +
+-           mul32x32_64(state->h4, state->s2);
+-    t[2] = mul32x32_64(state->h0, state->r2) +
+-           mul32x32_64(state->h1, state->r1) +
+-           mul32x32_64(state->h2, state->r0) +
+-           mul32x32_64(state->h3, state->s4) +
+-           mul32x32_64(state->h4, state->s3);
+-    t[3] = mul32x32_64(state->h0, state->r3) +
+-           mul32x32_64(state->h1, state->r2) +
+-           mul32x32_64(state->h2, state->r1) +
+-           mul32x32_64(state->h3, state->r0) +
+-           mul32x32_64(state->h4, state->s4);
+-    t[4] = mul32x32_64(state->h0, state->r4) +
+-           mul32x32_64(state->h1, state->r3) +
+-           mul32x32_64(state->h2, state->r2) +
+-           mul32x32_64(state->h3, state->r1) +
+-           mul32x32_64(state->h4, state->r0);
+-
+-    state->h0 = (uint32_t)t[0] & 0x3ffffff;
+-    c = (t[0] >> 26);
+-    t[1] += c;
+-    state->h1 = (uint32_t)t[1] & 0x3ffffff;
+-    b = (uint32_t)(t[1] >> 26);
+-    t[2] += b;
+-    state->h2 = (uint32_t)t[2] & 0x3ffffff;
+-    b = (uint32_t)(t[2] >> 26);
+-    t[3] += b;
+-    state->h3 = (uint32_t)t[3] & 0x3ffffff;
+-    b = (uint32_t)(t[3] >> 26);
+-    t[4] += b;
+-    state->h4 = (uint32_t)t[4] & 0x3ffffff;
+-    b = (uint32_t)(t[4] >> 26);
+-    state->h0 += b * 5;
+-
+-    if (len >= 16)
+-        goto poly1305_donna_16bytes;
+-
+-/* final bytes */
+-poly1305_donna_atmost15bytes:
+-    if (!len)
+-        return;
+-
+-    for (j = 0; j < len; j++)
+-        mp[j] = in[j];
+-    mp[j++] = 1;
+-    for (; j < 16; j++)
+-        mp[j] = 0;
+-    len = 0;
+-
+-    t0 = U8TO32_LE(mp + 0);
+-    t1 = U8TO32_LE(mp + 4);
+-    t2 = U8TO32_LE(mp + 8);
+-    t3 = U8TO32_LE(mp + 12);
+-
+-    state->h0 += t0 & 0x3ffffff;
+-    state->h1 += ((((uint64_t)t1 << 32) | t0) >> 26) & 0x3ffffff;
+-    state->h2 += ((((uint64_t)t2 << 32) | t1) >> 20) & 0x3ffffff;
+-    state->h3 += ((((uint64_t)t3 << 32) | t2) >> 14) & 0x3ffffff;
+-    state->h4 += (t3 >> 8);
+-
+-    goto poly1305_donna_mul;
+-}
+-
+-void
+-Poly1305Init(poly1305_state *statep, const unsigned char key[32])
+-{
+-    struct poly1305_state_st *state = (struct poly1305_state_st *)statep;
+-    uint32_t t0, t1, t2, t3;
+-
+-    t0 = U8TO32_LE(key + 0);
+-    t1 = U8TO32_LE(key + 4);
+-    t2 = U8TO32_LE(key + 8);
+-    t3 = U8TO32_LE(key + 12);
+-
+-    /* precompute multipliers */
+-    state->r0 = t0 & 0x3ffffff;
+-    t0 >>= 26;
+-    t0 |= t1 << 6;
+-    state->r1 = t0 & 0x3ffff03;
+-    t1 >>= 20;
+-    t1 |= t2 << 12;
+-    state->r2 = t1 & 0x3ffc0ff;
+-    t2 >>= 14;
+-    t2 |= t3 << 18;
+-    state->r3 = t2 & 0x3f03fff;
+-    t3 >>= 8;
+-    state->r4 = t3 & 0x00fffff;
+-
+-    state->s1 = state->r1 * 5;
+-    state->s2 = state->r2 * 5;
+-    state->s3 = state->r3 * 5;
+-    state->s4 = state->r4 * 5;
+-
+-    /* init state */
+-    state->h0 = 0;
+-    state->h1 = 0;
+-    state->h2 = 0;
+-    state->h3 = 0;
+-    state->h4 = 0;
+-
+-    state->buf_used = 0;
+-    memcpy(state->key, key + 16, sizeof(state->key));
+-}
+-
+-void
+-Poly1305Update(poly1305_state *statep, const unsigned char *in,
+-               size_t in_len)
+-{
+-    unsigned int i;
+-    struct poly1305_state_st *state = (struct poly1305_state_st *)statep;
+-
+-    if (state->buf_used) {
+-        unsigned int todo = 16 - state->buf_used;
+-        if (todo > in_len)
+-            todo = in_len;
+-        for (i = 0; i < todo; i++)
+-            state->buf[state->buf_used + i] = in[i];
+-        state->buf_used += todo;
+-        in_len -= todo;
+-        in += todo;
+-
+-        if (state->buf_used == 16) {
+-            update(state, state->buf, 16);
+-            state->buf_used = 0;
+-        }
+-    }
+-
+-    if (in_len >= 16) {
+-        size_t todo = in_len & ~0xf;
+-        update(state, in, todo);
+-        in += todo;
+-        in_len &= 0xf;
+-    }
+-
+-    if (in_len) {
+-        for (i = 0; i < in_len; i++)
+-            state->buf[i] = in[i];
+-        state->buf_used = in_len;
+-    }
+-}
+-
+-void
+-Poly1305Finish(poly1305_state *statep, unsigned char mac[16])
+-{
+-    struct poly1305_state_st *state = (struct poly1305_state_st *)statep;
+-    uint64_t f0, f1, f2, f3;
+-    uint32_t g0, g1, g2, g3, g4;
+-    uint32_t b, nb;
+-
+-    if (state->buf_used)
+-        update(state, state->buf, state->buf_used);
+-
+-    b = state->h0 >> 26;
+-    state->h0 = state->h0 & 0x3ffffff;
+-    state->h1 += b;
+-    b = state->h1 >> 26;
+-    state->h1 = state->h1 & 0x3ffffff;
+-    state->h2 += b;
+-    b = state->h2 >> 26;
+-    state->h2 = state->h2 & 0x3ffffff;
+-    state->h3 += b;
+-    b = state->h3 >> 26;
+-    state->h3 = state->h3 & 0x3ffffff;
+-    state->h4 += b;
+-    b = state->h4 >> 26;
+-    state->h4 = state->h4 & 0x3ffffff;
+-    state->h0 += b * 5;
+-
+-    g0 = state->h0 + 5;
+-    b = g0 >> 26;
+-    g0 &= 0x3ffffff;
+-    g1 = state->h1 + b;
+-    b = g1 >> 26;
+-    g1 &= 0x3ffffff;
+-    g2 = state->h2 + b;
+-    b = g2 >> 26;
+-    g2 &= 0x3ffffff;
+-    g3 = state->h3 + b;
+-    b = g3 >> 26;
+-    g3 &= 0x3ffffff;
+-    g4 = state->h4 + b - (1 << 26);
+-
+-    b = (g4 >> 31) - 1;
+-    nb = ~b;
+-    state->h0 = (state->h0 & nb) | (g0 & b);
+-    state->h1 = (state->h1 & nb) | (g1 & b);
+-    state->h2 = (state->h2 & nb) | (g2 & b);
+-    state->h3 = (state->h3 & nb) | (g3 & b);
+-    state->h4 = (state->h4 & nb) | (g4 & b);
+-
+-    f0 = ((state->h0) | (state->h1 << 26)) + (uint64_t)U8TO32_LE(&state->key[0]);
+-    f1 = ((state->h1 >> 6) | (state->h2 << 20)) + (uint64_t)U8TO32_LE(&state->key[4]);
+-    f2 = ((state->h2 >> 12) | (state->h3 << 14)) + (uint64_t)U8TO32_LE(&state->key[8]);
+-    f3 = ((state->h3 >> 18) | (state->h4 << 8)) + (uint64_t)U8TO32_LE(&state->key[12]);
+-
+-    U32TO8_LE(&mac[0], (uint32_t)f0);
+-    f1 += (f0 >> 32);
+-    U32TO8_LE(&mac[4], (uint32_t)f1);
+-    f2 += (f1 >> 32);
+-    U32TO8_LE(&mac[8], (uint32_t)f2);
+-    f3 += (f2 >> 32);
+-    U32TO8_LE(&mac[12], (uint32_t)f3);
+-}
+diff --git a/security/nss/lib/freebl/poly1305.h b/security/nss/lib/freebl/poly1305.h
+deleted file mode 100644
+--- a/security/nss/lib/freebl/poly1305.h
++++ /dev/null
+@@ -1,30 +0,0 @@
+-/*
+- * poly1305.h - header file for Poly1305 implementation.
+- *
+- * This Source Code Form is subject to the terms of the Mozilla Public
+- * 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/. */
+-
+-#ifndef FREEBL_POLY1305_H_
+-#define FREEBL_POLY1305_H_
+-
+-#include "stddef.h"
+-
+-typedef unsigned char poly1305_state[512];
+-
+-/* Poly1305Init sets up |state| so that it can be used to calculate an
+- * authentication tag with the one-time key |key|. Note that |key| is a
+- * one-time key and therefore there is no `reset' method because that would
+- * enable several messages to be authenticated with the same key. */
+-extern void Poly1305Init(poly1305_state* state, const unsigned char key[32]);
+-
+-/* Poly1305Update processes |in_len| bytes from |in|. It can be called zero or
+- * more times after poly1305_init. */
+-extern void Poly1305Update(poly1305_state* state, const unsigned char* in,
+-                           size_t inLen);
+-
+-/* Poly1305Finish completes the poly1305 calculation and writes a 16 byte
+- * authentication tag to |mac|. */
+-extern void Poly1305Finish(poly1305_state* state, unsigned char mac[16]);
+-
+-#endif /* FREEBL_POLY1305_H_ */
+diff --git a/security/nss/lib/freebl/rsapkcs.c b/security/nss/lib/freebl/rsapkcs.c
+--- a/security/nss/lib/freebl/rsapkcs.c
++++ b/security/nss/lib/freebl/rsapkcs.c
+@@ -933,66 +933,58 @@ failure:
+ SECStatus
+ RSA_DecryptBlock(RSAPrivateKey *key,
+                  unsigned char *output,
+                  unsigned int *outputLen,
+                  unsigned int maxOutputLen,
+                  const unsigned char *input,
+                  unsigned int inputLen)
+ {
+-    PRInt8 rv;
++    SECStatus rv;
+     unsigned int modulusLen = rsa_modulusLen(&key->modulus);
+     unsigned int i;
+-    unsigned char *buffer = NULL;
+-    unsigned int outLen = 0;
+-    unsigned int copyOutLen = modulusLen - 11;
++    unsigned char *buffer;
+ 
+-    if (inputLen != modulusLen || modulusLen < 10) {
+-        return SECFailure;
+-    }
++    if (inputLen != modulusLen)
++        goto failure;
+ 
+-    if (copyOutLen > maxOutputLen) {
+-        copyOutLen = maxOutputLen;
+-    }
++    buffer = (unsigned char *)PORT_Alloc(modulusLen + 1);
++    if (!buffer)
++        goto failure;
+ 
+-    // Allocate enough space to decrypt + copyOutLen to allow copying outLen later.
+-    buffer = PORT_ZAlloc(modulusLen + 1 + copyOutLen);
+-    if (!buffer) {
+-        return SECFailure;
+-    }
++    rv = RSA_PrivateKeyOp(key, buffer, input);
++    if (rv != SECSuccess)
++        goto loser;
+ 
+-    // rv is 0 if everything is going well and 1 if an error occurs.
+-    rv = RSA_PrivateKeyOp(key, buffer, input) != SECSuccess;
+-    rv |= (buffer[0] != RSA_BLOCK_FIRST_OCTET) |
+-          (buffer[1] != (unsigned char)RSA_BlockPublic);
+-
+-    // There have to be at least 8 bytes of padding.
+-    for (i = 2; i < 10; i++) {
+-        rv |= buffer[i] == RSA_BLOCK_AFTER_PAD_OCTET;
++    /* XXX(rsleevi): Constant time */
++    if (buffer[0] != RSA_BLOCK_FIRST_OCTET ||
++        buffer[1] != (unsigned char)RSA_BlockPublic) {
++        goto loser;
+     }
++    *outputLen = 0;
++    for (i = 2; i < modulusLen; i++) {
++        if (buffer[i] == RSA_BLOCK_AFTER_PAD_OCTET) {
++            *outputLen = modulusLen - i - 1;
++            break;
++        }
++    }
++    if (*outputLen == 0)
++        goto loser;
++    if (*outputLen > maxOutputLen)
++        goto loser;
+ 
+-    for (i = 10; i < modulusLen; i++) {
+-        unsigned int newLen = modulusLen - i - 1;
+-        unsigned int c = (buffer[i] == RSA_BLOCK_AFTER_PAD_OCTET) & (outLen == 0);
+-        outLen = constantTimeCondition(c, newLen, outLen);
+-    }
+-    rv |= outLen == 0;
+-    rv |= outLen > maxOutputLen;
+-
+-    // Note that output is set even if SECFailure is returned.
+-    PORT_Memcpy(output, buffer + modulusLen - outLen, copyOutLen);
+-    *outputLen = constantTimeCondition(outLen > maxOutputLen, maxOutputLen,
+-                                       outLen);
++    PORT_Memcpy(output, buffer + modulusLen - *outputLen, *outputLen);
+ 
+     PORT_Free(buffer);
++    return SECSuccess;
+ 
+-    for (i = 1; i < sizeof(rv) * 8; i <<= 1) {
+-        rv |= rv << i;
+-    }
+-    return (SECStatus)rv;
++loser:
++    PORT_Free(buffer);
++failure:
++    return SECFailure;
+ }
+ 
+ /*
+  * Encode a RSA-PSS signature.
+  * Described in RFC 3447, section 9.1.1.
+  * We use mHash instead of M as input.
+  * emBits from the RFC is just modBits - 1, see section 8.1.1.
+  * We only support MGF1 as the MGF.
+diff --git a/security/nss/lib/freebl/verified/Hacl_Poly1305_32.c b/security/nss/lib/freebl/verified/Hacl_Poly1305_32.c
+new file mode 100644
+--- /dev/null
++++ b/security/nss/lib/freebl/verified/Hacl_Poly1305_32.c
+@@ -0,0 +1,576 @@
++/* Copyright 2016-2017 INRIA and Microsoft Corporation
++ *
++ * Licensed under the Apache License, Version 2.0 (the "License");
++ * you may not use this file except in compliance with the License.
++ * You may obtain a copy of the License at
++ *
++ *     http://www.apache.org/licenses/LICENSE-2.0
++ *
++ * Unless required by applicable law or agreed to in writing, software
++ * distributed under the License is distributed on an "AS IS" BASIS,
++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
++ * See the License for the specific language governing permissions and
++ * limitations under the License.
++ */
++
++#include "Hacl_Poly1305_32.h"
++
++inline static void
++Hacl_Bignum_Modulo_reduce(uint32_t *b)
++{
++    uint32_t b0 = b[0U];
++    b[0U] = (b0 << (uint32_t)2U) + b0;
++}
++
++inline static void
++Hacl_Bignum_Modulo_carry_top(uint32_t *b)
++{
++    uint32_t b4 = b[4U];
++    uint32_t b0 = b[0U];
++    uint32_t b4_26 = b4 >> (uint32_t)26U;
++    b[4U] = b4 & (uint32_t)0x3ffffffU;
++    b[0U] = (b4_26 << (uint32_t)2U) + b4_26 + b0;
++}
++
++inline static void
++Hacl_Bignum_Modulo_carry_top_wide(uint64_t *b)
++{
++    uint64_t b4 = b[4U];
++    uint64_t b0 = b[0U];
++    uint64_t b4_ = b4 & (uint64_t)(uint32_t)0x3ffffffU;
++    uint32_t b4_26 = (uint32_t)(b4 >> (uint32_t)26U);
++    uint64_t b0_ = b0 + (uint64_t)((b4_26 << (uint32_t)2U) + b4_26);
++    b[4U] = b4_;
++    b[0U] = b0_;
++}
++
++inline static void
++Hacl_Bignum_Fproduct_copy_from_wide_(uint32_t *output, uint64_t *input)
++{
++    for (uint32_t i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U) {
++        uint64_t xi = input[i];
++        output[i] = (uint32_t)xi;
++    }
++}
++
++inline static void
++Hacl_Bignum_Fproduct_sum_scalar_multiplication_(uint64_t *output, uint32_t *input, uint32_t s)
++{
++    for (uint32_t i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U) {
++        uint64_t xi = output[i];
++        uint32_t yi = input[i];
++        output[i] = xi + (uint64_t)yi * (uint64_t)s;
++    }
++}
++
++inline static void
++Hacl_Bignum_Fproduct_carry_wide_(uint64_t *tmp)
++{
++    for (uint32_t i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U) {
++        uint32_t ctr = i;
++        uint64_t tctr = tmp[ctr];
++        uint64_t tctrp1 = tmp[ctr + (uint32_t)1U];
++        uint32_t r0 = (uint32_t)tctr & (uint32_t)0x3ffffffU;
++        uint64_t c = tctr >> (uint32_t)26U;
++        tmp[ctr] = (uint64_t)r0;
++        tmp[ctr + (uint32_t)1U] = tctrp1 + c;
++    }
++}
++
++inline static void
++Hacl_Bignum_Fproduct_carry_limb_(uint32_t *tmp)
++{
++    for (uint32_t i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U) {
++        uint32_t ctr = i;
++        uint32_t tctr = tmp[ctr];
++        uint32_t tctrp1 = tmp[ctr + (uint32_t)1U];
++        uint32_t r0 = tctr & (uint32_t)0x3ffffffU;
++        uint32_t c = tctr >> (uint32_t)26U;
++        tmp[ctr] = r0;
++        tmp[ctr + (uint32_t)1U] = tctrp1 + c;
++    }
++}
++
++inline static void
++Hacl_Bignum_Fmul_shift_reduce(uint32_t *output)
++{
++    uint32_t tmp = output[4U];
++    for (uint32_t i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U) {
++        uint32_t ctr = (uint32_t)5U - i - (uint32_t)1U;
++        uint32_t z = output[ctr - (uint32_t)1U];
++        output[ctr] = z;
++    }
++    output[0U] = tmp;
++    Hacl_Bignum_Modulo_reduce(output);
++}
++
++static void
++Hacl_Bignum_Fmul_mul_shift_reduce_(uint64_t *output, uint32_t *input, uint32_t *input2)
++{
++    for (uint32_t i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U) {
++        uint32_t input2i = input2[i];
++        Hacl_Bignum_Fproduct_sum_scalar_multiplication_(output, input, input2i);
++        Hacl_Bignum_Fmul_shift_reduce(input);
++    }
++    uint32_t i = (uint32_t)4U;
++    uint32_t input2i = input2[i];
++    Hacl_Bignum_Fproduct_sum_scalar_multiplication_(output, input, input2i);
++}
++
++inline static void
++Hacl_Bignum_Fmul_fmul(uint32_t *output, uint32_t *input, uint32_t *input2)
++{
++    uint32_t tmp[5U] = { 0U };
++    memcpy(tmp, input, (uint32_t)5U * sizeof input[0U]);
++    uint64_t t[5U] = { 0U };
++    Hacl_Bignum_Fmul_mul_shift_reduce_(t, tmp, input2);
++    Hacl_Bignum_Fproduct_carry_wide_(t);
++    Hacl_Bignum_Modulo_carry_top_wide(t);
++    Hacl_Bignum_Fproduct_copy_from_wide_(output, t);
++    uint32_t i0 = output[0U];
++    uint32_t i1 = output[1U];
++    uint32_t i0_ = i0 & (uint32_t)0x3ffffffU;
++    uint32_t i1_ = i1 + (i0 >> (uint32_t)26U);
++    output[0U] = i0_;
++    output[1U] = i1_;
++}
++
++inline static void
++Hacl_Bignum_AddAndMultiply_add_and_multiply(uint32_t *acc, uint32_t *block, uint32_t *r)
++{
++    for (uint32_t i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U) {
++        uint32_t xi = acc[i];
++        uint32_t yi = block[i];
++        acc[i] = xi + yi;
++    }
++    Hacl_Bignum_Fmul_fmul(acc, acc, r);
++}
++
++inline static void
++Hacl_Impl_Poly1305_32_poly1305_update(
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *m)
++{
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut0 = st;
++    uint32_t *h = scrut0.h;
++    uint32_t *acc = h;
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut = st;
++    uint32_t *r = scrut.r;
++    uint32_t *r5 = r;
++    uint32_t tmp[5U] = { 0U };
++    uint8_t *s0 = m;
++    uint8_t *s1 = m + (uint32_t)3U;
++    uint8_t *s2 = m + (uint32_t)6U;
++    uint8_t *s3 = m + (uint32_t)9U;
++    uint8_t *s4 = m + (uint32_t)12U;
++    uint32_t i0 = load32_le(s0);
++    uint32_t i1 = load32_le(s1);
++    uint32_t i2 = load32_le(s2);
++    uint32_t i3 = load32_le(s3);
++    uint32_t i4 = load32_le(s4);
++    uint32_t r0 = i0 & (uint32_t)0x3ffffffU;
++    uint32_t r1 = i1 >> (uint32_t)2U & (uint32_t)0x3ffffffU;
++    uint32_t r2 = i2 >> (uint32_t)4U & (uint32_t)0x3ffffffU;
++    uint32_t r3 = i3 >> (uint32_t)6U & (uint32_t)0x3ffffffU;
++    uint32_t r4 = i4 >> (uint32_t)8U;
++    tmp[0U] = r0;
++    tmp[1U] = r1;
++    tmp[2U] = r2;
++    tmp[3U] = r3;
++    tmp[4U] = r4;
++    uint32_t b4 = tmp[4U];
++    uint32_t b4_ = (uint32_t)0x1000000U | b4;
++    tmp[4U] = b4_;
++    Hacl_Bignum_AddAndMultiply_add_and_multiply(acc, tmp, r5);
++}
++
++inline static void
++Hacl_Impl_Poly1305_32_poly1305_process_last_block_(
++    uint8_t *block,
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *m,
++    uint64_t rem_)
++{
++    uint32_t tmp[5U] = { 0U };
++    uint8_t *s0 = block;
++    uint8_t *s1 = block + (uint32_t)3U;
++    uint8_t *s2 = block + (uint32_t)6U;
++    uint8_t *s3 = block + (uint32_t)9U;
++    uint8_t *s4 = block + (uint32_t)12U;
++    uint32_t i0 = load32_le(s0);
++    uint32_t i1 = load32_le(s1);
++    uint32_t i2 = load32_le(s2);
++    uint32_t i3 = load32_le(s3);
++    uint32_t i4 = load32_le(s4);
++    uint32_t r0 = i0 & (uint32_t)0x3ffffffU;
++    uint32_t r1 = i1 >> (uint32_t)2U & (uint32_t)0x3ffffffU;
++    uint32_t r2 = i2 >> (uint32_t)4U & (uint32_t)0x3ffffffU;
++    uint32_t r3 = i3 >> (uint32_t)6U & (uint32_t)0x3ffffffU;
++    uint32_t r4 = i4 >> (uint32_t)8U;
++    tmp[0U] = r0;
++    tmp[1U] = r1;
++    tmp[2U] = r2;
++    tmp[3U] = r3;
++    tmp[4U] = r4;
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut0 = st;
++    uint32_t *h = scrut0.h;
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut = st;
++    uint32_t *r = scrut.r;
++    Hacl_Bignum_AddAndMultiply_add_and_multiply(h, tmp, r);
++}
++
++inline static void
++Hacl_Impl_Poly1305_32_poly1305_process_last_block(
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *m,
++    uint64_t rem_)
++{
++    uint8_t zero1 = (uint8_t)0U;
++    KRML_CHECK_SIZE(zero1, (uint32_t)16U);
++    uint8_t block[16U];
++    for (uint32_t _i = 0U; _i < (uint32_t)16U; ++_i)
++        block[_i] = zero1;
++    uint32_t i0 = (uint32_t)rem_;
++    uint32_t i = (uint32_t)rem_;
++    memcpy(block, m, i * sizeof m[0U]);
++    block[i0] = (uint8_t)1U;
++    Hacl_Impl_Poly1305_32_poly1305_process_last_block_(block, st, m, rem_);
++}
++
++static void
++Hacl_Impl_Poly1305_32_poly1305_last_pass(uint32_t *acc)
++{
++    Hacl_Bignum_Fproduct_carry_limb_(acc);
++    Hacl_Bignum_Modulo_carry_top(acc);
++    uint32_t t0 = acc[0U];
++    uint32_t t10 = acc[1U];
++    uint32_t t20 = acc[2U];
++    uint32_t t30 = acc[3U];
++    uint32_t t40 = acc[4U];
++    uint32_t t1_ = t10 + (t0 >> (uint32_t)26U);
++    uint32_t mask_261 = (uint32_t)0x3ffffffU;
++    uint32_t t0_ = t0 & mask_261;
++    uint32_t t2_ = t20 + (t1_ >> (uint32_t)26U);
++    uint32_t t1__ = t1_ & mask_261;
++    uint32_t t3_ = t30 + (t2_ >> (uint32_t)26U);
++    uint32_t t2__ = t2_ & mask_261;
++    uint32_t t4_ = t40 + (t3_ >> (uint32_t)26U);
++    uint32_t t3__ = t3_ & mask_261;
++    acc[0U] = t0_;
++    acc[1U] = t1__;
++    acc[2U] = t2__;
++    acc[3U] = t3__;
++    acc[4U] = t4_;
++    Hacl_Bignum_Modulo_carry_top(acc);
++    uint32_t t00 = acc[0U];
++    uint32_t t1 = acc[1U];
++    uint32_t t2 = acc[2U];
++    uint32_t t3 = acc[3U];
++    uint32_t t4 = acc[4U];
++    uint32_t t1_0 = t1 + (t00 >> (uint32_t)26U);
++    uint32_t t0_0 = t00 & (uint32_t)0x3ffffffU;
++    uint32_t t2_0 = t2 + (t1_0 >> (uint32_t)26U);
++    uint32_t t1__0 = t1_0 & (uint32_t)0x3ffffffU;
++    uint32_t t3_0 = t3 + (t2_0 >> (uint32_t)26U);
++    uint32_t t2__0 = t2_0 & (uint32_t)0x3ffffffU;
++    uint32_t t4_0 = t4 + (t3_0 >> (uint32_t)26U);
++    uint32_t t3__0 = t3_0 & (uint32_t)0x3ffffffU;
++    acc[0U] = t0_0;
++    acc[1U] = t1__0;
++    acc[2U] = t2__0;
++    acc[3U] = t3__0;
++    acc[4U] = t4_0;
++    Hacl_Bignum_Modulo_carry_top(acc);
++    uint32_t i0 = acc[0U];
++    uint32_t i1 = acc[1U];
++    uint32_t i0_ = i0 & (uint32_t)0x3ffffffU;
++    uint32_t i1_ = i1 + (i0 >> (uint32_t)26U);
++    acc[0U] = i0_;
++    acc[1U] = i1_;
++    uint32_t a0 = acc[0U];
++    uint32_t a1 = acc[1U];
++    uint32_t a2 = acc[2U];
++    uint32_t a3 = acc[3U];
++    uint32_t a4 = acc[4U];
++    uint32_t mask0 = FStar_UInt32_gte_mask(a0, (uint32_t)0x3fffffbU);
++    uint32_t mask1 = FStar_UInt32_eq_mask(a1, (uint32_t)0x3ffffffU);
++    uint32_t mask2 = FStar_UInt32_eq_mask(a2, (uint32_t)0x3ffffffU);
++    uint32_t mask3 = FStar_UInt32_eq_mask(a3, (uint32_t)0x3ffffffU);
++    uint32_t mask4 = FStar_UInt32_eq_mask(a4, (uint32_t)0x3ffffffU);
++    uint32_t mask = (((mask0 & mask1) & mask2) & mask3) & mask4;
++    uint32_t a0_ = a0 - ((uint32_t)0x3fffffbU & mask);
++    uint32_t a1_ = a1 - ((uint32_t)0x3ffffffU & mask);
++    uint32_t a2_ = a2 - ((uint32_t)0x3ffffffU & mask);
++    uint32_t a3_ = a3 - ((uint32_t)0x3ffffffU & mask);
++    uint32_t a4_ = a4 - ((uint32_t)0x3ffffffU & mask);
++    acc[0U] = a0_;
++    acc[1U] = a1_;
++    acc[2U] = a2_;
++    acc[3U] = a3_;
++    acc[4U] = a4_;
++}
++
++static Hacl_Impl_Poly1305_32_State_poly1305_state
++Hacl_Impl_Poly1305_32_mk_state(uint32_t *r, uint32_t *h)
++{
++    return ((Hacl_Impl_Poly1305_32_State_poly1305_state){.r = r, .h = h });
++}
++
++static void
++Hacl_Standalone_Poly1305_32_poly1305_blocks(
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *m,
++    uint64_t len1)
++{
++    if (!(len1 == (uint64_t)0U)) {
++        uint8_t *block = m;
++        uint8_t *tail1 = m + (uint32_t)16U;
++        Hacl_Impl_Poly1305_32_poly1305_update(st, block);
++        uint64_t len2 = len1 - (uint64_t)1U;
++        Hacl_Standalone_Poly1305_32_poly1305_blocks(st, tail1, len2);
++    }
++}
++
++static void
++Hacl_Standalone_Poly1305_32_poly1305_partial(
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *input,
++    uint64_t len1,
++    uint8_t *kr)
++{
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut = st;
++    uint32_t *r = scrut.r;
++    uint32_t *x0 = r;
++    FStar_UInt128_t k1 = load128_le(kr);
++    FStar_UInt128_t
++        k_clamped =
++            FStar_UInt128_logand(k1,
++                                 FStar_UInt128_logor(FStar_UInt128_shift_left(FStar_UInt128_uint64_to_uint128((uint64_t)0x0ffffffc0ffffffcU),
++                                                                              (uint32_t)64U),
++                                                     FStar_UInt128_uint64_to_uint128((uint64_t)0x0ffffffc0fffffffU)));
++    uint32_t r0 = (uint32_t)FStar_UInt128_uint128_to_uint64(k_clamped) & (uint32_t)0x3ffffffU;
++    uint32_t
++        r1 =
++            (uint32_t)FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(k_clamped, (uint32_t)26U)) & (uint32_t)0x3ffffffU;
++    uint32_t
++        r2 =
++            (uint32_t)FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(k_clamped, (uint32_t)52U)) & (uint32_t)0x3ffffffU;
++    uint32_t
++        r3 =
++            (uint32_t)FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(k_clamped, (uint32_t)78U)) & (uint32_t)0x3ffffffU;
++    uint32_t
++        r4 =
++            (uint32_t)FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(k_clamped, (uint32_t)104U)) & (uint32_t)0x3ffffffU;
++    x0[0U] = r0;
++    x0[1U] = r1;
++    x0[2U] = r2;
++    x0[3U] = r3;
++    x0[4U] = r4;
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut0 = st;
++    uint32_t *h = scrut0.h;
++    uint32_t *x00 = h;
++    x00[0U] = (uint32_t)0U;
++    x00[1U] = (uint32_t)0U;
++    x00[2U] = (uint32_t)0U;
++    x00[3U] = (uint32_t)0U;
++    x00[4U] = (uint32_t)0U;
++    Hacl_Standalone_Poly1305_32_poly1305_blocks(st, input, len1);
++}
++
++static void
++Hacl_Standalone_Poly1305_32_poly1305_complete(
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *m,
++    uint64_t len1,
++    uint8_t *k1)
++{
++    uint8_t *kr = k1;
++    uint64_t len16 = len1 >> (uint32_t)4U;
++    uint64_t rem16 = len1 & (uint64_t)0xfU;
++    uint8_t *part_input = m;
++    uint8_t *last_block = m + (uint32_t)((uint64_t)16U * len16);
++    Hacl_Standalone_Poly1305_32_poly1305_partial(st, part_input, len16, kr);
++    if (!(rem16 == (uint64_t)0U))
++        Hacl_Impl_Poly1305_32_poly1305_process_last_block(st, last_block, rem16);
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut = st;
++    uint32_t *h = scrut.h;
++    uint32_t *acc = h;
++    Hacl_Impl_Poly1305_32_poly1305_last_pass(acc);
++}
++
++static void
++Hacl_Standalone_Poly1305_32_crypto_onetimeauth_(
++    uint8_t *output,
++    uint8_t *input,
++    uint64_t len1,
++    uint8_t *k1)
++{
++    uint32_t buf[10U] = { 0U };
++    uint32_t *r = buf;
++    uint32_t *h = buf + (uint32_t)5U;
++    Hacl_Impl_Poly1305_32_State_poly1305_state st = Hacl_Impl_Poly1305_32_mk_state(r, h);
++    uint8_t *key_s = k1 + (uint32_t)16U;
++    Hacl_Standalone_Poly1305_32_poly1305_complete(st, input, len1, k1);
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut = st;
++    uint32_t *h5 = scrut.h;
++    uint32_t *acc = h5;
++    FStar_UInt128_t k_ = load128_le(key_s);
++    uint32_t h0 = acc[0U];
++    uint32_t h1 = acc[1U];
++    uint32_t h2 = acc[2U];
++    uint32_t h3 = acc[3U];
++    uint32_t h4 = acc[4U];
++    FStar_UInt128_t
++        acc_ =
++            FStar_UInt128_logor(FStar_UInt128_shift_left(FStar_UInt128_uint64_to_uint128((uint64_t)h4),
++                                                         (uint32_t)104U),
++                                FStar_UInt128_logor(FStar_UInt128_shift_left(FStar_UInt128_uint64_to_uint128((uint64_t)h3),
++                                                                             (uint32_t)78U),
++                                                    FStar_UInt128_logor(FStar_UInt128_shift_left(FStar_UInt128_uint64_to_uint128((uint64_t)h2),
++                                                                                                 (uint32_t)52U),
++                                                                        FStar_UInt128_logor(FStar_UInt128_shift_left(FStar_UInt128_uint64_to_uint128((uint64_t)h1),
++                                                                                                                     (uint32_t)26U),
++                                                                                            FStar_UInt128_uint64_to_uint128((uint64_t)h0)))));
++    FStar_UInt128_t mac_ = FStar_UInt128_add_mod(acc_, k_);
++    store128_le(output, mac_);
++}
++
++static void
++Hacl_Standalone_Poly1305_32_crypto_onetimeauth(
++    uint8_t *output,
++    uint8_t *input,
++    uint64_t len1,
++    uint8_t *k1)
++{
++    Hacl_Standalone_Poly1305_32_crypto_onetimeauth_(output, input, len1, k1);
++}
++
++void *
++Hacl_Poly1305_32_op_String_Access(FStar_Monotonic_HyperStack_mem h, uint8_t *b)
++{
++    return (void *)(uint8_t)0U;
++}
++
++Hacl_Impl_Poly1305_32_State_poly1305_state
++Hacl_Poly1305_32_mk_state(uint32_t *r, uint32_t *acc)
++{
++    return Hacl_Impl_Poly1305_32_mk_state(r, acc);
++}
++
++void
++Hacl_Poly1305_32_init(Hacl_Impl_Poly1305_32_State_poly1305_state st, uint8_t *k1)
++{
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut = st;
++    uint32_t *r = scrut.r;
++    uint32_t *x0 = r;
++    FStar_UInt128_t k10 = load128_le(k1);
++    FStar_UInt128_t
++        k_clamped =
++            FStar_UInt128_logand(k10,
++                                 FStar_UInt128_logor(FStar_UInt128_shift_left(FStar_UInt128_uint64_to_uint128((uint64_t)0x0ffffffc0ffffffcU),
++                                                                              (uint32_t)64U),
++                                                     FStar_UInt128_uint64_to_uint128((uint64_t)0x0ffffffc0fffffffU)));
++    uint32_t r0 = (uint32_t)FStar_UInt128_uint128_to_uint64(k_clamped) & (uint32_t)0x3ffffffU;
++    uint32_t
++        r1 =
++            (uint32_t)FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(k_clamped, (uint32_t)26U)) & (uint32_t)0x3ffffffU;
++    uint32_t
++        r2 =
++            (uint32_t)FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(k_clamped, (uint32_t)52U)) & (uint32_t)0x3ffffffU;
++    uint32_t
++        r3 =
++            (uint32_t)FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(k_clamped, (uint32_t)78U)) & (uint32_t)0x3ffffffU;
++    uint32_t
++        r4 =
++            (uint32_t)FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(k_clamped, (uint32_t)104U)) & (uint32_t)0x3ffffffU;
++    x0[0U] = r0;
++    x0[1U] = r1;
++    x0[2U] = r2;
++    x0[3U] = r3;
++    x0[4U] = r4;
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut0 = st;
++    uint32_t *h = scrut0.h;
++    uint32_t *x00 = h;
++    x00[0U] = (uint32_t)0U;
++    x00[1U] = (uint32_t)0U;
++    x00[2U] = (uint32_t)0U;
++    x00[3U] = (uint32_t)0U;
++    x00[4U] = (uint32_t)0U;
++}
++
++void *Hacl_Poly1305_32_empty_log = (void *)(uint8_t)0U;
++
++void
++Hacl_Poly1305_32_update_block(Hacl_Impl_Poly1305_32_State_poly1305_state st, uint8_t *m)
++{
++    Hacl_Impl_Poly1305_32_poly1305_update(st, m);
++}
++
++void
++Hacl_Poly1305_32_update(
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *m,
++    uint32_t len1)
++{
++    if (!(len1 == (uint32_t)0U)) {
++        uint8_t *block = m;
++        uint8_t *m_ = m + (uint32_t)16U;
++        uint32_t len2 = len1 - (uint32_t)1U;
++        Hacl_Poly1305_32_update_block(st, block);
++        Hacl_Poly1305_32_update(st, m_, len2);
++    }
++}
++
++void
++Hacl_Poly1305_32_update_last(
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *m,
++    uint32_t len1)
++{
++    if (!((uint64_t)len1 == (uint64_t)0U))
++        Hacl_Impl_Poly1305_32_poly1305_process_last_block(st, m, (uint64_t)len1);
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut = st;
++    uint32_t *h = scrut.h;
++    uint32_t *acc = h;
++    Hacl_Impl_Poly1305_32_poly1305_last_pass(acc);
++}
++
++void
++Hacl_Poly1305_32_finish(
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *mac,
++    uint8_t *k1)
++{
++    Hacl_Impl_Poly1305_32_State_poly1305_state scrut = st;
++    uint32_t *h = scrut.h;
++    uint32_t *acc = h;
++    FStar_UInt128_t k_ = load128_le(k1);
++    uint32_t h0 = acc[0U];
++    uint32_t h1 = acc[1U];
++    uint32_t h2 = acc[2U];
++    uint32_t h3 = acc[3U];
++    uint32_t h4 = acc[4U];
++    FStar_UInt128_t
++        acc_ =
++            FStar_UInt128_logor(FStar_UInt128_shift_left(FStar_UInt128_uint64_to_uint128((uint64_t)h4),
++                                                         (uint32_t)104U),
++                                FStar_UInt128_logor(FStar_UInt128_shift_left(FStar_UInt128_uint64_to_uint128((uint64_t)h3),
++                                                                             (uint32_t)78U),
++                                                    FStar_UInt128_logor(FStar_UInt128_shift_left(FStar_UInt128_uint64_to_uint128((uint64_t)h2),
++                                                                                                 (uint32_t)52U),
++                                                                        FStar_UInt128_logor(FStar_UInt128_shift_left(FStar_UInt128_uint64_to_uint128((uint64_t)h1),
++                                                                                                                     (uint32_t)26U),
++                                                                                            FStar_UInt128_uint64_to_uint128((uint64_t)h0)))));
++    FStar_UInt128_t mac_ = FStar_UInt128_add_mod(acc_, k_);
++    store128_le(mac, mac_);
++}
++
++void
++Hacl_Poly1305_32_crypto_onetimeauth(
++    uint8_t *output,
++    uint8_t *input,
++    uint64_t len1,
++    uint8_t *k1)
++{
++    Hacl_Standalone_Poly1305_32_crypto_onetimeauth(output, input, len1, k1);
++}
+diff --git a/security/nss/lib/freebl/verified/Hacl_Poly1305_32.h b/security/nss/lib/freebl/verified/Hacl_Poly1305_32.h
+new file mode 100644
+--- /dev/null
++++ b/security/nss/lib/freebl/verified/Hacl_Poly1305_32.h
+@@ -0,0 +1,103 @@
++/* Copyright 2016-2017 INRIA and Microsoft Corporation
++ *
++ * Licensed under the Apache License, Version 2.0 (the "License");
++ * you may not use this file except in compliance with the License.
++ * You may obtain a copy of the License at
++ *
++ *     http://www.apache.org/licenses/LICENSE-2.0
++ *
++ * Unless required by applicable law or agreed to in writing, software
++ * distributed under the License is distributed on an "AS IS" BASIS,
++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
++ * See the License for the specific language governing permissions and
++ * limitations under the License.
++ */
++
++#include "kremlib.h"
++#ifndef __Hacl_Poly1305_32_H
++#define __Hacl_Poly1305_32_H
++
++typedef uint32_t Hacl_Bignum_Constants_limb;
++
++typedef uint64_t Hacl_Bignum_Constants_wide;
++
++typedef uint64_t Hacl_Bignum_Wide_t;
++
++typedef uint32_t Hacl_Bignum_Limb_t;
++
++typedef void *Hacl_Impl_Poly1305_32_State_log_t;
++
++typedef uint8_t *Hacl_Impl_Poly1305_32_State_uint8_p;
++
++typedef uint32_t *Hacl_Impl_Poly1305_32_State_bigint;
++
++typedef void *Hacl_Impl_Poly1305_32_State_seqelem;
++
++typedef uint32_t *Hacl_Impl_Poly1305_32_State_elemB;
++
++typedef uint8_t *Hacl_Impl_Poly1305_32_State_wordB;
++
++typedef uint8_t *Hacl_Impl_Poly1305_32_State_wordB_16;
++
++typedef struct
++{
++    uint32_t *r;
++    uint32_t *h;
++} Hacl_Impl_Poly1305_32_State_poly1305_state;
++
++typedef void *Hacl_Impl_Poly1305_32_log_t;
++
++typedef uint32_t *Hacl_Impl_Poly1305_32_bigint;
++
++typedef uint8_t *Hacl_Impl_Poly1305_32_uint8_p;
++
++typedef uint32_t *Hacl_Impl_Poly1305_32_elemB;
++
++typedef uint8_t *Hacl_Impl_Poly1305_32_wordB;
++
++typedef uint8_t *Hacl_Impl_Poly1305_32_wordB_16;
++
++typedef uint8_t *Hacl_Poly1305_32_uint8_p;
++
++typedef uint64_t Hacl_Poly1305_32_uint64_t;
++
++void *Hacl_Poly1305_32_op_String_Access(FStar_Monotonic_HyperStack_mem h, uint8_t *b);
++
++typedef uint8_t *Hacl_Poly1305_32_key;
++
++typedef Hacl_Impl_Poly1305_32_State_poly1305_state Hacl_Poly1305_32_state;
++
++Hacl_Impl_Poly1305_32_State_poly1305_state
++Hacl_Poly1305_32_mk_state(uint32_t *r, uint32_t *acc);
++
++void Hacl_Poly1305_32_init(Hacl_Impl_Poly1305_32_State_poly1305_state st, uint8_t *k1);
++
++extern void *Hacl_Poly1305_32_empty_log;
++
++void Hacl_Poly1305_32_update_block(Hacl_Impl_Poly1305_32_State_poly1305_state st, uint8_t *m);
++
++void
++Hacl_Poly1305_32_update(
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *m,
++    uint32_t len1);
++
++void
++Hacl_Poly1305_32_update_last(
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *m,
++    uint32_t len1);
++
++void
++Hacl_Poly1305_32_finish(
++    Hacl_Impl_Poly1305_32_State_poly1305_state st,
++    uint8_t *mac,
++    uint8_t *k1);
++
++void
++Hacl_Poly1305_32_crypto_onetimeauth(
++    uint8_t *output,
++    uint8_t *input,
++    uint64_t len1,
++    uint8_t *k1);
++#endif
+diff --git a/security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpdefaultclient.c b/security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpdefaultclient.c
+--- a/security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpdefaultclient.c
++++ b/security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpdefaultclient.c
+@@ -65,32 +65,32 @@ static const PKIX_UInt32 httpprotocolLen
+  *  "client"
+  *      The address of the HttpDefaultClient object. Must be non-NULL.
+  *  "bytesRead"
+  *      The UInt32 number of bytes received in the latest read.
+  *  "pKeepGoing"
+  *      The address at which the Boolean state machine flag is stored to
+  *      indicate whether processing can continue without further input.
+  *      Must be non-NULL.
+- *  "plContext"
++ *  "plCtx"
+  *      Platform-specific context pointer.
+  * THREAD SAFETY:
+  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
+  * RETURNS:
+  *  Returns NULL if the function succeeds.
+  *  Returns a HttpDefaultClient Error if the function fails in a
+  *      non-fatal way.
+  *  Returns a Fatal Error if the function fails in an unrecoverable way.
+  */
+ static PKIX_Error *
+ pkix_pl_HttpDefaultClient_HdrCheckComplete(
+         PKIX_PL_HttpDefaultClient *client,
+         PKIX_UInt32 bytesRead,
+         PKIX_Boolean *pKeepGoing,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_UInt32 alreadyScanned = 0;
+         PKIX_UInt32 comp = 0;
+         PKIX_UInt32 headerLength = 0;
+         PKIX_Int32 contentLength = HTTP_UNKNOWN_CONTENT_LENGTH;
+         char *eoh = NULL;
+         char *statusLineEnd = NULL;
+         char *space = NULL;
+@@ -137,17 +137,17 @@ pkix_pl_HttpDefaultClient_HdrCheckComple
+                 *pKeepGoing = PKIX_TRUE;
+                 goto cleanup;
+         }
+ 
+         /* Yes. Calculate how many bytes in header (not counting eohMarker) */
+         headerLength = (eoh - client->rcvBuf);
+ 
+         /* allocate space to copy header (and for the NULL terminator) */
+-        PKIX_CHECK(PKIX_PL_Malloc(headerLength + 1, (void **)&copy, plContext),
++        PKIX_CHECK(PKIX_PL_Malloc(headerLength + 1, (void **)&copy, plCtx),
+                 PKIX_MALLOCFAILED);
+ 
+         /* copy header data before we corrupt it (by storing NULLs) */
+         PORT_Memcpy(copy, client->rcvBuf, headerLength);
+ 	/* Store the NULL terminator */
+ 	copy[headerLength] = '\0';
+ 	client->rcvHeaders = copy;
+ 
+@@ -296,27 +296,27 @@ pkix_pl_HttpDefaultClient_HdrCheckComple
+              } else {
+                  client->connectStatus = HTTP_COMPLETE;
+                  *pKeepGoing = PKIX_FALSE;
+              }
+          }
+  
+          if (contentLength > 0) {
+              /* allocate a buffer of size contentLength  for the content */
+-             PKIX_CHECK(PKIX_PL_Malloc(contentLength, (void **)&body, plContext),
++             PKIX_CHECK(PKIX_PL_Malloc(contentLength, (void **)&body, plCtx),
+                         PKIX_MALLOCFAILED);
+              
+              /* copy any remaining bytes in current buffer into new buffer */
+              if (client->filledupBytes > 0) {
+                  PORT_Memcpy(body, &(client->rcvBuf[headerLength]),
+                              client->filledupBytes);
+              }
+          }
+  
+-         PKIX_CHECK(PKIX_PL_Free(client->rcvBuf, plContext),
++         PKIX_CHECK(PKIX_PL_Free(client->rcvBuf, plCtx),
+                     PKIX_FREEFAILED);
+          client->rcvBuf = body;
+ 
+ cleanup:
+ 
+         PKIX_RETURN(HTTPDEFAULTCLIENT);
+ }
+ 
+@@ -335,44 +335,44 @@ cleanup:
+  *  "host"
+  *      The name of the server with which we hope to exchange messages. Must
+  *      be non-NULL.
+  *  "portnum"
+  *      The port number to be used for our connection to the server.
+  *  "pClient"
+  *      The address at which the created HttpDefaultClient is to be stored.
+  *      Must be non-NULL.
+- *  "plContext"
++ *  "plCtx"
+  *      Platform-specific context pointer.
+  * THREAD SAFETY:
+  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
+  * RETURNS:
+  *  Returns NULL if the function succeeds.
+  *  Returns a HttpDefaultClient Error if the function fails in
+  *      a non-fatal way.
+  *  Returns a Fatal Error if the function fails in an unrecoverable way.
+  */
+ static PKIX_Error *
+ pkix_pl_HttpDefaultClient_Create(
+         const char *host,
+         PRUint16 portnum,
+         PKIX_PL_HttpDefaultClient **pClient,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_PL_HttpDefaultClient *client = NULL;
+ 
+         PKIX_ENTER(HTTPDEFAULTCLIENT, "PKIX_PL_HttpDefaultClient_Create");
+         PKIX_NULLCHECK_TWO(pClient, host);
+ 
+         /* allocate an HttpDefaultClient */
+         PKIX_CHECK(PKIX_PL_Object_Alloc
+                 (PKIX_HTTPDEFAULTCLIENT_TYPE,
+                 sizeof (PKIX_PL_HttpDefaultClient),
+                 (PKIX_PL_Object **)&client,
+-                plContext),
++                plCtx),
+                 PKIX_COULDNOTCREATEHTTPDEFAULTCLIENTOBJECT);
+ 
+         /* Client timeout is overwritten in HttpDefaultClient_RequestCreate
+          * function. Default value will be ignored. */
+         client->timeout = 0;
+         client->connectStatus = HTTP_NOT_CONNECTED;
+         client->portnum = portnum;
+         client->bytesToWrite = 0;
+@@ -403,20 +403,20 @@ pkix_pl_HttpDefaultClient_Create(
+         client->send_http_data = NULL;
+         client->rcv_http_response_code = NULL;
+         client->rcv_http_content_type = NULL;
+         client->rcv_http_headers = NULL;
+         client->rcv_http_data = NULL;
+         client->socket = NULL;
+ 
+         /*
+-         * The HttpClient API does not include a plContext argument in its
++         * The HttpClient API does not include a plCtx argument in its
+          * function calls. Save it here.
+          */
+-        client->plContext = plContext;
++        client->plContext = plCtx;
+ 
+         *pClient = client;
+ 
+ cleanup:
+         if (PKIX_ERROR_RECEIVED) {
+                 PKIX_DECREF(client);
+         }
+ 
+@@ -425,47 +425,47 @@ cleanup:
+ 
+ /*
+  * FUNCTION: pkix_pl_HttpDefaultClient_Destroy
+  * (see comments for PKIX_PL_DestructorCallback in pkix_pl_system.h)
+  */
+ static PKIX_Error *
+ pkix_pl_HttpDefaultClient_Destroy(
+         PKIX_PL_Object *object,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_PL_HttpDefaultClient *client = NULL;
+ 
+         PKIX_ENTER(HTTPDEFAULTCLIENT, "pkix_pl_HttpDefaultClient_Destroy");
+         PKIX_NULLCHECK_ONE(object);
+ 
+         PKIX_CHECK(pkix_CheckType
+-                    (object, PKIX_HTTPDEFAULTCLIENT_TYPE, plContext),
++                    (object, PKIX_HTTPDEFAULTCLIENT_TYPE, plCtx),
+                     PKIX_OBJECTNOTANHTTPDEFAULTCLIENT);
+ 
+         client = (PKIX_PL_HttpDefaultClient *)object;
+ 
+         if (client->rcvHeaders) {
+-            PKIX_PL_Free(client->rcvHeaders, plContext);
++            PKIX_PL_Free(client->rcvHeaders, plCtx);
+             client->rcvHeaders = NULL;
+         }
+         if (client->rcvContentType) {
+             PORT_Free(client->rcvContentType);
+             client->rcvContentType = NULL;
+         }
+         if (client->GETBuf != NULL) {
+                 PR_smprintf_free(client->GETBuf);
+                 client->GETBuf = NULL;
+         }
+         if (client->POSTBuf != NULL) {
+-                PKIX_PL_Free(client->POSTBuf, plContext);
++                PKIX_PL_Free(client->POSTBuf, plCtx);
+                 client->POSTBuf = NULL;
+         }
+         if (client->rcvBuf != NULL) {
+-                PKIX_PL_Free(client->rcvBuf, plContext);
++                PKIX_PL_Free(client->rcvBuf, plCtx);
+                 client->rcvBuf = NULL;
+         }
+         if (client->host) {
+                 PORT_Free(client->host);
+                 client->host = NULL;
+         }
+         if (client->path) {
+                 PORT_Free(client->path);
+@@ -488,17 +488,17 @@ cleanup:
+  * THREAD SAFETY:
+  *  Not Thread Safe - for performance and complexity reasons
+  *
+  *  Since this function is only called by PKIX_PL_Initialize, which should
+  *  only be called once, it is acceptable that this function is not
+  *  thread-safe.
+  */
+ PKIX_Error *
+-pkix_pl_HttpDefaultClient_RegisterSelf(void *plContext)
++pkix_pl_HttpDefaultClient_RegisterSelf(void *plCtx)
+ {
+         extern pkix_ClassTable_Entry systemClasses[PKIX_NUMTYPES];
+         pkix_ClassTable_Entry *entry =
+             &systemClasses[PKIX_HTTPDEFAULTCLIENT_TYPE];
+ 
+         PKIX_ENTER(HTTPDEFAULTCLIENT,
+                 "pkix_pl_HttpDefaultClient_RegisterSelf");
+ 
+@@ -524,45 +524,45 @@ pkix_pl_HttpDefaultClient_RegisterSelf(v
+  *
+  * PARAMETERS:
+  *  "client"
+  *      The address of the HttpDefaultClient object. Must be non-NULL.
+  *  "pKeepGoing"
+  *      The address at which the Boolean state machine flag is stored to
+  *      indicate whether processing can continue without further input.
+  *      Must be non-NULL.
+- *  "plContext"
++ *  "plCtx"
+  *      Platform-specific context pointer.
+  * THREAD SAFETY:
+  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
+  * RETURNS:
+  *  Returns NULL if the function succeeds.
+  *  Returns a HttpDefaultClient Error if the function fails in a
+  *      non-fatal way.
+  *  Returns a Fatal Error if the function fails in an unrecoverable way.
+  */
+ static PKIX_Error *
+ pkix_pl_HttpDefaultClient_ConnectContinue(
+         PKIX_PL_HttpDefaultClient *client,
+         PKIX_Boolean *pKeepGoing,
+-        void *plContext)
++        void *plCtx)
+ {
+         PRErrorCode status;
+         PKIX_Boolean keepGoing = PKIX_FALSE;
+         PKIX_PL_Socket_Callback *callbackList = NULL;
+ 
+         PKIX_ENTER
+                 (HTTPDEFAULTCLIENT,
+                 "pkix_pl_HttpDefaultClient_ConnectContinue");
+         PKIX_NULLCHECK_ONE(client);
+ 
+         callbackList = (PKIX_PL_Socket_Callback *)client->callbackList;
+ 
+         PKIX_CHECK(callbackList->connectcontinueCallback
+-                (client->socket, &status, plContext),
++                (client->socket, &status, plCtx),
+                 PKIX_SOCKETCONNECTCONTINUEFAILED);
+ 
+         if (status == 0) {
+                 client->connectStatus = HTTP_CONNECTED;
+                 keepGoing = PKIX_TRUE;
+         } else if (status != PR_IN_PROGRESS_ERROR) {
+                 PKIX_ERROR(PKIX_UNEXPECTEDERRORINESTABLISHINGCONNECTION);
+         }
+@@ -590,32 +590,32 @@ cleanup:
+  *      The address of the HttpDefaultClient object. Must be non-NULL.
+  *  "pKeepGoing"
+  *      The address at which the Boolean state machine flag is stored to
+  *      indicate whether processing can continue without further input.
+  *      Must be non-NULL.
+  *  "pBytesTransferred"
+  *      The address at which the number of bytes sent is stored. Must be
+  *      non-NULL.
+- *  "plContext"
++ *  "plCtx"
+  *      Platform-specific context pointer.
+  * THREAD SAFETY:
+  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
+  * RETURNS:
+  *  Returns NULL if the function succeeds.
+  *  Returns a HttpDefaultClient Error if the function fails in a
+  *      non-fatal way.
+  *  Returns a Fatal Error if the function fails in an unrecoverable way.
+  */
+ static PKIX_Error *
+ pkix_pl_HttpDefaultClient_Send(
+         PKIX_PL_HttpDefaultClient *client,
+         PKIX_Boolean *pKeepGoing,
+         PKIX_UInt32 *pBytesTransferred,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_Int32 bytesWritten = 0;
+         PKIX_Int32 lenToWrite = 0;
+         PKIX_PL_Socket_Callback *callbackList = NULL;
+         char *dataToWrite = NULL;
+ 
+         PKIX_ENTER(HTTPDEFAULTCLIENT, "pkix_pl_HttpDefaultClient_Send");
+         PKIX_NULLCHECK_THREE(client, pKeepGoing, pBytesTransferred);
+@@ -635,17 +635,17 @@ pkix_pl_HttpDefaultClient_Send(
+ 
+                 callbackList = (PKIX_PL_Socket_Callback *)client->callbackList;
+ 
+                 PKIX_CHECK(callbackList->sendCallback
+                         (client->socket,
+                         dataToWrite,
+                         lenToWrite,
+                         &bytesWritten,
+-                        plContext),
++                        plCtx),
+                         PKIX_SOCKETSENDFAILED);
+ 
+                 client->rcvBuf = NULL;
+                 client->capacity = 0;
+                 client->filledupBytes = 0;
+ 
+                 /*
+                  * If the send completed we can proceed to try for the
+@@ -685,45 +685,45 @@ cleanup:
+  *      The address of the HttpDefaultClient object. Must be non-NULL.
+  *  "pKeepGoing"
+  *      The address at which the Boolean state machine flag is stored to
+  *      indicate whether processing can continue without further input.
+  *      Must be non-NULL.
+  *  "pBytesTransferred"
+  *      The address at which the number of bytes sent is stored. Must be
+  *      non-NULL.
+- *  "plContext"
++ *  "plCtx"
+  *      Platform-specific context pointer.
+  * THREAD SAFETY:
+  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
+  * RETURNS:
+  *  Returns NULL if the function succeeds.
+  *  Returns a HttpDefaultClient Error if the function fails in a
+  *      non-fatal way.
+  *  Returns a Fatal Error if the function fails in an unrecoverable way.
+  */
+ static PKIX_Error *
+ pkix_pl_HttpDefaultClient_SendContinue(
+         PKIX_PL_HttpDefaultClient *client,
+         PKIX_Boolean *pKeepGoing,
+         PKIX_UInt32 *pBytesTransferred,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_Int32 bytesWritten = 0;
+         PKIX_PL_Socket_Callback *callbackList = NULL;
+ 
+         PKIX_ENTER(HTTPDEFAULTCLIENT, "pkix_pl_HttpDefaultClient_SendContinue");
+         PKIX_NULLCHECK_THREE(client, pKeepGoing, pBytesTransferred);
+ 
+         *pKeepGoing = PKIX_FALSE;
+ 
+         callbackList = (PKIX_PL_Socket_Callback *)client->callbackList;
+ 
+         PKIX_CHECK(callbackList->pollCallback
+-                (client->socket, &bytesWritten, NULL, plContext),
++                (client->socket, &bytesWritten, NULL, plCtx),
+                 PKIX_SOCKETPOLLFAILED);
+ 
+         /*
+          * If the send completed we can proceed to try for the
+          * response. If the send did not complete we will have
+          * continue to poll.
+          */
+         if (bytesWritten >= 0) {
+@@ -747,31 +747,31 @@ cleanup:
+  *
+  * PARAMETERS:
+  *  "client"
+  *      The address of the HttpDefaultClient object. Must be non-NULL.
+  *  "pKeepGoing"
+  *      The address at which the Boolean state machine flag is stored to
+  *      indicate whether processing can continue without further input.
+  *      Must be non-NULL.
+- *  "plContext"
++ *  "plCtx"
+  *      Platform-specific context pointer.
+  * THREAD SAFETY:
+  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
+  * RETURNS:
+  *  Returns NULL if the function succeeds.
+  *  Returns a HttpDefaultClient Error if the function fails in a
+  *      non-fatal way.
+  *  Returns a Fatal Error if the function fails in an unrecoverable way.
+  */
+ static PKIX_Error *
+ pkix_pl_HttpDefaultClient_RecvHdr(
+         PKIX_PL_HttpDefaultClient *client,
+         PKIX_Boolean *pKeepGoing,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_UInt32 bytesToRead = 0;
+         PKIX_Int32 bytesRead = 0;
+         PKIX_PL_Socket_Callback *callbackList = NULL;
+ 
+         PKIX_ENTER(HTTPDEFAULTCLIENT, "pkix_pl_HttpDefaultClient_RecvHdr");
+         PKIX_NULLCHECK_TWO(client, pKeepGoing);
+ 
+@@ -782,38 +782,38 @@ pkix_pl_HttpDefaultClient_RecvHdr(
+          * reading again if necessary, until we have read the end-of-header
+          * marker, "\r\n\r\n", or have reached our maximum.
+          */
+         client->capacity += HTTP_HEADER_BUFSIZE;
+         PKIX_CHECK(PKIX_PL_Realloc
+                 (client->rcvBuf,
+                 client->capacity,
+                 (void **)&(client->rcvBuf),
+-                plContext),
++                plCtx),
+                 PKIX_REALLOCFAILED);
+ 
+         bytesToRead = client->capacity - client->filledupBytes;
+ 
+         callbackList = (PKIX_PL_Socket_Callback *)client->callbackList;
+ 
+         PKIX_CHECK(callbackList->recvCallback
+                 (client->socket,
+                 (void *)&(client->rcvBuf[client->filledupBytes]),
+                 bytesToRead,
+                 &bytesRead,
+-                plContext),
++                plCtx),
+                 PKIX_SOCKETRECVFAILED);
+ 
+         if (bytesRead > 0) {
+             /* client->filledupBytes will be adjusted by
+              * pkix_pl_HttpDefaultClient_HdrCheckComplete */
+             PKIX_CHECK(
+                 pkix_pl_HttpDefaultClient_HdrCheckComplete(client, bytesRead,
+                                                            pKeepGoing,
+-                                                           plContext),
++                                                           plCtx),
+                        PKIX_HTTPDEFAULTCLIENTHDRCHECKCOMPLETEFAILED);
+         } else {
+             client->connectStatus = HTTP_RECV_HDR_PENDING;
+             *pKeepGoing = PKIX_FALSE;
+         }
+ 
+ cleanup:
+         PKIX_RETURN(HTTPDEFAULTCLIENT);
+@@ -829,51 +829,51 @@ cleanup:
+  *
+  * PARAMETERS:
+  *  "client"
+  *      The address of the HttpDefaultClient object. Must be non-NULL.
+  *  "pKeepGoing"
+  *      The address at which the Boolean state machine flag is stored to
+  *      indicate whether processing can continue without further input.
+  *      Must be non-NULL.
+- *  "plContext"
++ *  "plCtx"
+  *      Platform-specific context pointer.
+  * THREAD SAFETY:
+  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
+  * RETURNS:
+  *  Returns NULL if the function succeeds.
+  *  Returns a HttpDefaultClient Error if the function fails in a
+  *      non-fatal way.
+  *  Returns a Fatal Error if the function fails in an unrecoverable way.
+  */
+ static PKIX_Error *
+ pkix_pl_HttpDefaultClient_RecvHdrContinue(
+         PKIX_PL_HttpDefaultClient *client,
+         PKIX_Boolean *pKeepGoing,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_Int32 bytesRead = 0;
+         PKIX_PL_Socket_Callback *callbackList = NULL;
+ 
+         PKIX_ENTER
+                 (HTTPDEFAULTCLIENT,
+                 "pkix_pl_HttpDefaultClient_RecvHdrContinue");
+         PKIX_NULLCHECK_TWO(client, pKeepGoing);
+ 
+         callbackList = (PKIX_PL_Socket_Callback *)client->callbackList;
+ 
+         PKIX_CHECK(callbackList->pollCallback
+-                (client->socket, NULL, &bytesRead, plContext),
++                (client->socket, NULL, &bytesRead, plCtx),
+                 PKIX_SOCKETPOLLFAILED);
+ 
+         if (bytesRead > 0) {
+                 client->filledupBytes += bytesRead;
+ 
+                 PKIX_CHECK(pkix_pl_HttpDefaultClient_HdrCheckComplete
+-                        (client, bytesRead, pKeepGoing, plContext),
++                        (client, bytesRead, pKeepGoing, plCtx),
+                         PKIX_HTTPDEFAULTCLIENTHDRCHECKCOMPLETEFAILED);
+ 
+         } else {
+ 
+                 *pKeepGoing = PKIX_FALSE;
+ 
+         }
+ 
+@@ -892,31 +892,31 @@ cleanup:
+  *
+  * PARAMETERS:
+  *  "client"
+  *      The address of the HttpDefaultClient object. Must be non-NULL.
+  *  "pKeepGoing"
+  *      The address at which the Boolean state machine flag is stored to
+  *      indicate whether processing can continue without further input.
+  *      Must be non-NULL.
+- *  "plContext"
++ *  "plCtx"
+  *      Platform-specific context pointer.
+  * THREAD SAFETY:
+  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
+  * RETURNS:
+  *  Returns NULL if the function succeeds.
+  *  Returns a HttpDefaultClient Error if the function fails in a
+  *      non-fatal way.
+  *  Returns a Fatal Error if the function fails in an unrecoverable way.
+  */
+ static PKIX_Error *
+ pkix_pl_HttpDefaultClient_RecvBody(
+         PKIX_PL_HttpDefaultClient *client,
+         PKIX_Boolean *pKeepGoing,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_Int32 bytesRead = 0;
+         PKIX_Int32 bytesToRead = 0;
+         PKIX_PL_Socket_Callback *callbackList = NULL;
+ 
+         PKIX_ENTER(HTTPDEFAULTCLIENT, "pkix_pl_HttpDefaultClient_RecvBody");
+         PKIX_NULLCHECK_TWO(client, pKeepGoing);
+ 
+@@ -947,37 +947,37 @@ pkix_pl_HttpDefaultClient_RecvBody(
+                     client->connectStatus = HTTP_ERROR;
+                     *pKeepGoing = PKIX_FALSE;
+                     goto cleanup;
+                 }
+                 if (client->capacity < newLength) {
+                     client->capacity = newLength;
+                     PKIX_CHECK(
+                         PKIX_PL_Realloc(client->rcvBuf, newLength,
+-                                        (void**)&client->rcvBuf, plContext),
++                                        (void**)&client->rcvBuf, plCtx),
+                         PKIX_REALLOCFAILED);
+                     freeBuffSize = client->capacity -
+                         client->filledupBytes;
+                 }
+             }
+             bytesToRead = freeBuffSize;
+         }
+ 
+         /* Use poll callback if waiting on non-blocking IO */
+         if (client->connectStatus == HTTP_RECV_BODY_PENDING) {
+             PKIX_CHECK(callbackList->pollCallback
+-                       (client->socket, NULL, &bytesRead, plContext),
++                       (client->socket, NULL, &bytesRead, plCtx),
+                        PKIX_SOCKETPOLLFAILED);
+         } else {
+             PKIX_CHECK(callbackList->recvCallback
+                        (client->socket,
+                         (void *)&(client->rcvBuf[client->filledupBytes]),
+                         bytesToRead,
+                         &bytesRead,
+-                        plContext),
++                        plCtx),
+                        PKIX_SOCKETRECVFAILED);
+         }
+ 
+         /* If bytesRead < 0, an error will be thrown by recvCallback, so
+          * need to handle >= 0 cases. */
+ 
+         /* bytesRead == 0 - IO was blocked. */
+         if (bytesRead == 0) {
+@@ -1021,68 +1021,68 @@ cleanup:
+  *
+  *  This function is the state machine dispatcher for the HttpDefaultClient
+  *  pointed to by "client". Results are returned by changes to various fields
+  *  in the context.
+  *
+  * PARAMETERS:
+  *  "client"
+  *      The address of the HttpDefaultClient object. Must be non-NULL.
+- *  "plContext"
++ *  "plCtx"
+  *      Platform-specific context pointer.
+  * THREAD SAFETY:
+  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
+  * RETURNS:
+  *  Returns NULL if the function succeeds.
+  *  Returns a HttpDefaultClient Error if the function fails in a
+  *      non-fatal way.
+  *  Returns a Fatal Error if the function fails in an unrecoverable way.
+  */
+ static PKIX_Error *
+ pkix_pl_HttpDefaultClient_Dispatch(
+         PKIX_PL_HttpDefaultClient *client,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_UInt32 bytesTransferred = 0;
+         PKIX_Boolean keepGoing = PKIX_TRUE;
+ 
+         PKIX_ENTER(HTTPDEFAULTCLIENT, "pkix_pl_HttpDefaultClient_Dispatch");
+         PKIX_NULLCHECK_ONE(client);
+ 
+         while (keepGoing) {
+                 switch (client->connectStatus) {
+                 case HTTP_CONNECT_PENDING:
+                     PKIX_CHECK(pkix_pl_HttpDefaultClient_ConnectContinue
+-                        (client, &keepGoing, plContext),
++                        (client, &keepGoing, plCtx),
+                         PKIX_HTTPDEFAULTCLIENTCONNECTCONTINUEFAILED);
+                     break;
+                 case HTTP_CONNECTED:
+                     PKIX_CHECK(pkix_pl_HttpDefaultClient_Send
+-                        (client, &keepGoing, &bytesTransferred, plContext),
++                        (client, &keepGoing, &bytesTransferred, plCtx),
+                         PKIX_HTTPDEFAULTCLIENTSENDFAILED);
+                     break;
+                 case HTTP_SEND_PENDING:
+                     PKIX_CHECK(pkix_pl_HttpDefaultClient_SendContinue
+-                        (client, &keepGoing, &bytesTransferred, plContext),
++                        (client, &keepGoing, &bytesTransferred, plCtx),
+                         PKIX_HTTPDEFAULTCLIENTSENDCONTINUEFAILED);
+                     break;
+                 case HTTP_RECV_HDR:
+                     PKIX_CHECK(pkix_pl_HttpDefaultClient_RecvHdr
+-                        (client, &keepGoing, plContext),
++                        (client, &keepGoing, plCtx),
+                         PKIX_HTTPDEFAULTCLIENTRECVHDRFAILED);
+                     break;
+                 case HTTP_RECV_HDR_PENDING:
+                     PKIX_CHECK(pkix_pl_HttpDefaultClient_RecvHdrContinue
+-                        (client, &keepGoing, plContext),
++                        (client, &keepGoing, plCtx),
+                         PKIX_HTTPDEFAULTCLIENTRECVHDRCONTINUEFAILED);
+                     break;
+                 case HTTP_RECV_BODY:
+                 case HTTP_RECV_BODY_PENDING:
+                     PKIX_CHECK(pkix_pl_HttpDefaultClient_RecvBody
+-                        (client, &keepGoing, plContext),
++                        (client, &keepGoing, plCtx),
+                         PKIX_HTTPDEFAULTCLIENTRECVBODYFAILED);
+                     break;
+                 case HTTP_ERROR:
+                 case HTTP_COMPLETE:
+                     keepGoing = PKIX_FALSE;
+                     break;
+                 case HTTP_NOT_CONNECTED:
+                 default:
+@@ -1101,51 +1101,51 @@ cleanup:
+  * The functions that return PKIX_Error* are the libpkix implementations.
+  */
+ 
+ PKIX_Error *
+ pkix_pl_HttpDefaultClient_CreateSession(
+         const char *host,
+         PRUint16 portnum,
+         SEC_HTTP_SERVER_SESSION *pSession,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_PL_HttpDefaultClient *client = NULL;
+ 
+         PKIX_ENTER
+                 (HTTPDEFAULTCLIENT, "pkix_pl_HttpDefaultClient_CreateSession");
+         PKIX_NULLCHECK_TWO(host, pSession);
+ 
+         PKIX_CHECK(pkix_pl_HttpDefaultClient_Create
+-                (host, portnum, &client, plContext),
++                (host, portnum, &client, plCtx),
+                 PKIX_HTTPDEFAULTCLIENTCREATEFAILED);
+ 
+         *pSession = (SEC_HTTP_SERVER_SESSION)client;
+ 
+ cleanup:
+ 
+         PKIX_RETURN(HTTPDEFAULTCLIENT);
+ 
+ }
+ 
+ PKIX_Error *
+ pkix_pl_HttpDefaultClient_KeepAliveSession(
+         SEC_HTTP_SERVER_SESSION session,
+         PRPollDesc **pPollDesc,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_ENTER
+                 (HTTPDEFAULTCLIENT,
+                 "pkix_pl_HttpDefaultClient_KeepAliveSession");
+         PKIX_NULLCHECK_TWO(session, pPollDesc);
+ 
+         PKIX_CHECK(pkix_CheckType
+                 ((PKIX_PL_Object *)session,
+                 PKIX_HTTPDEFAULTCLIENT_TYPE,
+-                plContext),
++                plCtx),
+                 PKIX_SESSIONNOTANHTTPDEFAULTCLIENT);
+ 
+         /* XXX Not implemented */
+ 
+ cleanup:
+ 
+         PKIX_RETURN(HTTPDEFAULTCLIENT);
+ 
+@@ -1154,32 +1154,32 @@ cleanup:
+ PKIX_Error *
+ pkix_pl_HttpDefaultClient_RequestCreate(
+         SEC_HTTP_SERVER_SESSION session,
+         const char *http_protocol_variant, /* usually "http" */
+         const char *path_and_query_string,
+         const char *http_request_method, 
+         const PRIntervalTime timeout, 
+         SEC_HTTP_REQUEST_SESSION *pRequest,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_PL_HttpDefaultClient *client = NULL;
+         PKIX_PL_Socket *socket = NULL;
+         PKIX_PL_Socket_Callback *callbackList = NULL;
+         PRFileDesc *fileDesc = NULL;
+         PRErrorCode status = 0;
+ 
+         PKIX_ENTER
+                 (HTTPDEFAULTCLIENT, "pkix_pl_HttpDefaultClient_RequestCreate");
+         PKIX_NULLCHECK_TWO(session, pRequest);
+ 
+         PKIX_CHECK(pkix_CheckType
+                 ((PKIX_PL_Object *)session,
+                 PKIX_HTTPDEFAULTCLIENT_TYPE,
+-                plContext),
++                plCtx),
+                 PKIX_SESSIONNOTANHTTPDEFAULTCLIENT);
+ 
+         client = (PKIX_PL_HttpDefaultClient *)session;
+ 
+         /* We only know how to do http */
+         if (PORT_Strncasecmp(http_protocol_variant, "http", 4) != 0) {
+                 PKIX_ERROR(PKIX_UNRECOGNIZEDPROTOCOLREQUESTED);
+         }
+@@ -1207,39 +1207,39 @@ pkix_pl_HttpDefaultClient_RequestCreate(
+ 
+ #if 0
+ 	PKIX_CHECK(pkix_HttpCertStore_FindSocketConnection
+                 (timeout,
+                 "variation.red.iplanet.com", /* (char *)client->host, */
+                 2001,   /* client->portnum, */
+                 &status,
+                 &socket,
+-                plContext),
++                plCtx),
+ 		PKIX_HTTPCERTSTOREFINDSOCKETCONNECTIONFAILED);
+ #else
+ 	PKIX_CHECK(pkix_HttpCertStore_FindSocketConnection
+                 (timeout,
+                 (char *)client->host,
+                 client->portnum,
+                 &status,
+                 &socket,
+-                plContext),
++                plCtx),
+ 		PKIX_HTTPCERTSTOREFINDSOCKETCONNECTIONFAILED);
+ #endif
+ 
+         client->socket = socket;
+ 
+         PKIX_CHECK(pkix_pl_Socket_GetCallbackList
+-                (socket, &callbackList, plContext),
++                (socket, &callbackList, plCtx),
+                 PKIX_SOCKETGETCALLBACKLISTFAILED);
+ 
+         client->callbackList = (void *)callbackList;
+ 
+         PKIX_CHECK(pkix_pl_Socket_GetPRFileDesc
+-                (socket, &fileDesc, plContext),
++                (socket, &fileDesc, plCtx),
+                 PKIX_SOCKETGETPRFILEDESCFAILED);
+ 
+         client->pollDesc.fd = fileDesc;
+         client->pollDesc.in_flags = 0;
+         client->pollDesc.out_flags = 0;
+ 
+         client->send_http_data = NULL;
+         client->send_http_data_len = 0;
+@@ -1259,29 +1259,29 @@ cleanup:
+ }
+ 
+ PKIX_Error *
+ pkix_pl_HttpDefaultClient_SetPostData(
+         SEC_HTTP_REQUEST_SESSION request,
+         const char *http_data, 
+         const PRUint32 http_data_len,
+         const char *http_content_type,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_PL_HttpDefaultClient *client = NULL;
+ 
+         PKIX_ENTER
+                 (HTTPDEFAULTCLIENT,
+                 "pkix_pl_HttpDefaultClient_SetPostData");
+         PKIX_NULLCHECK_ONE(request);
+ 
+         PKIX_CHECK(pkix_CheckType
+                 ((PKIX_PL_Object *)request,
+                 PKIX_HTTPDEFAULTCLIENT_TYPE,
+-                plContext),
++                plCtx),
+                 PKIX_REQUESTNOTANHTTPDEFAULTCLIENT);
+ 
+         client = (PKIX_PL_HttpDefaultClient *)request;
+ 
+         client->send_http_data = http_data;
+         client->send_http_data_len = http_data_len;
+         client->send_http_content_type = http_content_type;
+ 
+@@ -1302,34 +1302,34 @@ pkix_pl_HttpDefaultClient_TrySendAndRece
+         SEC_HTTP_REQUEST_SESSION request,
+         PRUint16 *http_response_code, 
+         const char **http_response_content_type, 
+         const char **http_response_headers, 
+         const char **http_response_data, 
+         PRUint32 *http_response_data_len, 
+         PRPollDesc **pPollDesc,
+         SECStatus *pSECReturn,
+-        void *plContext)        
++        void *plCtx)        
+ {
+         PKIX_PL_HttpDefaultClient *client = NULL;
+         PKIX_UInt32 postLen = 0;
+         PRPollDesc *pollDesc = NULL;
+         char *sendbuf = NULL;
+         char portstr[16];
+ 
+         PKIX_ENTER
+                 (HTTPDEFAULTCLIENT,
+                 "pkix_pl_HttpDefaultClient_TrySendAndReceive");
+ 
+         PKIX_NULLCHECK_ONE(request);
+ 
+         PKIX_CHECK(pkix_CheckType
+                 ((PKIX_PL_Object *)request,
+                 PKIX_HTTPDEFAULTCLIENT_TYPE,
+-                plContext),
++                plCtx),
+                 PKIX_REQUESTNOTANHTTPDEFAULTCLIENT);
+ 
+         client = (PKIX_PL_HttpDefaultClient *)request;
+ 
+         if (!pPollDesc && client->timeout == 0) {
+             PKIX_ERROR_FATAL(PKIX_NULLARGUMENT);
+         }
+ 
+@@ -1375,17 +1375,17 @@ pkix_pl_HttpDefaultClient_TrySendAndRece
+                         postLen = PORT_Strlen(sendbuf);
+                             
+                         client->POSTLen = postLen + client->send_http_data_len;
+ 
+                         /* allocate postBuffer big enough for header + data */
+                         PKIX_CHECK(PKIX_PL_Malloc
+                                 (client->POSTLen,
+                                 (void **)&(client->POSTBuf),
+-                                plContext),
++                                plCtx),
+                                 PKIX_MALLOCFAILED);
+ 
+                         /* copy header into postBuffer */
+                         PORT_Memcpy(client->POSTBuf, sendbuf, postLen);
+ 
+                         /* append data after header */
+                         PORT_Memcpy(&client->POSTBuf[postLen],
+                                     client->send_http_data,
+@@ -1402,17 +1402,17 @@ pkix_pl_HttpDefaultClient_TrySendAndRece
+                             client->host,
+                             portstr);
+                         client->GETLen = PORT_Strlen(client->GETBuf);
+                 }
+ 
+         }
+ 
+         /* continue according to state */
+-        PKIX_CHECK(pkix_pl_HttpDefaultClient_Dispatch(client, plContext),
++        PKIX_CHECK(pkix_pl_HttpDefaultClient_Dispatch(client, plCtx),
+                 PKIX_HTTPDEFAULTCLIENTDISPATCHFAILED);
+ 
+         switch (client->connectStatus) {
+                 case HTTP_CONNECT_PENDING:
+                 case HTTP_SEND_PENDING:
+                 case HTTP_RECV_HDR_PENDING:
+                 case HTTP_RECV_BODY_PENDING:
+                         pollDesc = &(client->pollDesc);
+@@ -1473,25 +1473,25 @@ cleanup:
+ 
+         PKIX_RETURN(HTTPDEFAULTCLIENT);
+ 
+ }
+ 
+ PKIX_Error *
+ pkix_pl_HttpDefaultClient_Cancel(
+         SEC_HTTP_REQUEST_SESSION request,
+-        void *plContext)
++        void *plCtx)
+ {
+         PKIX_ENTER(HTTPDEFAULTCLIENT, "pkix_pl_HttpDefaultClient_Cancel");
+         PKIX_NULLCHECK_ONE(request);
+ 
+         PKIX_CHECK(pkix_CheckType
+                 ((PKIX_PL_Object *)request,
+                 PKIX_HTTPDEFAULTCLIENT_TYPE,
+-                plContext),
++                plCtx),
+                 PKIX_REQUESTNOTANHTTPDEFAULTCLIENT);
+ 
+         /* XXX Not implemented */
+ 
+ cleanup:
+ 
+         PKIX_RETURN(HTTPDEFAULTCLIENT);
+ 
+diff --git a/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_infoaccess.c b/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_infoaccess.c
+--- a/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_infoaccess.c
++++ b/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_infoaccess.c
+@@ -18,53 +18,53 @@
+  *
+  *  This function creates an InfoAccess from the method provided in "method" and
+  *  the GeneralName provided in "generalName" and stores the result at
+  *  "pInfoAccess".
+  *
+  * PARAMETERS
+  *  "method"
+  *      The UInt32 value to be stored as the method field of the InfoAccess.
+- *  "generalName"
+- *      The GeneralName to be stored as the generalName field of the InfoAccess.
++ *  "gName"
++ *      The GeneralName to be stored as the gName field of the InfoAccess.
+  *      Must be non-NULL.
+  *  "pInfoAccess"
+  *      Address where the result is stored. Must be non-NULL.
+  *  "plContext"
+  *      Platform-specific context pointer.
+  * THREAD SAFETY:
+  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
+  * RETURNS:
+  *  Returns NULL if the function succeeds.
+  *  Returns a Fatal Error if the function fails in an unrecoverable way.
+  */
+ static PKIX_Error *
+ pkix_pl_InfoAccess_Create(
+         PKIX_UInt32 method,
+-        PKIX_PL_GeneralName *generalName,
++        PKIX_PL_GeneralName *gName,
+         PKIX_PL_InfoAccess **pInfoAccess,
+         void *plContext)
+ {
+ 
+         PKIX_PL_InfoAccess *infoAccess = NULL;
+ 
+         PKIX_ENTER(INFOACCESS, "pkix_pl_InfoAccess_Create");
+-        PKIX_NULLCHECK_TWO(generalName, pInfoAccess);
++        PKIX_NULLCHECK_TWO(gName, pInfoAccess);
+ 
+         PKIX_CHECK(PKIX_PL_Object_Alloc
+                 (PKIX_INFOACCESS_TYPE,
+                 sizeof (PKIX_PL_InfoAccess),
+                 (PKIX_PL_Object **)&infoAccess,
+                 plContext),
+                 PKIX_COULDNOTCREATEINFOACCESSOBJECT);
+ 
+         infoAccess->method = method;
+ 
+-        PKIX_INCREF(generalName);
+-        infoAccess->location = generalName;
++        PKIX_INCREF(gName);
++        infoAccess->location = gName;
+ 
+         *pInfoAccess = infoAccess;
+         infoAccess = NULL;
+ 
+ cleanup:
+         PKIX_DECREF(infoAccess);
+ 
+         PKIX_RETURN(INFOACCESS);
+@@ -673,17 +673,17 @@ pkix_pl_UnescapeURL(
+  *
+  *  ldap://<ldap-server-site>/[cn=<cname>][,o=<org>][,c=<country>]?
+  *  [caCertificate|crossCertificatPair|certificateRevocationList];
+  *  [binary|<other-type>]
+  *  [[,caCertificate|crossCertificatPair|certificateRevocationList]
+  *   [binary|<other-type>]]*
+  *
+  * PARAMETERS
+- *  "generalName"
++ *  "gName"
+  *      Address of the GeneralName whose LDAPLocation is to be parsed. Must be
+  *      non-NULL.
+  *  "arena"
+  *      Address of PLArenaPool to be used for the domainName and for components
+  *      of the LDAPRequest. Must be non-NULL.
+  *  "request"
+  *      Address of the LDAPRequestParams into which request components are
+  *      stored. Must be non-NULL.
+@@ -695,17 +695,17 @@ pkix_pl_UnescapeURL(
+  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
+  * RETURNS:
+  *  Returns NULL if the function succeeds.
+  *  Returns an InfoAccess Error if the function fails in a non-fatal way.
+  *  Returns a Fatal Error if the function fails in an unrecoverable way.
+  */
+ PKIX_Error *
+ pkix_pl_InfoAccess_ParseLocation(
+-        PKIX_PL_GeneralName *generalName,
++        PKIX_PL_GeneralName *gName,
+         PLArenaPool *arena,
+         LDAPRequestParams *request,
+         char **pDomainName,
+         void *plContext)
+ {
+         PKIX_PL_String *locationString = NULL;
+         PKIX_UInt32 len = 0;
+         PKIX_UInt32 ncIndex = 0;
+@@ -717,19 +717,19 @@ pkix_pl_InfoAccess_ParseLocation(
+         char *startPos = NULL;
+         char *endPos = NULL;
+         char *avaPtr = NULL;
+         LdapAttrMask attrBit = 0;
+         LDAPNameComponent **setOfNameComponent = NULL;
+         LDAPNameComponent *nameComponent = NULL;
+ 
+         PKIX_ENTER(INFOACCESS, "pkix_pl_InfoAccess_ParseLocation");
+-        PKIX_NULLCHECK_FOUR(generalName, arena, request, pDomainName);
++        PKIX_NULLCHECK_FOUR(gName, arena, request, pDomainName);
+ 
+-        PKIX_TOSTRING(generalName, &locationString, plContext,
++        PKIX_TOSTRING(gName, &locationString, plContext,
+                 PKIX_GENERALNAMETOSTRINGFAILED);
+ 
+         PKIX_CHECK(PKIX_PL_String_GetEncoded
+                 (locationString,
+                 PKIX_ESCASCII,
+                 (void **)&locationAscii,
+                 &len,
+                 plContext),
+diff --git a/security/nss/lib/nss/nss.h b/security/nss/lib/nss/nss.h
+--- a/security/nss/lib/nss/nss.h
++++ b/security/nss/lib/nss/nss.h
+@@ -17,22 +17,22 @@
+ 
+ /*
+  * NSS's major version, minor version, patch level, build number, and whether
+  * this is a beta release.
+  *
+  * The format of the version string should be
+  *     "<major version>.<minor version>[.<patch level>[.<build number>]][ <ECC>][ <Beta>]"
+  */
+-#define NSS_VERSION "3.36.8" _NSS_CUSTOMIZED
++#define NSS_VERSION "3.37" _NSS_CUSTOMIZED " Beta"
+ #define NSS_VMAJOR 3
+-#define NSS_VMINOR 36
+-#define NSS_VPATCH 8
++#define NSS_VMINOR 37
++#define NSS_VPATCH 0
+ #define NSS_VBUILD 0
+-#define NSS_BETA PR_FALSE
++#define NSS_BETA PR_TRUE
+ 
+ #ifndef RC_INVOKED
+ 
+ #include "seccomon.h"
+ 
+ typedef struct NSSInitParametersStr NSSInitParameters;
+ 
+ /*
+diff --git a/security/nss/lib/pk11wrap/dev3hack.c b/security/nss/lib/pk11wrap/dev3hack.c
+--- a/security/nss/lib/pk11wrap/dev3hack.c
++++ b/security/nss/lib/pk11wrap/dev3hack.c
+@@ -117,17 +117,17 @@ nssSlot_CreateFromPK11SlotInfo(NSSTrustD
+     rvSlot->pk11slot = PK11_ReferenceSlot(nss3slot);
+     rvSlot->epv = nss3slot->functionList;
+     rvSlot->slotID = nss3slot->slotID;
+     /* Grab the slot name from the PKCS#11 fixed-length buffer */
+     rvSlot->base.name = nssUTF8_Duplicate(nss3slot->slot_name, td->arena);
+     rvSlot->lock = (nss3slot->isThreadSafe) ? NULL : nss3slot->sessionLock;
+     rvSlot->isPresentLock = PZ_NewLock(nssiLockOther);
+     rvSlot->isPresentCondition = PR_NewCondVar(rvSlot->isPresentLock);
+-    rvSlot->isPresentThread = NULL;
++    rvSlot->inIsPresent = PR_FALSE;
+     rvSlot->lastTokenPingState = nssSlotLastPingState_Reset;
+     return rvSlot;
+ }
+ 
+ NSSToken *
+ nssToken_CreateFromPK11SlotInfo(NSSTrustDomain *td, PK11SlotInfo *nss3slot)
+ {
+     NSSToken *rvToken;
+diff --git a/security/nss/lib/pk11wrap/pk11akey.c b/security/nss/lib/pk11wrap/pk11akey.c
+--- a/security/nss/lib/pk11wrap/pk11akey.c
++++ b/security/nss/lib/pk11wrap/pk11akey.c
+@@ -185,16 +185,17 @@ PK11_ImportPublicKey(PK11SlotInfo *slot,
+                 attrs++;
+                 break;
+             case ecKey:
+                 keyType = CKK_EC;
+                 PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));
+                 attrs++;
+                 PK11_SETATTRS(attrs, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL));
+                 attrs++;
++                signedattr = attrs;
+                 PK11_SETATTRS(attrs, CKA_EC_PARAMS,
+                               pubKey->u.ec.DEREncodedParams.data,
+                               pubKey->u.ec.DEREncodedParams.len);
+                 attrs++;
+                 if (PR_GetEnvSecure("NSS_USE_DECODED_CKA_EC_POINT")) {
+                     PK11_SETATTRS(attrs, CKA_EC_POINT,
+                                   pubKey->u.ec.publicValue.data,
+                                   pubKey->u.ec.publicValue.len);
+@@ -216,24 +217,22 @@ PK11_ImportPublicKey(PK11SlotInfo *slot,
+                 break;
+             default:
+                 if (ckaId) {
+                     SECITEM_FreeItem(ckaId, PR_TRUE);
+                 }
+                 PORT_SetError(SEC_ERROR_BAD_KEY);
+                 return CK_INVALID_HANDLE;
+         }
++
+         templateCount = attrs - theTemplate;
++        signedcount = attrs - signedattr;
+         PORT_Assert(templateCount <= (sizeof(theTemplate) / sizeof(CK_ATTRIBUTE)));
+-        if (pubKey->keyType != ecKey) {
+-            PORT_Assert(signedattr);
+-            signedcount = attrs - signedattr;
+-            for (attrs = signedattr; signedcount; attrs++, signedcount--) {
+-                pk11_SignedToUnsigned(attrs);
+-            }
++        for (attrs = signedattr; signedcount; attrs++, signedcount--) {
++            pk11_SignedToUnsigned(attrs);
+         }
+         rv = PK11_CreateNewObject(slot, CK_INVALID_SESSION, theTemplate,
+                                   templateCount, isToken, &objectID);
+         if (ckaId) {
+             SECITEM_FreeItem(ckaId, PR_TRUE);
+         }
+         if (pubValue) {
+             SECITEM_FreeItem(pubValue, PR_TRUE);
+@@ -800,22 +799,40 @@ PK11_MakePrivKey(PK11SlotInfo *slot, Key
+     PLArenaPool *arena;
+     SECKEYPrivateKey *privKey;
+     PRBool isPrivate;
+     SECStatus rv;
+ 
+     /* don't know? look it up */
+     if (keyType == nullKey) {
+         CK_KEY_TYPE pk11Type = CKK_RSA;
++        SECItem info;
+ 
+         pk11Type = PK11_ReadULongAttribute(slot, privID, CKA_KEY_TYPE);
+         isTemp = (PRBool)!PK11_HasAttributeSet(slot, privID, CKA_TOKEN, PR_FALSE);
+         switch (pk11Type) {
+             case CKK_RSA:
+                 keyType = rsaKey;
++                /* determine RSA key type from the CKA_PUBLIC_KEY_INFO if present */
++                rv = PK11_ReadAttribute(slot, privID, CKA_PUBLIC_KEY_INFO, NULL, &info);
++                if (rv == SECSuccess) {
++                    CERTSubjectPublicKeyInfo *spki;
++
++                    spki = SECKEY_DecodeDERSubjectPublicKeyInfo(&info);
++                    if (spki) {
++                        SECOidTag tag;
++
++                        tag = SECOID_GetAlgorithmTag(&spki->algorithm);
++                        if (tag == SEC_OID_PKCS1_RSA_PSS_SIGNATURE)
++                            keyType = rsaPssKey;
++                        SECKEY_DestroySubjectPublicKeyInfo(spki);
++                    }
++                    SECITEM_FreeItem(&info, PR_FALSE);
++                }
++
+                 break;
+             case CKK_DSA:
+                 keyType = dsaKey;
+                 break;
+             case CKK_DH:
+                 keyType = dhKey;
+                 break;
+             case CKK_KEA:
+@@ -1070,23 +1087,19 @@ pk11_loadPrivKeyWithFlags(PK11SlotInfo *
+         return NULL;
+     }
+ 
+     /* Set token, private, modifiable, sensitive, and extractable */
+     count += pk11_AttrFlagsToAttributes(attrFlags, &privTemplate[count],
+                                         &cktrue, &ckfalse);
+ 
+     /* Not everyone can handle zero padded key values, give
+-     * them the raw data as unsigned. The exception is EC,
+-     * where the values are encoded or zero-preserving
+-     * per-RFC5915 */
+-    if (privKey->keyType != ecKey) {
+-        for (ap = attrs; extra_count; ap++, extra_count--) {
+-            pk11_SignedToUnsigned(ap);
+-        }
++      * them the raw data as unsigned */
++    for (ap = attrs; extra_count; ap++, extra_count--) {
++        pk11_SignedToUnsigned(ap);
+     }
+ 
+     /* now Store the puppies */
+     rv = PK11_CreateNewObject(slot, CK_INVALID_SESSION, privTemplate,
+                               count, token, &objectID);
+     PORT_FreeArena(arena, PR_TRUE);
+     if (rv != SECSuccess) {
+         return NULL;
+diff --git a/security/nss/lib/pk11wrap/pk11cert.c b/security/nss/lib/pk11wrap/pk11cert.c
+--- a/security/nss/lib/pk11wrap/pk11cert.c
++++ b/security/nss/lib/pk11wrap/pk11cert.c
+@@ -179,19 +179,17 @@ PK11_IsUserCert(PK11SlotInfo *slot, CERT
+                 /* fall through and return false */
+                 break;
+         }
+ 
+         if (theTemplate.ulValueLen == 0) {
+             SECKEY_DestroyPublicKey(pubKey);
+             return PR_FALSE;
+         }
+-        if (pubKey->keyType != ecKey) {
+-            pk11_SignedToUnsigned(&theTemplate);
+-        }
++        pk11_SignedToUnsigned(&theTemplate);
+         if (pk11_FindObjectByTemplate(slot, &theTemplate, 1) != CK_INVALID_HANDLE) {
+             SECKEY_DestroyPublicKey(pubKey);
+             return PR_TRUE;
+         }
+         SECKEY_DestroyPublicKey(pubKey);
+     }
+     return PR_FALSE;
+ }
+diff --git a/security/nss/lib/pk11wrap/pk11pars.c b/security/nss/lib/pk11wrap/pk11pars.c
+--- a/security/nss/lib/pk11wrap/pk11pars.c
++++ b/security/nss/lib/pk11wrap/pk11pars.c
+@@ -542,26 +542,26 @@ secmod_applyCryptoPolicy(const char *pol
+                 NSS_SetAlgorithmPolicy(algOptList[i].oid, enable, disable);
+             }
+             continue;
+         }
+ 
+         for (i = 0; i < PR_ARRAY_SIZE(algOptList); i++) {
+             const oidValDef *algOpt = &algOptList[i];
+             unsigned name_size = algOpt->name_size;
+-            PRBool newValue = PR_FALSE;
++            PRBool newOption = PR_FALSE;
+ 
+             if ((length >= name_size) && (cipher[name_size] == '/')) {
+-                newValue = PR_TRUE;
++                newOption = PR_TRUE;
+             }
+-            if ((newValue || algOpt->name_size == length) &&
++            if ((newOption || algOpt->name_size == length) &&
+                 PORT_Strncasecmp(algOpt->name, cipher, name_size) == 0) {
+                 PRUint32 value = algOpt->val;
+                 PRUint32 enable, disable;
+-                if (newValue) {
++                if (newOption) {
+                     value = secmod_parsePolicyValue(&cipher[name_size] + 1,
+                                                     length - name_size - 1);
+                 }
+                 if (allow) {
+                     enable = value;
+                     disable = 0;
+                 } else {
+                     enable = 0;
+diff --git a/security/nss/lib/pk11wrap/pk11pk12.c b/security/nss/lib/pk11wrap/pk11pk12.c
+--- a/security/nss/lib/pk11wrap/pk11pk12.c
++++ b/security/nss/lib/pk11wrap/pk11pk12.c
+@@ -500,17 +500,17 @@ PK11_ImportAndReturnPrivateKey(PK11SlotI
+                           sizeof(CK_BBOOL));
+             attrs++;
+             ck_id = PK11_MakeIDFromPubKey(&lpk->u.ec.publicValue);
+             if (ck_id == NULL) {
+                 goto loser;
+             }
+             PK11_SETATTRS(attrs, CKA_ID, ck_id->data, ck_id->len);
+             attrs++;
+-            /* No signed attrs for EC */
++            signedattr = attrs;
+             /* curveOID always is a copy of AlgorithmID.parameters. */
+             PK11_SETATTRS(attrs, CKA_EC_PARAMS, lpk->u.ec.curveOID.data,
+                           lpk->u.ec.curveOID.len);
+             attrs++;
+             PK11_SETATTRS(attrs, CKA_VALUE, lpk->u.ec.privateValue.data,
+                           lpk->u.ec.privateValue.len);
+             attrs++;
+             PK11_SETATTRS(attrs, CKA_EC_POINT, lpk->u.ec.publicValue.data,
+@@ -518,22 +518,21 @@ PK11_ImportAndReturnPrivateKey(PK11SlotI
+             attrs++;
+             break;
+         default:
+             PORT_SetError(SEC_ERROR_BAD_KEY);
+             goto loser;
+     }
+     templateCount = attrs - theTemplate;
+     PORT_Assert(templateCount <= sizeof(theTemplate) / sizeof(CK_ATTRIBUTE));
+-    if (lpk->keyType != ecKey) {
+-        PORT_Assert(signedattr);
+-        signedcount = attrs - signedattr;
+-        for (ap = signedattr; signedcount; ap++, signedcount--) {
+-            pk11_SignedToUnsigned(ap);
+-        }
++    PORT_Assert(signedattr != NULL);
++    signedcount = attrs - signedattr;
++
++    for (ap = signedattr; signedcount; ap++, signedcount--) {
++        pk11_SignedToUnsigned(ap);
+     }
+ 
+     rv = PK11_CreateNewObject(slot, CK_INVALID_SESSION,
+                               theTemplate, templateCount, isPerm, &objectID);
+ 
+     /* create and return a SECKEYPrivateKey */
+     if (rv == SECSuccess && privk != NULL) {
+         *privk = PK11_MakePrivKey(slot, lpk->keyType, !isPerm, objectID, wincx);
+diff --git a/security/nss/lib/pkcs12/p12d.c b/security/nss/lib/pkcs12/p12d.c
+--- a/security/nss/lib/pkcs12/p12d.c
++++ b/security/nss/lib/pkcs12/p12d.c
+@@ -808,17 +808,16 @@ sec_pkcs12_decoder_asafes_notify(void *a
+ 
+     if (!before) {
+         /* if one is being decoded, finish the decode */
+         if (p12dcx->currentASafeP7Dcx != NULL) {
+             SEC_PKCS7ContentInfo *cinfo;
+             unsigned int cnt = p12dcx->safeContentsCnt - 1;
+             safeContentsCtx = p12dcx->safeContentsList[cnt];
+             if (safeContentsCtx->safeContentsA1Dcx) {
+-                SEC_ASN1DecoderClearFilterProc(p12dcx->aSafeA1Dcx);
+                 SEC_ASN1DecoderFinish(safeContentsCtx->safeContentsA1Dcx);
+                 safeContentsCtx->safeContentsA1Dcx = NULL;
+             }
+             cinfo = SEC_PKCS7DecoderFinish(p12dcx->currentASafeP7Dcx);
+             p12dcx->currentASafeP7Dcx = NULL;
+             if (!cinfo) {
+                 p12dcx->errorValue = PORT_GetError();
+                 goto loser;
+diff --git a/security/nss/lib/pkcs7/p7create.c b/security/nss/lib/pkcs7/p7create.c
+--- a/security/nss/lib/pkcs7/p7create.c
++++ b/security/nss/lib/pkcs7/p7create.c
+@@ -17,17 +17,17 @@
+ #include "secerr.h"
+ #include "secder.h"
+ #include "secpkcs5.h"
+ 
+ const int NSS_PBE_DEFAULT_ITERATION_COUNT = /* used in p12e.c too */
+ #ifdef DEBUG
+     10000
+ #else
+-    600000
++    1000000
+ #endif
+     ;
+ 
+ static SECStatus
+ sec_pkcs7_init_content_info(SEC_PKCS7ContentInfo *cinfo, PLArenaPool *poolp,
+                             SECOidTag kind, PRBool detached)
+ {
+     void *thing;
+diff --git a/security/nss/lib/pkcs7/p7decode.c b/security/nss/lib/pkcs7/p7decode.c
+--- a/security/nss/lib/pkcs7/p7decode.c
++++ b/security/nss/lib/pkcs7/p7decode.c
+@@ -555,17 +555,16 @@ sec_pkcs7_decoder_start_decrypt(SEC_PKCS
+                                  (PRBool)(p7dcx->cb != NULL));
+ 
+     p7dcx->worker.depth = depth;
+     p7dcx->worker.decryptobj = decryptobj;
+ 
+     return SECSuccess;
+ 
+ no_decryption:
+-    PK11_FreeSymKey(bulkkey);
+     /*
+      * For some reason (error set already, if appropriate), we cannot
+      * decrypt the content.  I am not sure what exactly is the right
+      * thing to do here; in some cases we want to just stop, and in
+      * others we want to let the decoding finish even though we cannot
+      * decrypt the content.  My current thinking is that if the caller
+      * set up a content callback, then they are really interested in
+      * getting (decrypted) content, and if they cannot they will want
+@@ -1027,21 +1026,16 @@ SEC_PKCS7DecoderStart(SEC_PKCS7DecoderCo
+  * again in case that is the easiest route for our caller to take.
+  * We simply detect it and do not do anything except keep setting
+  * that error in case our caller has not noticed it yet...
+  */
+ SECStatus
+ SEC_PKCS7DecoderUpdate(SEC_PKCS7DecoderContext *p7dcx,
+                        const char *buf, unsigned long len)
+ {
+-    if (!p7dcx) {
+-        PORT_SetError(SEC_ERROR_INVALID_ARGS);
+-        return SECFailure;
+-    }
+-
+     if (p7dcx->cinfo != NULL && p7dcx->dcx != NULL) {
+         PORT_Assert(p7dcx->error == 0);
+         if (p7dcx->error == 0) {
+             if (SEC_ASN1DecoderUpdate(p7dcx->dcx, buf, len) != SECSuccess) {
+                 p7dcx->error = PORT_GetError();
+                 PORT_Assert(p7dcx->error);
+                 if (p7dcx->error == 0)
+                     p7dcx->error = -1;
+@@ -1591,17 +1585,16 @@ sec_pkcs7_verify_signature(SEC_PKCS7Cont
+                                                 encoded_attrs.len,
+                                                 publickey, &(signerinfo->encDigest),
+                                                 encTag, digestTag, NULL,
+                                                 cinfo->pwfn_arg) == SECSuccess);
+         PORT_Free(encoded_attrs.data);
+     } else {
+         SECItem *sig;
+         SECItem holder;
+-        SECStatus rv;
+ 
+         /*
+          * No authenticated attributes.
+          * The signature is based on the plain message digest.
+          */
+ 
+         sig = &(signerinfo->encDigest);
+         if (sig->len == 0) { /* bad signature */
+diff --git a/security/nss/lib/pki/pki3hack.c b/security/nss/lib/pki/pki3hack.c
+--- a/security/nss/lib/pki/pki3hack.c
++++ b/security/nss/lib/pki/pki3hack.c
+@@ -1138,18 +1138,18 @@ STAN_ChangeCertTrust(CERTCertificate *cc
+     nssTrust->serverAuth = get_stan_trust(trust->sslFlags, PR_FALSE);
+     nssTrust->clientAuth = get_stan_trust(trust->sslFlags, PR_TRUE);
+     nssTrust->emailProtection = get_stan_trust(trust->emailFlags, PR_FALSE);
+     nssTrust->codeSigning = get_stan_trust(trust->objectSigningFlags, PR_FALSE);
+     nssTrust->stepUpApproved =
+         (PRBool)(trust->sslFlags & CERTDB_GOVT_APPROVED_CA);
+     if (c->object.cryptoContext != NULL) {
+         /* The cert is in a context, set the trust there */
+-        NSSCryptoContext *cc = c->object.cryptoContext;
+-        nssrv = nssCryptoContext_ImportTrust(cc, nssTrust);
++        NSSCryptoContext *cctx = c->object.cryptoContext;
++        nssrv = nssCryptoContext_ImportTrust(cctx, nssTrust);
+         if (nssrv != PR_SUCCESS) {
+             goto done;
+         }
+         if (c->object.numInstances == 0) {
+             /* The context is the only instance, finished */
+             goto done;
+         }
+     }
+diff --git a/security/nss/lib/smime/cmscinfo.c b/security/nss/lib/smime/cmscinfo.c
+--- a/security/nss/lib/smime/cmscinfo.c
++++ b/security/nss/lib/smime/cmscinfo.c
+@@ -46,20 +46,16 @@ nss_cmsContentInfo_private_destroy(NSSCM
+ /*
+  * NSS_CMSContentInfo_Destroy - destroy a CMS contentInfo and all of its sub-pieces.
+  */
+ void
+ NSS_CMSContentInfo_Destroy(NSSCMSContentInfo *cinfo)
+ {
+     SECOidTag kind;
+ 
+-    if (cinfo == NULL) {
+-        return;
+-    }
+-
+     kind = NSS_CMSContentInfo_GetContentTypeTag(cinfo);
+     switch (kind) {
+         case SEC_OID_PKCS7_ENVELOPED_DATA:
+             NSS_CMSEnvelopedData_Destroy(cinfo->content.envelopedData);
+             break;
+         case SEC_OID_PKCS7_SIGNED_DATA:
+             NSS_CMSSignedData_Destroy(cinfo->content.signedData);
+             break;
+@@ -85,21 +81,16 @@ NSS_CMSContentInfo_Destroy(NSSCMSContent
+ 
+ /*
+  * NSS_CMSContentInfo_GetChildContentInfo - get content's contentInfo (if it exists)
+  */
+ NSSCMSContentInfo *
+ NSS_CMSContentInfo_GetChildContentInfo(NSSCMSContentInfo *cinfo)
+ {
+     NSSCMSContentInfo *ccinfo = NULL;
+-
+-    if (cinfo == NULL) {
+-        return NULL;
+-    }
+-
+     SECOidTag tag = NSS_CMSContentInfo_GetContentTypeTag(cinfo);
+     switch (tag) {
+         case SEC_OID_PKCS7_SIGNED_DATA:
+             if (cinfo->content.signedData != NULL) {
+                 ccinfo = &(cinfo->content.signedData->contentInfo);
+             }
+             break;
+         case SEC_OID_PKCS7_ENVELOPED_DATA:
+@@ -131,19 +122,16 @@ NSS_CMSContentInfo_GetChildContentInfo(N
+     }
+     return ccinfo;
+ }
+ 
+ SECStatus
+ NSS_CMSContentInfo_SetDontStream(NSSCMSContentInfo *cinfo, PRBool dontStream)
+ {
+     SECStatus rv;
+-    if (cinfo == NULL) {
+-        return SECFailure;
+-    }
+ 
+     rv = NSS_CMSContentInfo_Private_Init(cinfo);
+     if (rv != SECSuccess) {
+         /* default is streaming, failure to get ccinfo will not effect this */
+         return dontStream ? SECFailure : SECSuccess;
+     }
+     cinfo->privateInfo->dontStream = dontStream;
+     return SECSuccess;
+@@ -152,30 +140,25 @@ NSS_CMSContentInfo_SetDontStream(NSSCMSC
+ /*
+  * NSS_CMSContentInfo_SetContent - set content type & content
+  */
+ SECStatus
+ NSS_CMSContentInfo_SetContent(NSSCMSMessage *cmsg, NSSCMSContentInfo *cinfo,
+                               SECOidTag type, void *ptr)
+ {
+     SECStatus rv;
+-    if (cinfo == NULL || cmsg == NULL) {
+-        return SECFailure;
+-    }
+ 
+     cinfo->contentTypeTag = SECOID_FindOIDByTag(type);
+-    if (cinfo->contentTypeTag == NULL) {
++    if (cinfo->contentTypeTag == NULL)
+         return SECFailure;
+-    }
+ 
+     /* do not copy the oid, just create a reference */
+     rv = SECITEM_CopyItem(cmsg->poolp, &(cinfo->contentType), &(cinfo->contentTypeTag->oid));
+-    if (rv != SECSuccess) {
++    if (rv != SECSuccess)
+         return SECFailure;
+-    }
+ 
+     cinfo->content.pointer = ptr;
+ 
+     if (NSS_CMSType_IsData(type) && ptr) {
+         cinfo->rawContent = ptr;
+     } else {
+         /* as we always have some inner data,
+      * we need to set it to something, just to fool the encoder enough to work on it
+@@ -197,19 +180,18 @@ NSS_CMSContentInfo_SetContent(NSSCMSMess
+ /*
+  * data == NULL -> pass in data via NSS_CMSEncoder_Update
+  * data != NULL -> take this data
+  */
+ SECStatus
+ NSS_CMSContentInfo_SetContent_Data(NSSCMSMessage *cmsg, NSSCMSContentInfo *cinfo,
+                                    SECItem *data, PRBool detached)
+ {
+-    if (NSS_CMSContentInfo_SetContent(cmsg, cinfo, SEC_OID_PKCS7_DATA, (void *)data) != SECSuccess) {
++    if (NSS_CMSContentInfo_SetContent(cmsg, cinfo, SEC_OID_PKCS7_DATA, (void *)data) != SECSuccess)
+         return SECFailure;
+-    }
+     if (detached) {
+         cinfo->rawContent = NULL;
+     }
+ 
+     return SECSuccess;
+ }
+ 
+ SECStatus
+@@ -243,20 +225,16 @@ NSS_CMSContentInfo_SetContent_EncryptedD
+ /*
+  * NSS_CMSContentInfo_GetContent - get pointer to inner content
+  *
+  * needs to be casted...
+  */
+ void *
+ NSS_CMSContentInfo_GetContent(NSSCMSContentInfo *cinfo)
+ {
+-    if (cinfo == NULL) {
+-        return NULL;
+-    }
+-
+     SECOidTag tag = cinfo->contentTypeTag
+                         ? cinfo->contentTypeTag->offset
+                         : SEC_OID_UNKNOWN;
+     switch (tag) {
+         case SEC_OID_PKCS7_DATA:
+         case SEC_OID_PKCS7_SIGNED_DATA:
+         case SEC_OID_PKCS7_ENVELOPED_DATA:
+         case SEC_OID_PKCS7_DIGESTED_DATA:
+@@ -277,20 +255,16 @@ NSS_CMSContentInfo_GetContent(NSSCMSCont
+ 
+ SECItem *
+ NSS_CMSContentInfo_GetInnerContent(NSSCMSContentInfo *cinfo)
+ {
+     NSSCMSContentInfo *ccinfo;
+     SECOidTag tag;
+     SECItem *pItem = NULL;
+ 
+-    if (cinfo == NULL) {
+-        return NULL;
+-    }
+-
+     tag = NSS_CMSContentInfo_GetContentTypeTag(cinfo);
+     if (NSS_CMSType_IsData(tag)) {
+         pItem = cinfo->content.data;
+     } else if (NSS_CMSType_IsWrapper(tag)) {
+         ccinfo = NSS_CMSContentInfo_GetChildContentInfo(cinfo);
+         if (ccinfo != NULL) {
+             pItem = NSS_CMSContentInfo_GetContent(ccinfo);
+         }
+@@ -303,141 +277,99 @@ NSS_CMSContentInfo_GetInnerContent(NSSCM
+ 
+ /*
+  * NSS_CMSContentInfo_GetContentType{Tag,OID} - find out (saving pointer to lookup result
+  * for future reference) and return the inner content type.
+  */
+ SECOidTag
+ NSS_CMSContentInfo_GetContentTypeTag(NSSCMSContentInfo *cinfo)
+ {
+-    if (cinfo == NULL) {
+-        return SEC_OID_UNKNOWN;
+-    }
+-
+     if (cinfo->contentTypeTag == NULL)
+         cinfo->contentTypeTag = SECOID_FindOID(&(cinfo->contentType));
+ 
+     if (cinfo->contentTypeTag == NULL)
+         return SEC_OID_UNKNOWN;
+ 
+     return cinfo->contentTypeTag->offset;
+ }
+ 
+ SECItem *
+ NSS_CMSContentInfo_GetContentTypeOID(NSSCMSContentInfo *cinfo)
+ {
+-    if (cinfo == NULL) {
+-        return NULL;
+-    }
+-
+-    if (cinfo->contentTypeTag == NULL) {
++    if (cinfo->contentTypeTag == NULL)
+         cinfo->contentTypeTag = SECOID_FindOID(&(cinfo->contentType));
+-    }
+ 
+-    if (cinfo->contentTypeTag == NULL) {
++    if (cinfo->contentTypeTag == NULL)
+         return NULL;
+-    }
+ 
+     return &(cinfo->contentTypeTag->oid);
+ }
+ 
+ /*
+  * NSS_CMSContentInfo_GetContentEncAlgTag - find out (saving pointer to lookup result
+  * for future reference) and return the content encryption algorithm tag.
+  */
+ SECOidTag
+ NSS_CMSContentInfo_GetContentEncAlgTag(NSSCMSContentInfo *cinfo)
+ {
+-    if (cinfo == NULL) {
+-        return SEC_OID_UNKNOWN;
+-    }
+-
+-    if (cinfo->contentEncAlgTag == SEC_OID_UNKNOWN) {
++    if (cinfo->contentEncAlgTag == SEC_OID_UNKNOWN)
+         cinfo->contentEncAlgTag = SECOID_GetAlgorithmTag(&(cinfo->contentEncAlg));
+-    }
+ 
+     return cinfo->contentEncAlgTag;
+ }
+ 
+ /*
+  * NSS_CMSContentInfo_GetContentEncAlg - find out and return the content encryption algorithm tag.
+  */
+ SECAlgorithmID *
+ NSS_CMSContentInfo_GetContentEncAlg(NSSCMSContentInfo *cinfo)
+ {
+-    if (cinfo == NULL) {
+-        return NULL;
+-    }
+-
+     return &(cinfo->contentEncAlg);
+ }
+ 
+ SECStatus
+ NSS_CMSContentInfo_SetContentEncAlg(PLArenaPool *poolp, NSSCMSContentInfo *cinfo,
+                                     SECOidTag bulkalgtag, SECItem *parameters, int keysize)
+ {
+     SECStatus rv;
+-    if (cinfo == NULL) {
+-        return SECFailure;
+-    }
+ 
+     rv = SECOID_SetAlgorithmID(poolp, &(cinfo->contentEncAlg), bulkalgtag, parameters);
+-    if (rv != SECSuccess) {
++    if (rv != SECSuccess)
+         return SECFailure;
+-    }
+     cinfo->keysize = keysize;
+     return SECSuccess;
+ }
+ 
+ SECStatus
+ NSS_CMSContentInfo_SetContentEncAlgID(PLArenaPool *poolp, NSSCMSContentInfo *cinfo,
+                                       SECAlgorithmID *algid, int keysize)
+ {
+     SECStatus rv;
+-    if (cinfo == NULL) {
+-        return SECFailure;
+-    }
+ 
+     rv = SECOID_CopyAlgorithmID(poolp, &(cinfo->contentEncAlg), algid);
+-    if (rv != SECSuccess) {
++    if (rv != SECSuccess)
+         return SECFailure;
+-    }
+-    if (keysize >= 0) {
++    if (keysize >= 0)
+         cinfo->keysize = keysize;
+-    }
+     return SECSuccess;
+ }
+ 
+ void
+ NSS_CMSContentInfo_SetBulkKey(NSSCMSContentInfo *cinfo, PK11SymKey *bulkkey)
+ {
+-    if (cinfo == NULL) {
+-        return;
+-    }
+-
+-    if (bulkkey == NULL) {
+-        cinfo->bulkkey = NULL;
+-        cinfo->keysize = 0;
+-    } else {
+-        cinfo->bulkkey = PK11_ReferenceSymKey(bulkkey);
+-        cinfo->keysize = PK11_GetKeyStrength(cinfo->bulkkey, &(cinfo->contentEncAlg));
+-    }
++    cinfo->bulkkey = PK11_ReferenceSymKey(bulkkey);
++    cinfo->keysize = PK11_GetKeyStrength(cinfo->bulkkey, &(cinfo->contentEncAlg));
+ }
+ 
+ PK11SymKey *
+ NSS_CMSContentInfo_GetBulkKey(NSSCMSContentInfo *cinfo)
+ {
+-    if (cinfo == NULL || cinfo->bulkkey == NULL) {
++    if (cinfo->bulkkey == NULL)
+         return NULL;
+-    }
+ 
+     return PK11_ReferenceSymKey(cinfo->bulkkey);
+ }
+ 
+ int
+ NSS_CMSContentInfo_GetBulkKeySize(NSSCMSContentInfo *cinfo)
+ {
+-    if (cinfo == NULL) {
+-        return 0;
+-    }
+-
+     return cinfo->keysize;
+ }
+diff --git a/security/nss/lib/smime/cmsdigdata.c b/security/nss/lib/smime/cmsdigdata.c
+--- a/security/nss/lib/smime/cmsdigdata.c
++++ b/security/nss/lib/smime/cmsdigdata.c
+@@ -51,19 +51,17 @@ loser:
+ 
+ /*
+  * NSS_CMSDigestedData_Destroy - destroy a digestedData object
+  */
+ void
+ NSS_CMSDigestedData_Destroy(NSSCMSDigestedData *digd)
+ {
+     /* everything's in a pool, so don't worry about the storage */
+-    if (digd != NULL) {
+-        NSS_CMSContentInfo_Destroy(&(digd->contentInfo));
+-    }
++    NSS_CMSContentInfo_Destroy(&(digd->contentInfo));
+     return;
+ }
+ 
+ /*
+  * NSS_CMSDigestedData_GetContentInfo - return pointer to digestedData object's contentInfo
+  */
+ NSSCMSContentInfo *
+ NSS_CMSDigestedData_GetContentInfo(NSSCMSDigestedData *digd)
+diff --git a/security/nss/lib/smime/cmsencdata.c b/security/nss/lib/smime/cmsencdata.c
+--- a/security/nss/lib/smime/cmsencdata.c
++++ b/security/nss/lib/smime/cmsencdata.c
+@@ -82,19 +82,17 @@ loser:
+ 
+ /*
+  * NSS_CMSEncryptedData_Destroy - destroy an encryptedData object
+  */
+ void
+ NSS_CMSEncryptedData_Destroy(NSSCMSEncryptedData *encd)
+ {
+     /* everything's in a pool, so don't worry about the storage */
+-    if (encd != NULL) {
+-        NSS_CMSContentInfo_Destroy(&(encd->contentInfo));
+-    }
++    NSS_CMSContentInfo_Destroy(&(encd->contentInfo));
+     return;
+ }
+ 
+ /*
+  * NSS_CMSEncryptedData_GetContentInfo - return pointer to encryptedData object's contentInfo
+  */
+ NSSCMSContentInfo *
+ NSS_CMSEncryptedData_GetContentInfo(NSSCMSEncryptedData *encd)
+diff --git a/security/nss/lib/smime/cmsenvdata.c b/security/nss/lib/smime/cmsenvdata.c
+--- a/security/nss/lib/smime/cmsenvdata.c
++++ b/security/nss/lib/smime/cmsenvdata.c
+@@ -139,21 +139,16 @@ NSS_CMSEnvelopedData_Encode_BeforeStart(
+     PLArenaPool *poolp;
+     extern const SEC_ASN1Template NSSCMSRecipientInfoTemplate[];
+     void *mark = NULL;
+     int i;
+ 
+     poolp = envd->cmsg->poolp;
+     cinfo = &(envd->contentInfo);
+ 
+-    if (cinfo == NULL) {
+-        PORT_SetError(SEC_ERROR_BAD_DATA);
+-        goto loser;
+-    }
+-
+     recipientinfos = envd->recipientInfos;
+     if (recipientinfos == NULL) {
+         PORT_SetError(SEC_ERROR_BAD_DATA);
+ #if 0
+     PORT_SetErrorString("Cannot find recipientinfos to encode.");
+ #endif
+         goto loser;
+     }
+diff --git a/security/nss/lib/smime/cmsmessage.c b/security/nss/lib/smime/cmsmessage.c
+--- a/security/nss/lib/smime/cmsmessage.c
++++ b/security/nss/lib/smime/cmsmessage.c
+@@ -24,45 +24,42 @@ NSSCMSMessage *
+ NSS_CMSMessage_Create(PLArenaPool *poolp)
+ {
+     void *mark = NULL;
+     NSSCMSMessage *cmsg;
+     PRBool poolp_is_ours = PR_FALSE;
+ 
+     if (poolp == NULL) {
+         poolp = PORT_NewArena(1024); /* XXX what is right value? */
+-        if (poolp == NULL) {
++        if (poolp == NULL)
+             return NULL;
+-        }
+         poolp_is_ours = PR_TRUE;
+     }
+ 
+     if (!poolp_is_ours)
+         mark = PORT_ArenaMark(poolp);
+ 
+     cmsg = (NSSCMSMessage *)PORT_ArenaZAlloc(poolp, sizeof(NSSCMSMessage));
+     if (cmsg == NULL ||
+         NSS_CMSContentInfo_Private_Init(&(cmsg->contentInfo)) != SECSuccess) {
+         if (!poolp_is_ours) {
+             if (mark) {
+                 PORT_ArenaRelease(poolp, mark);
+             }
+-        } else {
++        } else
+             PORT_FreeArena(poolp, PR_FALSE);
+-        }
+         return NULL;
+     }
+ 
+     cmsg->poolp = poolp;
+     cmsg->poolp_is_ours = poolp_is_ours;
+     cmsg->refCount = 1;
+ 
+-    if (mark) {
++    if (mark)
+         PORT_ArenaUnmark(poolp, mark);
+-    }
+ 
+     return cmsg;
+ }
+ 
+ /*
+  * NSS_CMSMessage_SetEncodingParams - set up a CMS message object for encoding or decoding
+  *
+  * "cmsg" - message object
+@@ -71,114 +68,90 @@ NSS_CMSMessage_Create(PLArenaPool *poolp
+  * "detached_digestalgs", "detached_digests" - digests from detached content
+  */
+ void
+ NSS_CMSMessage_SetEncodingParams(NSSCMSMessage *cmsg,
+                                  PK11PasswordFunc pwfn, void *pwfn_arg,
+                                  NSSCMSGetDecryptKeyCallback decrypt_key_cb, void *decrypt_key_cb_arg,
+                                  SECAlgorithmID **detached_digestalgs, SECItem **detached_digests)
+ {
+-    if (cmsg == NULL) {
+-        return;
+-    }
+-    if (pwfn) {
++    if (pwfn)
+         PK11_SetPasswordFunc(pwfn);
+-    }
+-
+     cmsg->pwfn_arg = pwfn_arg;
+     cmsg->decrypt_key_cb = decrypt_key_cb;
+     cmsg->decrypt_key_cb_arg = decrypt_key_cb_arg;
+     cmsg->detached_digestalgs = detached_digestalgs;
+     cmsg->detached_digests = detached_digests;
+ }
+ 
+ /*
+  * NSS_CMSMessage_Destroy - destroy a CMS message and all of its sub-pieces.
+  */
+ void
+ NSS_CMSMessage_Destroy(NSSCMSMessage *cmsg)
+ {
+-    if (cmsg == NULL)
++    PORT_Assert(cmsg->refCount > 0);
++    if (cmsg->refCount <= 0) /* oops */
+         return;
+ 
+-    PORT_Assert(cmsg->refCount > 0);
+-    if (cmsg->refCount <= 0) { /* oops */
++    cmsg->refCount--; /* thread safety? */
++    if (cmsg->refCount > 0)
+         return;
+-    }
+-
+-    cmsg->refCount--; /* thread safety? */
+-    if (cmsg->refCount > 0) {
+-        return;
+-    }
+ 
+     NSS_CMSContentInfo_Destroy(&(cmsg->contentInfo));
+ 
+     /* if poolp is not NULL, cmsg is the owner of its arena */
+-    if (cmsg->poolp_is_ours) {
++    if (cmsg->poolp_is_ours)
+         PORT_FreeArena(cmsg->poolp, PR_FALSE); /* XXX clear it? */
+-    }
+ }
+ 
+ /*
+  * NSS_CMSMessage_Copy - return a copy of the given message.
+  *
+  * The copy may be virtual or may be real -- either way, the result needs
+  * to be passed to NSS_CMSMessage_Destroy later (as does the original).
+  */
+ NSSCMSMessage *
+ NSS_CMSMessage_Copy(NSSCMSMessage *cmsg)
+ {
+-    if (cmsg == NULL) {
++    if (cmsg == NULL)
+         return NULL;
+-    }
+ 
+     PORT_Assert(cmsg->refCount > 0);
+ 
+     cmsg->refCount++; /* XXX chrisk thread safety? */
+     return cmsg;
+ }
+ 
+ /*
+  * NSS_CMSMessage_GetArena - return a pointer to the message's arena pool
+  */
+ PLArenaPool *
+ NSS_CMSMessage_GetArena(NSSCMSMessage *cmsg)
+ {
+-    if (cmsg == NULL) {
+-        return NULL;
+-    }
+-
+     return cmsg->poolp;
+ }
+ 
+ /*
+  * NSS_CMSMessage_GetContentInfo - return a pointer to the top level contentInfo
+  */
+ NSSCMSContentInfo *
+ NSS_CMSMessage_GetContentInfo(NSSCMSMessage *cmsg)
+ {
+-    if (cmsg == NULL) {
+-        return NULL;
+-    }
+-
+     return &(cmsg->contentInfo);
+ }
+ 
+ /*
+  * Return a pointer to the actual content.
+  * In the case of those types which are encrypted, this returns the *plain* content.
+  * In case of nested contentInfos, this descends and retrieves the innermost content.
+  */
+ SECItem *
+ NSS_CMSMessage_GetContent(NSSCMSMessage *cmsg)
+ {
+-    if (cmsg == NULL) {
+-        return NULL;
+-    }
+-
+     /* this is a shortcut */
+     NSSCMSContentInfo *cinfo = NSS_CMSMessage_GetContentInfo(cmsg);
+     SECItem *pItem = NSS_CMSContentInfo_GetInnerContent(cinfo);
+     return pItem;
+ }
+ 
+ /*
+  * NSS_CMSMessage_ContentLevelCount - count number of levels of CMS content objects in this message
+@@ -186,20 +159,16 @@ NSS_CMSMessage_GetContent(NSSCMSMessage 
+  * CMS data content objects do not count.
+  */
+ int
+ NSS_CMSMessage_ContentLevelCount(NSSCMSMessage *cmsg)
+ {
+     int count = 0;
+     NSSCMSContentInfo *cinfo;
+ 
+-    if (cmsg == NULL) {
+-        return 0;
+-    }
+-
+     /* walk down the chain of contentinfos */
+     for (cinfo = &(cmsg->contentInfo); cinfo != NULL;) {
+         count++;
+         cinfo = NSS_CMSContentInfo_GetChildContentInfo(cinfo);
+     }
+     return count;
+ }
+ 
+@@ -209,20 +178,16 @@ NSS_CMSMessage_ContentLevelCount(NSSCMSM
+  * CMS data content objects do not count.
+  */
+ NSSCMSContentInfo *
+ NSS_CMSMessage_ContentLevel(NSSCMSMessage *cmsg, int n)
+ {
+     int count = 0;
+     NSSCMSContentInfo *cinfo;
+ 
+-    if (cmsg == NULL) {
+-        return NULL;
+-    }
+-
+     /* walk down the chain of contentinfos */
+     for (cinfo = &(cmsg->contentInfo); cinfo != NULL && count < n;
+          cinfo = NSS_CMSContentInfo_GetChildContentInfo(cinfo)) {
+         count++;
+     }
+ 
+     return cinfo;
+ }
+@@ -230,20 +195,16 @@ NSS_CMSMessage_ContentLevel(NSSCMSMessag
+ /*
+  * NSS_CMSMessage_ContainsCertsOrCrls - see if message contains certs along the way
+  */
+ PRBool
+ NSS_CMSMessage_ContainsCertsOrCrls(NSSCMSMessage *cmsg)
+ {
+     NSSCMSContentInfo *cinfo;
+ 
+-    if (cmsg == NULL) {
+-        return PR_FALSE;
+-    }
+-
+     /* descend into CMS message */
+     for (cinfo = &(cmsg->contentInfo); cinfo != NULL;
+          cinfo = NSS_CMSContentInfo_GetChildContentInfo(cinfo)) {
+         if (!NSS_CMSType_IsData(NSS_CMSContentInfo_GetContentTypeTag(cinfo)))
+             continue; /* next level */
+ 
+         if (NSS_CMSSignedData_ContainsCertsOrCrls(cinfo->content.signedData))
+             return PR_TRUE;
+@@ -255,20 +216,16 @@ NSS_CMSMessage_ContainsCertsOrCrls(NSSCM
+ /*
+  * NSS_CMSMessage_IsEncrypted - see if message contains a encrypted submessage
+  */
+ PRBool
+ NSS_CMSMessage_IsEncrypted(NSSCMSMessage *cmsg)
+ {
+     NSSCMSContentInfo *cinfo;
+ 
+-    if (cmsg == NULL) {
+-        return PR_FALSE;
+-    }
+-
+     /* walk down the chain of contentinfos */
+     for (cinfo = &(cmsg->contentInfo); cinfo != NULL;
+          cinfo = NSS_CMSContentInfo_GetChildContentInfo(cinfo)) {
+         switch (NSS_CMSContentInfo_GetContentTypeTag(cinfo)) {
+             case SEC_OID_PKCS7_ENVELOPED_DATA:
+             case SEC_OID_PKCS7_ENCRYPTED_DATA:
+                 return PR_TRUE;
+             default:
+@@ -289,31 +246,23 @@ NSS_CMSMessage_IsEncrypted(NSSCMSMessage
+  * Note that the content itself can be empty (detached content was sent
+  * another way); it is the presence of the signature that matters.
+  */
+ PRBool
+ NSS_CMSMessage_IsSigned(NSSCMSMessage *cmsg)
+ {
+     NSSCMSContentInfo *cinfo;
+ 
+-    if (cmsg == NULL) {
+-        return PR_FALSE;
+-    }
+-
+     /* walk down the chain of contentinfos */
+     for (cinfo = &(cmsg->contentInfo); cinfo != NULL;
+          cinfo = NSS_CMSContentInfo_GetChildContentInfo(cinfo)) {
+         switch (NSS_CMSContentInfo_GetContentTypeTag(cinfo)) {
+             case SEC_OID_PKCS7_SIGNED_DATA:
+-                if (cinfo->content.signedData == NULL) {
+-                    return PR_FALSE;
+-                }
+-                if (!NSS_CMSArray_IsEmpty((void **)cinfo->content.signedData->signerInfos)) {
++                if (!NSS_CMSArray_IsEmpty((void **)cinfo->content.signedData->signerInfos))
+                     return PR_TRUE;
+-                }
+                 break;
+             default:
+                 /* callback here for generic wrappers? */
+                 break;
+         }
+     }
+     return PR_FALSE;
+ }
+@@ -324,19 +273,18 @@ NSS_CMSMessage_IsSigned(NSSCMSMessage *c
+  * returns PR_TRUE is innermost content length is < minLen
+  * XXX need the encrypted content length (why?)
+  */
+ PRBool
+ NSS_CMSMessage_IsContentEmpty(NSSCMSMessage *cmsg, unsigned int minLen)
+ {
+     SECItem *item = NULL;
+ 
+-    if (cmsg == NULL) {
++    if (cmsg == NULL)
+         return PR_TRUE;
+-    }
+ 
+     item = NSS_CMSContentInfo_GetContent(NSS_CMSMessage_GetContentInfo(cmsg));
+ 
+     if (!item) {
+         return PR_TRUE;
+     } else if (item->len <= minLen) {
+         return PR_TRUE;
+     }
+diff --git a/security/nss/lib/smime/cmsrecinfo.c b/security/nss/lib/smime/cmsrecinfo.c
+--- a/security/nss/lib/smime/cmsrecinfo.c
++++ b/security/nss/lib/smime/cmsrecinfo.c
+@@ -77,17 +77,17 @@ nss_cmsrecipientinfo_create(NSSCMSMessag
+     if (ri == NULL)
+         goto loser;
+ 
+     ri->cmsg = cmsg;
+ 
+     if (DERinput) {
+         /* decode everything from DER */
+         SECItem newinput;
+-        SECStatus rv = SECITEM_CopyItem(poolp, &newinput, DERinput);
++        rv = SECITEM_CopyItem(poolp, &newinput, DERinput);
+         if (SECSuccess != rv)
+             goto loser;
+         rv = SEC_QuickDERDecodeItem(poolp, ri, NSSCMSRecipientInfoTemplate, &newinput);
+         if (SECSuccess != rv)
+             goto loser;
+     }
+ 
+     switch (type) {
+diff --git a/security/nss/lib/smime/cmsudf.c b/security/nss/lib/smime/cmsudf.c
+--- a/security/nss/lib/smime/cmsudf.c
++++ b/security/nss/lib/smime/cmsudf.c
+@@ -234,17 +234,17 @@ NSS_CMSType_GetContentSize(SECOidTag typ
+     return sizeof(SECItem *);
+ }
+ 
+ void
+ NSS_CMSGenericWrapperData_Destroy(SECOidTag type, NSSCMSGenericWrapperData *gd)
+ {
+     const nsscmstypeInfo *typeInfo = nss_cmstype_lookup(type);
+ 
+-    if (typeInfo && (typeInfo->destroy) && (gd != NULL)) {
++    if (typeInfo && typeInfo->destroy) {
+         (*typeInfo->destroy)(gd);
+     }
+ }
+ 
+ SECStatus
+ NSS_CMSGenericWrapperData_Decode_BeforeData(SECOidTag type,
+                                             NSSCMSGenericWrapperData *gd)
+ {
+diff --git a/security/nss/lib/softoken/legacydb/lgattr.c b/security/nss/lib/softoken/legacydb/lgattr.c
+--- a/security/nss/lib/softoken/legacydb/lgattr.c
++++ b/security/nss/lib/softoken/legacydb/lgattr.c
+@@ -945,19 +945,19 @@ lg_FindECPrivateKeyAttribute(NSSLOWKEYPr
+         case CKA_DERIVE:
+         case CKA_SIGN:
+             return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr);
+         case CKA_DECRYPT:
+         case CKA_SIGN_RECOVER:
+         case CKA_UNWRAP:
+             return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr);
+         case CKA_VALUE:
+-            return lg_CopyPrivAttribute(attribute, type,
+-                                        key->u.ec.privateValue.data,
+-                                        key->u.ec.privateValue.len, sdbpw);
++            return lg_CopyPrivAttrSigned(attribute, type,
++                                         key->u.ec.privateValue.data,
++                                         key->u.ec.privateValue.len, sdbpw);
+         case CKA_EC_PARAMS:
+             return lg_CopyAttributeSigned(attribute, type,
+                                           key->u.ec.ecParams.DEREncoding.data,
+                                           key->u.ec.ecParams.DEREncoding.len);
+         case CKA_NETSCAPE_DB:
+             return lg_CopyAttributeSigned(attribute, type,
+                                           key->u.ec.publicValue.data,
+                                           key->u.ec.publicValue.len);
+diff --git a/security/nss/lib/softoken/lowkey.c b/security/nss/lib/softoken/lowkey.c
+--- a/security/nss/lib/softoken/lowkey.c
++++ b/security/nss/lib/softoken/lowkey.c
+@@ -40,16 +40,33 @@ const SEC_ASN1Template nsslowkey_Private
+     { SEC_ASN1_OCTET_STRING,
+       offsetof(NSSLOWKEYPrivateKeyInfo, privateKey) },
+     { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0,
+       offsetof(NSSLOWKEYPrivateKeyInfo, attributes),
+       nsslowkey_SetOfAttributeTemplate },
+     { 0 }
+ };
+ 
++const SEC_ASN1Template nsslowkey_SubjectPublicKeyInfoTemplate[] = {
++    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYSubjectPublicKeyInfo) },
++    { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
++      offsetof(NSSLOWKEYSubjectPublicKeyInfo, algorithm),
++      SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
++    { SEC_ASN1_BIT_STRING,
++      offsetof(NSSLOWKEYSubjectPublicKeyInfo, subjectPublicKey) },
++    { 0 }
++};
++
++const SEC_ASN1Template nsslowkey_RSAPublicKeyTemplate[] = {
++    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPublicKey) },
++    { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey, u.rsa.modulus) },
++    { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey, u.rsa.publicExponent) },
++    { 0 }
++};
++
+ const SEC_ASN1Template nsslowkey_PQGParamsTemplate[] = {
+     { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(PQGParams) },
+     { SEC_ASN1_INTEGER, offsetof(PQGParams, prime) },
+     { SEC_ASN1_INTEGER, offsetof(PQGParams, subPrime) },
+     { SEC_ASN1_INTEGER, offsetof(PQGParams, base) },
+     { 0 }
+ };
+ 
+@@ -130,16 +147,23 @@ prepare_low_rsa_priv_key_for_asn1(NSSLOW
+     key->u.rsa.prime1.type = siUnsignedInteger;
+     key->u.rsa.prime2.type = siUnsignedInteger;
+     key->u.rsa.exponent1.type = siUnsignedInteger;
+     key->u.rsa.exponent2.type = siUnsignedInteger;
+     key->u.rsa.coefficient.type = siUnsignedInteger;
+ }
+ 
+ void
++prepare_low_rsa_pub_key_for_asn1(NSSLOWKEYPublicKey *key)
++{
++    key->u.rsa.modulus.type = siUnsignedInteger;
++    key->u.rsa.publicExponent.type = siUnsignedInteger;
++}
++
++void
+ prepare_low_pqg_params_for_asn1(PQGParams *params)
+ {
+     params->prime.type = siUnsignedInteger;
+     params->subPrime.type = siUnsignedInteger;
+     params->base.type = siUnsignedInteger;
+ }
+ 
+ void
+diff --git a/security/nss/lib/softoken/lowkeyi.h b/security/nss/lib/softoken/lowkeyi.h
+--- a/security/nss/lib/softoken/lowkeyi.h
++++ b/security/nss/lib/softoken/lowkeyi.h
+@@ -22,16 +22,17 @@ SEC_BEGIN_PROTOS
+  */
+ extern void prepare_low_rsa_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
+ extern void prepare_low_pqg_params_for_asn1(PQGParams *params);
+ extern void prepare_low_dsa_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
+ extern void prepare_low_dsa_priv_key_export_for_asn1(NSSLOWKEYPrivateKey *key);
+ extern void prepare_low_dh_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
+ extern void prepare_low_ec_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
+ extern void prepare_low_ecparams_for_asn1(ECParams *params);
++extern void prepare_low_rsa_pub_key_for_asn1(NSSLOWKEYPublicKey *key);
+ 
+ /*
+ ** Destroy a private key object.
+ **  "key" the object
+ **  "freeit" if PR_TRUE then free the object as well as its sub-objects
+ */
+ extern void nsslowkey_DestroyPrivateKey(NSSLOWKEYPrivateKey *key);
+ 
+diff --git a/security/nss/lib/softoken/lowkeyti.h b/security/nss/lib/softoken/lowkeyti.h
+--- a/security/nss/lib/softoken/lowkeyti.h
++++ b/security/nss/lib/softoken/lowkeyti.h
+@@ -20,16 +20,18 @@ extern const SEC_ASN1Template nsslowkey_
+ extern const SEC_ASN1Template nsslowkey_DSAPrivateKeyExportTemplate[];
+ extern const SEC_ASN1Template nsslowkey_DHPrivateKeyTemplate[];
+ extern const SEC_ASN1Template nsslowkey_DHPrivateKeyExportTemplate[];
+ #define NSSLOWKEY_EC_PRIVATE_KEY_VERSION 1 /* as per SECG 1 C.4 */
+ extern const SEC_ASN1Template nsslowkey_ECPrivateKeyTemplate[];
+ 
+ extern const SEC_ASN1Template nsslowkey_PrivateKeyInfoTemplate[];
+ extern const SEC_ASN1Template nsslowkey_EncryptedPrivateKeyInfoTemplate[];
++extern const SEC_ASN1Template nsslowkey_SubjectPublicKeyInfoTemplate[];
++extern const SEC_ASN1Template nsslowkey_RSAPublicKeyTemplate[];
+ 
+ /*
+  * PKCS #8 attributes
+  */
+ struct NSSLOWKEYAttributeStr {
+     SECItem attrType;
+     SECItem *attrValue;
+ };
+@@ -43,16 +45,23 @@ struct NSSLOWKEYPrivateKeyInfoStr {
+     SECItem version;
+     SECAlgorithmID algorithm;
+     SECItem privateKey;
+     NSSLOWKEYAttribute **attributes;
+ };
+ typedef struct NSSLOWKEYPrivateKeyInfoStr NSSLOWKEYPrivateKeyInfo;
+ #define NSSLOWKEY_PRIVATE_KEY_INFO_VERSION 0 /* what we *create* */
+ 
++struct NSSLOWKEYSubjectPublicKeyInfoStr {
++    PLArenaPool *arena;
++    SECAlgorithmID algorithm;
++    SECItem subjectPublicKey;
++};
++typedef struct NSSLOWKEYSubjectPublicKeyInfoStr NSSLOWKEYSubjectPublicKeyInfo;
++
+ typedef enum {
+     NSSLOWKEYNullKey = 0,
+     NSSLOWKEYRSAKey = 1,
+     NSSLOWKEYDSAKey = 2,
+     NSSLOWKEYDHKey = 4,
+     NSSLOWKEYECKey = 5
+ } NSSLOWKEYType;
+ 
+diff --git a/security/nss/lib/softoken/lowpbe.c b/security/nss/lib/softoken/lowpbe.c
+--- a/security/nss/lib/softoken/lowpbe.c
++++ b/security/nss/lib/softoken/lowpbe.c
+@@ -1068,25 +1068,25 @@ sec_pkcs5_rc2(SECItem *key, SECItem *iv,
+     }
+ 
+     dup_src = SECITEM_DupItem(src);
+     if (dup_src == NULL) {
+         return NULL;
+     }
+ 
+     if (encrypt != PR_FALSE) {
+-        void *dummy;
++        void *v;
+ 
+-        dummy = CBC_PadBuffer(NULL, dup_src->data,
+-                              dup_src->len, &dup_src->len, 8 /* RC2_BLOCK_SIZE */);
+-        if (dummy == NULL) {
++        v = CBC_PadBuffer(NULL, dup_src->data,
++                          dup_src->len, &dup_src->len, 8 /* RC2_BLOCK_SIZE */);
++        if (v == NULL) {
+             SECITEM_FreeItem(dup_src, PR_TRUE);
+             return NULL;
+         }
+-        dup_src->data = (unsigned char *)dummy;
++        dup_src->data = (unsigned char *)v;
+     }
+ 
+     dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem));
+     if (dest != NULL) {
+         dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64);
+         if (dest->data != NULL) {
+             RC2Context *ctxt;
+ 
+diff --git a/security/nss/lib/softoken/pkcs11.c b/security/nss/lib/softoken/pkcs11.c
+--- a/security/nss/lib/softoken/pkcs11.c
++++ b/security/nss/lib/softoken/pkcs11.c
+@@ -1338,17 +1338,16 @@ sftk_handleSecretKeyObject(SFTKSession *
+     crv = validateSecretKey(session, object, key_type, isFIPS);
+     if (crv != CKR_OK)
+         goto loser;
+ 
+     /* If the object is a TOKEN object, store in the database */
+     if (sftk_isTrue(object, CKA_TOKEN)) {
+         SFTKSlot *slot = session->slot;
+         SFTKDBHandle *keyHandle = sftk_getKeyDB(slot);
+-        CK_RV crv;
+ 
+         if (keyHandle == NULL) {
+             return CKR_TOKEN_WRITE_PROTECTED;
+         }
+ 
+         crv = sftkdb_write(keyHandle, object, &object->handle);
+         sftk_freeDB(keyHandle);
+         return crv;
+@@ -3802,22 +3801,22 @@ NSC_SetPIN(CK_SESSION_HANDLE hSession, C
+     /* Now update our local copy of the pin */
+     if (rv == SECSuccess) {
+         PZ_Lock(slot->slotLock);
+         slot->needLogin = (PRBool)(ulNewLen != 0);
+         slot->isLoggedIn = (PRBool)(sftkdb_PWCached(handle) == SECSuccess);
+         PZ_Unlock(slot->slotLock);
+         /* Reset login flags. */
+         if (ulNewLen == 0) {
+-            PRBool tokenRemoved = PR_FALSE;
+             PZ_Lock(slot->slotLock);
+             slot->isLoggedIn = PR_FALSE;
+             slot->ssoLoggedIn = PR_FALSE;
+             PZ_Unlock(slot->slotLock);
+ 
++            tokenRemoved = PR_FALSE;
+             rv = sftkdb_CheckPassword(handle, "", &tokenRemoved);
+             if (tokenRemoved) {
+                 sftk_CloseAllSessions(slot, PR_FALSE);
+             }
+         }
+         sftk_update_all_states(slot);
+         sftk_freeDB(handle);
+         return CKR_OK;
+@@ -4417,16 +4416,54 @@ NSC_GetObjectSize(CK_SESSION_HANDLE hSes
+                   CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize)
+ {
+     CHECK_FORK();
+ 
+     *pulSize = 0;
+     return CKR_OK;
+ }
+ 
++static CK_RV
++nsc_GetTokenAttributeValue(SFTKSession *session, CK_OBJECT_HANDLE hObject,
++                           CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
++{
++    SFTKSlot *slot = sftk_SlotFromSession(session);
++    SFTKDBHandle *dbHandle = sftk_getDBForTokenObject(slot, hObject);
++    SFTKDBHandle *keydb = NULL;
++    CK_RV crv;
++
++    if (dbHandle == NULL) {
++        return CKR_OBJECT_HANDLE_INVALID;
++    }
++
++    crv = sftkdb_GetAttributeValue(dbHandle, hObject, pTemplate, ulCount);
++
++    /* make sure we don't export any sensitive information */
++    keydb = sftk_getKeyDB(slot);
++    if (dbHandle == keydb) {
++        CK_ULONG i;
++        for (i = 0; i < ulCount; i++) {
++            if (sftk_isSensitive(pTemplate[i].type, CKO_PRIVATE_KEY)) {
++                crv = CKR_ATTRIBUTE_SENSITIVE;
++                if (pTemplate[i].pValue && (pTemplate[i].ulValueLen != -1)) {
++                    PORT_Memset(pTemplate[i].pValue, 0,
++                                pTemplate[i].ulValueLen);
++                }
++                pTemplate[i].ulValueLen = -1;
++            }
++        }
++    }
++
++    sftk_freeDB(dbHandle);
++    if (keydb) {
++        sftk_freeDB(keydb);
++    }
++    return crv;
++}
++
+ /* NSC_GetAttributeValue obtains the value of one or more object attributes. */
+ CK_RV
+ NSC_GetAttributeValue(CK_SESSION_HANDLE hSession,
+                       CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
+ {
+     SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession);
+     SFTKSession *session;
+     SFTKObject *object;
+@@ -4445,47 +4482,18 @@ NSC_GetAttributeValue(CK_SESSION_HANDLE 
+      */
+     session = sftk_SessionFromHandle(hSession);
+     if (session == NULL) {
+         return CKR_SESSION_HANDLE_INVALID;
+     }
+ 
+     /* short circuit everything for token objects */
+     if (sftk_isToken(hObject)) {
+-        SFTKSlot *slot = sftk_SlotFromSession(session);
+-        SFTKDBHandle *dbHandle = sftk_getDBForTokenObject(slot, hObject);
+-        SFTKDBHandle *keydb = NULL;
+-
+-        if (dbHandle == NULL) {
+-            sftk_FreeSession(session);
+-            return CKR_OBJECT_HANDLE_INVALID;
+-        }
+-
+-        crv = sftkdb_GetAttributeValue(dbHandle, hObject, pTemplate, ulCount);
+-
+-        /* make sure we don't export any sensitive information */
+-        keydb = sftk_getKeyDB(slot);
+-        if (dbHandle == keydb) {
+-            for (i = 0; i < (int)ulCount; i++) {
+-                if (sftk_isSensitive(pTemplate[i].type, CKO_PRIVATE_KEY)) {
+-                    crv = CKR_ATTRIBUTE_SENSITIVE;
+-                    if (pTemplate[i].pValue && (pTemplate[i].ulValueLen != -1)) {
+-                        PORT_Memset(pTemplate[i].pValue, 0,
+-                                    pTemplate[i].ulValueLen);
+-                    }
+-                    pTemplate[i].ulValueLen = -1;
+-                }
+-            }
+-        }
+-
++        crv = nsc_GetTokenAttributeValue(session, hObject, pTemplate, ulCount);
+         sftk_FreeSession(session);
+-        sftk_freeDB(dbHandle);
+-        if (keydb) {
+-            sftk_freeDB(keydb);
+-        }
+         return crv;
+     }
+ 
+     /* handle the session object */
+     object = sftk_ObjectFromHandle(hObject, session);
+     sftk_FreeSession(session);
+     if (object == NULL) {
+         return CKR_OBJECT_HANDLE_INVALID;
+diff --git a/security/nss/lib/softoken/pkcs11c.c b/security/nss/lib/softoken/pkcs11c.c
+--- a/security/nss/lib/softoken/pkcs11c.c
++++ b/security/nss/lib/softoken/pkcs11c.c
+@@ -5319,17 +5319,62 @@ sftk_PackagePrivateKey(SFTKObject *key, 
+     pki->arena = arena;
+ 
+     param = NULL;
+     switch (lk->keyType) {
+         case NSSLOWKEYRSAKey:
+             prepare_low_rsa_priv_key_for_asn1(lk);
+             dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk,
+                                        nsslowkey_RSAPrivateKeyTemplate);
+-            algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION;
++
++            /* determine RSA key type from the CKA_PUBLIC_KEY_INFO if present */
++            attribute = sftk_FindAttribute(key, CKA_PUBLIC_KEY_INFO);
++            if (attribute) {
++                NSSLOWKEYSubjectPublicKeyInfo *publicKeyInfo;
++                SECItem spki;
++
++                spki.data = attribute->attrib.pValue;
++                spki.len = attribute->attrib.ulValueLen;
++
++                publicKeyInfo = PORT_ArenaZAlloc(arena,
++                                                 sizeof(NSSLOWKEYSubjectPublicKeyInfo));
++                if (!publicKeyInfo) {
++                    sftk_FreeAttribute(attribute);
++                    *crvp = CKR_HOST_MEMORY;
++                    rv = SECFailure;
++                    goto loser;
++                }
++                rv = SEC_QuickDERDecodeItem(arena, publicKeyInfo,
++                                            nsslowkey_SubjectPublicKeyInfoTemplate,
++                                            &spki);
++                if (rv != SECSuccess) {
++                    sftk_FreeAttribute(attribute);
++                    *crvp = CKR_KEY_TYPE_INCONSISTENT;
++                    goto loser;
++                }
++                algorithm = SECOID_GetAlgorithmTag(&publicKeyInfo->algorithm);
++                if (algorithm != SEC_OID_PKCS1_RSA_ENCRYPTION &&
++                    algorithm != SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
++                    sftk_FreeAttribute(attribute);
++                    rv = SECFailure;
++                    *crvp = CKR_KEY_TYPE_INCONSISTENT;
++                    goto loser;
++                }
++                param = SECITEM_DupItem(&publicKeyInfo->algorithm.parameters);
++                if (!param) {
++                    sftk_FreeAttribute(attribute);
++                    rv = SECFailure;
++                    *crvp = CKR_HOST_MEMORY;
++                    goto loser;
++                }
++                sftk_FreeAttribute(attribute);
++            } else {
++                /* default to PKCS #1 */
++                algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION;
++            }
+             break;
+         case NSSLOWKEYDSAKey:
+             prepare_low_dsa_priv_key_export_for_asn1(lk);
+             dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk,
+                                        nsslowkey_DSAPrivateKeyExportTemplate);
+             prepare_low_pqg_params_for_asn1(&lk->u.dsa.params);
+             param = SEC_ASN1EncodeItem(NULL, NULL, &(lk->u.dsa.params),
+                                        nsslowkey_PQGParamsTemplate);
+@@ -5798,16 +5843,63 @@ sftk_unwrapPrivateKey(SFTKObject *key, S
+                 break;
+             /* XXX Do we need to decode the EC Params here ?? */
+             break;
+         default:
+             crv = CKR_KEY_TYPE_INCONSISTENT;
+             break;
+     }
+ 
++    if (crv != CKR_OK) {
++        goto loser;
++    }
++
++    /* For RSA-PSS, record the original algorithm parameters so
++     * they can be encrypted altoghether when wrapping */
++    if (SECOID_GetAlgorithmTag(&pki->algorithm) == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
++        NSSLOWKEYSubjectPublicKeyInfo spki;
++        NSSLOWKEYPublicKey pubk;
++        SECItem *publicKeyInfo;
++
++        memset(&spki, 0, sizeof(NSSLOWKEYSubjectPublicKeyInfo));
++        rv = SECOID_CopyAlgorithmID(arena, &spki.algorithm, &pki->algorithm);
++        if (rv != SECSuccess) {
++            crv = CKR_HOST_MEMORY;
++            goto loser;
++        }
++
++        prepare_low_rsa_pub_key_for_asn1(&pubk);
++
++        rv = SECITEM_CopyItem(arena, &pubk.u.rsa.modulus, &lpk->u.rsa.modulus);
++        if (rv != SECSuccess) {
++            crv = CKR_HOST_MEMORY;
++            goto loser;
++        }
++        rv = SECITEM_CopyItem(arena, &pubk.u.rsa.publicExponent, &lpk->u.rsa.publicExponent);
++        if (rv != SECSuccess) {
++            crv = CKR_HOST_MEMORY;
++            goto loser;
++        }
++
++        if (SEC_ASN1EncodeItem(arena, &spki.subjectPublicKey,
++                               &pubk, nsslowkey_RSAPublicKeyTemplate) == NULL) {
++            crv = CKR_HOST_MEMORY;
++            goto loser;
++        }
++
++        publicKeyInfo = SEC_ASN1EncodeItem(arena, NULL,
++                                           &spki, nsslowkey_SubjectPublicKeyInfoTemplate);
++        if (!publicKeyInfo) {
++            crv = CKR_HOST_MEMORY;
++            goto loser;
++        }
++        crv = sftk_AddAttributeType(key, CKA_PUBLIC_KEY_INFO,
++                                    sftk_item_expand(publicKeyInfo));
++    }
++
+ loser:
+     if (lpk) {
+         nsslowkey_DestroyPrivateKey(lpk);
+     }
+ 
+     if (crv != CKR_OK) {
+         return SECFailure;
+     }
+@@ -7471,17 +7563,17 @@ NSC_DeriveKey(CK_SESSION_HANDLE hSession
+             }
+ 
+             if (mechanism == CKM_ECDH1_COFACTOR_DERIVE) {
+                 withCofactor = PR_TRUE;
+             }
+ 
+             rv = ECDH_Derive(&ecPoint, &privKey->u.ec.ecParams, &ecScalar,
+                              withCofactor, &tmp);
+-            PORT_ZFree(ecScalar.data, ecScalar.len);
++            PORT_Free(ecScalar.data);
+             ecScalar.data = NULL;
+             if (privKey != sourceKey->objectInfo) {
+                 nsslowkey_DestroyPrivateKey(privKey);
+                 privKey = NULL;
+             }
+             if (arena) {
+                 PORT_FreeArena(arena, PR_FALSE);
+                 arena = NULL;
+@@ -7570,23 +7662,23 @@ NSC_DeriveKey(CK_SESSION_HANDLE hSession
+         case CKM_NSS_HKDF_SHA512:
+             hashType = HASH_AlgSHA512;
+             goto hkdf;
+         hkdf : {
+             const CK_NSS_HKDFParams *params =
+                 (const CK_NSS_HKDFParams *)pMechanism->pParameter;
+             const SECHashObject *rawHash;
+             unsigned hashLen;
+-            CK_BYTE buf[HASH_LENGTH_MAX];
++            CK_BYTE hashbuf[HASH_LENGTH_MAX];
+             CK_BYTE *prk; /* psuedo-random key */
+             CK_ULONG prkLen;
+             CK_BYTE *okm; /* output keying material */
+ 
+             rawHash = HASH_GetRawHashObject(hashType);
+-            if (rawHash == NULL || rawHash->length > sizeof buf) {
++            if (rawHash == NULL || rawHash->length > sizeof(hashbuf)) {
+                 crv = CKR_FUNCTION_FAILED;
+                 break;
+             }
+             hashLen = rawHash->length;
+ 
+             if (pMechanism->ulParameterLen != sizeof(CK_NSS_HKDFParams) ||
+                 !params || (!params->bExpand && !params->bExtract) ||
+                 (params->bExtract && params->ulSaltLen > 0 && !params->pSalt) ||
+@@ -7610,65 +7702,65 @@ NSC_DeriveKey(CK_SESSION_HANDLE hSession
+                 CK_ULONG saltLen;
+                 HMACContext *hmac;
+                 unsigned int bufLen;
+ 
+                 salt = params->pSalt;
+                 saltLen = params->ulSaltLen;
+                 if (salt == NULL) {
+                     saltLen = hashLen;
+-                    salt = buf;
++                    salt = hashbuf;
+                     memset(salt, 0, saltLen);
+                 }
+                 hmac = HMAC_Create(rawHash, salt, saltLen, isFIPS);
+                 if (!hmac) {
+                     crv = CKR_HOST_MEMORY;
+                     break;
+                 }
+                 HMAC_Begin(hmac);
+                 HMAC_Update(hmac, (const unsigned char *)att->attrib.pValue,
+                             att->attrib.ulValueLen);
+-                HMAC_Finish(hmac, buf, &bufLen, sizeof(buf));
++                HMAC_Finish(hmac, hashbuf, &bufLen, sizeof(hashbuf));
+                 HMAC_Destroy(hmac, PR_TRUE);
+                 PORT_Assert(bufLen == rawHash->length);
+-                prk = buf;
++                prk = hashbuf;
+                 prkLen = bufLen;
+             } else {
+                 /* PRK = base key value */
+                 prk = (CK_BYTE *)att->attrib.pValue;
+                 prkLen = att->attrib.ulValueLen;
+             }
+ 
+             /* HKDF-Expand */
+             if (!params->bExpand) {
+                 okm = prk;
+             } else {
+                 /* T(1) = HMAC-Hash(prk, "" | info | 0x01)
+                  * T(n) = HMAC-Hash(prk, T(n-1) | info | n
+                  * key material = T(1) | ... | T(n)
+                  */
+                 HMACContext *hmac;
+-                CK_BYTE i;
++                CK_BYTE bi;
+                 unsigned iterations = PR_ROUNDUP(keySize, hashLen) / hashLen;
+                 hmac = HMAC_Create(rawHash, prk, prkLen, isFIPS);
+                 if (hmac == NULL) {
+                     crv = CKR_HOST_MEMORY;
+                     break;
+                 }
+-                for (i = 1; i <= iterations; ++i) {
++                for (bi = 1; bi <= iterations; ++bi) {
+                     unsigned len;
+                     HMAC_Begin(hmac);
+-                    if (i > 1) {
+-                        HMAC_Update(hmac, key_block + ((i - 2) * hashLen), hashLen);
++                    if (bi > 1) {
++                        HMAC_Update(hmac, key_block + ((bi - 2) * hashLen), hashLen);
+                     }
+                     if (params->ulInfoLen != 0) {
+                         HMAC_Update(hmac, params->pInfo, params->ulInfoLen);
+                     }
+-                    HMAC_Update(hmac, &i, 1);
+-                    HMAC_Finish(hmac, key_block + ((i - 1) * hashLen), &len,
++                    HMAC_Update(hmac, &bi, 1);
++                    HMAC_Finish(hmac, key_block + ((bi - 1) * hashLen), &len,
+                                 hashLen);
+                     PORT_Assert(len == hashLen);
+                 }
+                 HMAC_Destroy(hmac, PR_TRUE);
+                 okm = key_block;
+             }
+             /* key material = prk */
+             crv = sftk_forceAttribute(key, CKA_VALUE, okm, keySize);
+diff --git a/security/nss/lib/softoken/pkcs11u.c b/security/nss/lib/softoken/pkcs11u.c
+--- a/security/nss/lib/softoken/pkcs11u.c
++++ b/security/nss/lib/softoken/pkcs11u.c
+@@ -1188,17 +1188,17 @@ sftk_DeleteObject(SFTKSession *session, 
+ {
+     SFTKSlot *slot = sftk_SlotFromSession(session);
+     SFTKSessionObject *so = sftk_narrowToSessionObject(object);
+     CK_RV crv = CKR_OK;
+     PRUint32 index = sftk_hash(object->handle, slot->sessObjHashSize);
+ 
+     /* Handle Token case */
+     if (so && so->session) {
+-        SFTKSession *session = so->session;
++        session = so->session;
+         PZ_Lock(session->objectLock);
+         sftkqueue_delete(&so->sessionList, 0, session->objects, 0);
+         PZ_Unlock(session->objectLock);
+         PZ_Lock(slot->objectLock);
+         sftkqueue_delete2(object, object->handle, index, slot->sessObjHashTable);
+         PZ_Unlock(slot->objectLock);
+         sftkqueue_clear_deleted_element(object);
+         sftk_FreeObject(object); /* free the reference owned by the queue */
+@@ -1264,17 +1264,17 @@ static const CK_ULONG dhPubKeyAttrsCount
+ static const CK_ATTRIBUTE_TYPE ecPubKeyAttrs[] = {
+     CKA_EC_PARAMS, CKA_EC_POINT
+ };
+ static const CK_ULONG ecPubKeyAttrsCount =
+     sizeof(ecPubKeyAttrs) / sizeof(ecPubKeyAttrs[0]);
+ 
+ static const CK_ATTRIBUTE_TYPE commonPrivKeyAttrs[] = {
+     CKA_DECRYPT, CKA_SIGN, CKA_SIGN_RECOVER, CKA_UNWRAP, CKA_SUBJECT,
+-    CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_NETSCAPE_DB
++    CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_NETSCAPE_DB, CKA_PUBLIC_KEY_INFO
+ };
+ static const CK_ULONG commonPrivKeyAttrsCount =
+     sizeof(commonPrivKeyAttrs) / sizeof(commonPrivKeyAttrs[0]);
+ 
+ static const CK_ATTRIBUTE_TYPE rsaPrivKeyAttrs[] = {
+     CKA_MODULUS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT,
+     CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT
+ };
+diff --git a/security/nss/lib/softoken/sdb.c b/security/nss/lib/softoken/sdb.c
+--- a/security/nss/lib/softoken/sdb.c
++++ b/security/nss/lib/softoken/sdb.c
+@@ -149,17 +149,18 @@ static const CK_ATTRIBUTE_TYPE known_att
+     CKA_NETSCAPE_PQG_H, CKA_NETSCAPE_PQG_SEED_BITS, CKA_NETSCAPE_MODULE_SPEC,
+     CKA_TRUST_DIGITAL_SIGNATURE, CKA_TRUST_NON_REPUDIATION,
+     CKA_TRUST_KEY_ENCIPHERMENT, CKA_TRUST_DATA_ENCIPHERMENT,
+     CKA_TRUST_KEY_AGREEMENT, CKA_TRUST_KEY_CERT_SIGN, CKA_TRUST_CRL_SIGN,
+     CKA_TRUST_SERVER_AUTH, CKA_TRUST_CLIENT_AUTH, CKA_TRUST_CODE_SIGNING,
+     CKA_TRUST_EMAIL_PROTECTION, CKA_TRUST_IPSEC_END_SYSTEM,
+     CKA_TRUST_IPSEC_TUNNEL, CKA_TRUST_IPSEC_USER, CKA_TRUST_TIME_STAMPING,
+     CKA_TRUST_STEP_UP_APPROVED, CKA_CERT_SHA1_HASH, CKA_CERT_MD5_HASH,
+-    CKA_NETSCAPE_DB, CKA_NETSCAPE_TRUST, CKA_NSS_OVERRIDE_EXTENSIONS
++    CKA_NETSCAPE_DB, CKA_NETSCAPE_TRUST, CKA_NSS_OVERRIDE_EXTENSIONS,
++    CKA_PUBLIC_KEY_INFO
+ };
+ 
+ static int known_attributes_size = sizeof(known_attributes) /
+                                    sizeof(known_attributes[0]);
+ 
+ /* Magic for an explicit NULL. NOTE: ideally this should be
+  * out of band data. Since it's not completely out of band, pick
+  * a value that has no meaning to any existing PKCS #11 attributes.
+diff --git a/security/nss/lib/softoken/sftkdb.c b/security/nss/lib/softoken/sftkdb.c
+--- a/security/nss/lib/softoken/sftkdb.c
++++ b/security/nss/lib/softoken/sftkdb.c
+@@ -1586,17 +1586,18 @@ static const CK_ATTRIBUTE_TYPE known_att
+     CKA_NSS_PQG_H, CKA_NSS_PQG_SEED_BITS, CKA_NSS_MODULE_SPEC,
+     CKA_TRUST_DIGITAL_SIGNATURE, CKA_TRUST_NON_REPUDIATION,
+     CKA_TRUST_KEY_ENCIPHERMENT, CKA_TRUST_DATA_ENCIPHERMENT,
+     CKA_TRUST_KEY_AGREEMENT, CKA_TRUST_KEY_CERT_SIGN, CKA_TRUST_CRL_SIGN,
+     CKA_TRUST_SERVER_AUTH, CKA_TRUST_CLIENT_AUTH, CKA_TRUST_CODE_SIGNING,
+     CKA_TRUST_EMAIL_PROTECTION, CKA_TRUST_IPSEC_END_SYSTEM,
+     CKA_TRUST_IPSEC_TUNNEL, CKA_TRUST_IPSEC_USER, CKA_TRUST_TIME_STAMPING,
+     CKA_TRUST_STEP_UP_APPROVED, CKA_CERT_SHA1_HASH, CKA_CERT_MD5_HASH,
+-    CKA_NETSCAPE_DB, CKA_NETSCAPE_TRUST, CKA_NSS_OVERRIDE_EXTENSIONS
++    CKA_NETSCAPE_DB, CKA_NETSCAPE_TRUST, CKA_NSS_OVERRIDE_EXTENSIONS,
++    CKA_PUBLIC_KEY_INFO
+ };
+ 
+ static unsigned int known_attributes_size = sizeof(known_attributes) /
+                                             sizeof(known_attributes[0]);
+ 
+ static CK_RV
+ sftkdb_GetObjectTemplate(SDB *source, CK_OBJECT_HANDLE id,
+                          CK_ATTRIBUTE *ptemplate, CK_ULONG *max)
+diff --git a/security/nss/lib/softoken/sftkpars.c b/security/nss/lib/softoken/sftkpars.c
+--- a/security/nss/lib/softoken/sftkpars.c
++++ b/security/nss/lib/softoken/sftkpars.c
+@@ -157,50 +157,50 @@ sftk_parseParameters(char *param, sftk_p
+         NSSUTIL_HANDLE_STRING_ARG(index, tmp, "flags=",
+                                   if (tmp) { sftk_parseFlags(param,parsed); PORT_Free(tmp); tmp = NULL; })
+         NSSUTIL_HANDLE_STRING_ARG(index, tmp, "tokens=",
+                                   if (tmp) { sftk_parseTokens(tmp,parsed); PORT_Free(tmp); tmp = NULL; })
+         NSSUTIL_HANDLE_FINAL_ARG(index)
+     }
+     if (parsed->tokens == NULL) {
+         int count = isFIPS ? 1 : 2;
+-        int index = count - 1;
++        int i = count - 1;
+         sftk_token_parameters *tokens = NULL;
+ 
+         tokens = (sftk_token_parameters *)
+             PORT_ZAlloc(count * sizeof(sftk_token_parameters));
+         if (tokens == NULL) {
+             goto loser;
+         }
+         parsed->tokens = tokens;
+         parsed->token_count = count;
+-        tokens[index].slotID = isFIPS ? FIPS_SLOT_ID : PRIVATE_KEY_SLOT_ID;
+-        tokens[index].certPrefix = certPrefix;
+-        tokens[index].keyPrefix = keyPrefix;
+-        tokens[index].minPW = minPW ? atoi(minPW) : 0;
+-        tokens[index].readOnly = parsed->readOnly;
+-        tokens[index].noCertDB = parsed->noCertDB;
+-        tokens[index].noKeyDB = parsed->noCertDB;
+-        tokens[index].forceOpen = parsed->forceOpen;
+-        tokens[index].pwRequired = parsed->pwRequired;
+-        tokens[index].optimizeSpace = parsed->optimizeSpace;
++        tokens[i].slotID = isFIPS ? FIPS_SLOT_ID : PRIVATE_KEY_SLOT_ID;
++        tokens[i].certPrefix = certPrefix;
++        tokens[i].keyPrefix = keyPrefix;
++        tokens[i].minPW = minPW ? atoi(minPW) : 0;
++        tokens[i].readOnly = parsed->readOnly;
++        tokens[i].noCertDB = parsed->noCertDB;
++        tokens[i].noKeyDB = parsed->noCertDB;
++        tokens[i].forceOpen = parsed->forceOpen;
++        tokens[i].pwRequired = parsed->pwRequired;
++        tokens[i].optimizeSpace = parsed->optimizeSpace;
+         tokens[0].optimizeSpace = parsed->optimizeSpace;
+         certPrefix = NULL;
+         keyPrefix = NULL;
+         if (isFIPS) {
+-            tokens[index].tokdes = ftokdes;
+-            tokens[index].updtokdes = pupdtokdes;
+-            tokens[index].slotdes = fslotdes;
++            tokens[i].tokdes = ftokdes;
++            tokens[i].updtokdes = pupdtokdes;
++            tokens[i].slotdes = fslotdes;
+             fslotdes = NULL;
+             ftokdes = NULL;
+             pupdtokdes = NULL;
+         } else {
+-            tokens[index].tokdes = ptokdes;
+-            tokens[index].updtokdes = pupdtokdes;
+-            tokens[index].slotdes = pslotdes;
++            tokens[i].tokdes = ptokdes;
++            tokens[i].updtokdes = pupdtokdes;
++            tokens[i].slotdes = pslotdes;
+             tokens[0].slotID = NETSCAPE_SLOT_ID;
+             tokens[0].tokdes = tokdes;
+             tokens[0].slotdes = slotdes;
+             tokens[0].noCertDB = PR_TRUE;
+             tokens[0].noKeyDB = PR_TRUE;
+             pupdtokdes = NULL;
+             ptokdes = NULL;
+             pslotdes = NULL;
+diff --git a/security/nss/lib/softoken/softkver.h b/security/nss/lib/softoken/softkver.h
+--- a/security/nss/lib/softoken/softkver.h
++++ b/security/nss/lib/softoken/softkver.h
+@@ -12,16 +12,16 @@
+ 
+ /*
+  * Softoken's major version, minor version, patch level, build number,
+  * and whether this is a beta release.
+  *
+  * The format of the version string should be
+  *     "<major version>.<minor version>[.<patch level>[.<build number>]][ <ECC>][ <Beta>]"
+  */
+-#define SOFTOKEN_VERSION "3.36.8" SOFTOKEN_ECC_STRING
++#define SOFTOKEN_VERSION "3.37" SOFTOKEN_ECC_STRING " Beta"
+ #define SOFTOKEN_VMAJOR 3
+-#define SOFTOKEN_VMINOR 36
+-#define SOFTOKEN_VPATCH 8
++#define SOFTOKEN_VMINOR 37
++#define SOFTOKEN_VPATCH 0
+ #define SOFTOKEN_VBUILD 0
+-#define SOFTOKEN_BETA PR_FALSE
++#define SOFTOKEN_BETA PR_TRUE
+ 
+ #endif /* _SOFTKVER_H_ */
+diff --git a/security/nss/lib/ssl/ssl3con.c b/security/nss/lib/ssl/ssl3con.c
+--- a/security/nss/lib/ssl/ssl3con.c
++++ b/security/nss/lib/ssl/ssl3con.c
+@@ -3029,17 +3029,16 @@ ssl3_SendChangeCipherSpecsInt(sslSocket 
+     if (!IS_DTLS(ss)) {
+         PRInt32 sent;
+         sent = ssl3_SendRecord(ss, NULL, content_change_cipher_spec,
+                                &change, 1, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
+         if (sent < 0) {
+             return SECFailure; /* error code set by ssl3_SendRecord */
+         }
+     } else {
+-        SECStatus rv;
+         rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1);
+         if (rv != SECSuccess) {
+             return SECFailure;
+         }
+     }
+     return SECSuccess;
+ }
+ 
+@@ -6147,58 +6146,16 @@ ssl_ClientSetCipherSuite(sslSocket *ss, 
+         PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
+         return SECFailure;
+     }
+ 
+     ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)suite;
+     return ssl3_SetupCipherSuite(ss, initHashes);
+ }
+ 
+-/* Check that session ID we received from the server, if any, matches our
+- * expectations, depending on whether we're in compat mode and whether we
+- * negotiated TLS 1.3+ or TLS 1.2-.
+- */
+-static PRBool
+-ssl_CheckServerSessionIdCorrectness(sslSocket *ss, SECItem *sidBytes)
+-{
+-    sslSessionID *sid = ss->sec.ci.sid;
+-    PRBool sidMatch = PR_FALSE;
+-    PRBool sentFakeSid = PR_FALSE;
+-    PRBool sentRealSid = sid && sid->version < SSL_LIBRARY_VERSION_TLS_1_3;
+-
+-    /* If attempting to resume a TLS 1.2 connection, the session ID won't be a
+-     * fake. Check for the real value. */
+-    if (sentRealSid) {
+-        sidMatch = (sidBytes->len == sid->u.ssl3.sessionIDLength) &&
+-                   PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len) == 0;
+-    } else {
+-        /* Otherwise, the session ID was a fake if TLS 1.3 compat mode is
+-         * enabled.  If so, check for the fake value. */
+-        sentFakeSid = ss->opt.enableTls13CompatMode && !IS_DTLS(ss);
+-        if (sentFakeSid && sidBytes->len == SSL3_SESSIONID_BYTES) {
+-            PRUint8 buf[SSL3_SESSIONID_BYTES];
+-            ssl_MakeFakeSid(ss, buf);
+-            sidMatch = PORT_Memcmp(buf, sidBytes->data, sidBytes->len) == 0;
+-        }
+-    }
+-
+-    /* TLS 1.2: Session ID shouldn't match if we sent a fake. */
+-    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+-        return !sentFakeSid || !sidMatch;
+-    }
+-
+-    /* TLS 1.3: We sent a session ID.  The server's should match. */
+-    if (sentRealSid || sentFakeSid) {
+-        return sidMatch;
+-    }
+-
+-    /* TLS 1.3: The server shouldn't send a session ID. */
+-    return sidBytes->len == 0;
+-}
+-
+ /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
+  * ssl3 ServerHello message.
+  * Caller must hold Handshake and RecvBuf locks.
+  */
+ static SECStatus
+ ssl3_HandleServerHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
+ {
+     PRUint32 cipher;
+@@ -6396,20 +6353,32 @@ ssl3_HandleServerHello(sslSocket *ss, PR
+      * HelloRetryRequest, because cwSpec might be a 0-RTT cipher spec. */
+     if (!ss->firstHsDone && !ss->ssl3.hs.helloRetry) {
+         ssl_GetSpecWriteLock(ss);
+         ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
+         ssl_ReleaseSpecWriteLock(ss);
+     }
+ 
+     /* Check that the session ID is as expected. */
+-    if (!ssl_CheckServerSessionIdCorrectness(ss, &sidBytes)) {
+-        desc = illegal_parameter;
+-        errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+-        goto alert_loser;
++    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
++        PRUint8 buf[SSL3_SESSIONID_BYTES];
++        unsigned int expectedSidLen;
++        if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
++            expectedSidLen = SSL3_SESSIONID_BYTES;
++            ssl_MakeFakeSid(ss, buf);
++        } else {
++            expectedSidLen = 0;
++        }
++        if (sidBytes.len != expectedSidLen ||
++            (expectedSidLen > 0 &&
++             PORT_Memcmp(buf, sidBytes.data, expectedSidLen) != 0)) {
++            desc = illegal_parameter;
++            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
++            goto alert_loser;
++        }
+     }
+ 
+     /* Only initialize hashes if this isn't a Hello Retry. */
+     rv = ssl_ClientSetCipherSuite(ss, ss->version, cipher,
+                                   !isHelloRetry);
+     if (rv != SECSuccess) {
+         desc = illegal_parameter;
+         errCode = PORT_GetError();
+@@ -8077,16 +8046,24 @@ ssl3_HandleClientHello(sslSocket *ss, PR
+         rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.fakeSid, &sidBytes);
+         if (rv != SECSuccess) {
+             desc = internal_error;
+             errCode = PORT_GetError();
+             goto alert_loser;
+         }
+     }
+ 
++    /* Generate the Server Random now so it is available
++     * when we process the ClientKeyShare in TLS 1.3 */
++    rv = ssl3_GetNewRandom(ss->ssl3.hs.server_random);
++    if (rv != SECSuccess) {
++        errCode = SSL_ERROR_GENERATE_RANDOM_FAILURE;
++        goto loser;
++    }
++
+ #ifndef TLS_1_3_DRAFT_VERSION
+     /*
+      * [draft-ietf-tls-tls13-11 Section 6.3.1.1].
+      * TLS 1.3 server implementations which respond to a ClientHello with a
+      * client_version indicating TLS 1.2 or below MUST set the last eight
+      * bytes of their Random value to the bytes:
+      *
+      * 44 4F 57 4E 47 52 44 01
+@@ -8865,39 +8842,30 @@ loser:
+ 
+ SECStatus
+ ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
+                          const sslBuffer *extensionBuf, sslBuffer *messageBuf)
+ {
+     SECStatus rv;
+     SSL3ProtocolVersion version;
+     sslSessionID *sid = ss->sec.ci.sid;
+-    const PRUint8 *random;
+ 
+     if (IS_DTLS(ss) && ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+         version = dtls_TLSVersionToDTLSVersion(ss->version);
+     } else {
+         version = PR_MIN(ss->version, SSL_LIBRARY_VERSION_TLS_1_2);
+     }
+ 
+     rv = sslBuffer_AppendNumber(messageBuf, version, 2);
+     if (rv != SECSuccess) {
+         return SECFailure;
+     }
+-
+-    if (helloRetry) {
+-        random = ssl_hello_retry_random;
+-    } else {
+-        rv = ssl3_GetNewRandom(ss->ssl3.hs.server_random);
+-        if (rv != SECSuccess) {
+-            return SECFailure;
+-        }
+-        random = ss->ssl3.hs.server_random;
+-    }
+-    rv = sslBuffer_Append(messageBuf, random, SSL3_RANDOM_LENGTH);
++    /* Random already generated in ssl3_HandleClientHello */
++    rv = sslBuffer_Append(messageBuf, helloRetry ? ssl_hello_retry_random : ss->ssl3.hs.server_random,
++                          SSL3_RANDOM_LENGTH);
+     if (rv != SECSuccess) {
+         return SECFailure;
+     }
+ 
+     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+         if (sid) {
+             rv = sslBuffer_AppendVariable(messageBuf, sid->u.ssl3.sessionID,
+                                           sid->u.ssl3.sessionIDLength, 1);
+@@ -9493,33 +9461,16 @@ ssl3_GenerateRSAPMS(sslSocket *ss, ssl3C
+     if (!serverKeySlot)
+         PK11_FreeSlot(slot);
+     if (pms == NULL) {
+         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+     }
+     return pms;
+ }
+ 
+-static void
+-ssl3_CSwapPK11SymKey(PK11SymKey **x, PK11SymKey **y, PRBool c)
+-{
+-    uintptr_t mask = (uintptr_t)c;
+-    unsigned int i;
+-    for (i = 1; i < sizeof(uintptr_t) * 8; i <<= 1) {
+-        mask |= mask << i;
+-    }
+-    uintptr_t x_ptr = (uintptr_t)*x;
+-    uintptr_t y_ptr = (uintptr_t)*y;
+-    uintptr_t tmp = (x_ptr ^ y_ptr) & mask;
+-    x_ptr = x_ptr ^ tmp;
+-    y_ptr = y_ptr ^ tmp;
+-    *x = (PK11SymKey *)x_ptr;
+-    *y = (PK11SymKey *)y_ptr;
+-}
+-
+ /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
+  * return any indication of failure of the Client Key Exchange message,
+  * where that failure is caused by the content of the client's message.
+  * This function must not return SECFailure for any reason that is directly
+  * or indirectly caused by the content of the client's encrypted PMS.
+  * We must not send an alert and also not drop the connection.
+  * Instead, we generate a random PMS.  This will cause a failure
+  * in the processing the finished message, which is exactly where
+@@ -9530,19 +9481,19 @@ ssl3_CSwapPK11SymKey(PK11SymKey **x, PK1
+ static SECStatus
+ ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
+                                 PRUint8 *b,
+                                 PRUint32 length,
+                                 sslKeyPair *serverKeyPair)
+ {
+     SECStatus rv;
+     SECItem enc_pms;
+-    PK11SymKey *pms = NULL;
+-    PK11SymKey *fauxPms = NULL;
+-    PK11SlotInfo *slot = NULL;
++    PK11SymKey *tmpPms[2] = { NULL, NULL };
++    PK11SlotInfo *slot;
++    int useFauxPms = 0;
+ 
+     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+     PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
+ 
+     enc_pms.data = b;
+     enc_pms.len = length;
+ 
+@@ -9553,16 +9504,21 @@ ssl3_HandleRSAClientKeyExchange(sslSocke
+             PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+             return SECFailure;
+         }
+         if ((unsigned)kLen < enc_pms.len) {
+             enc_pms.len = kLen;
+         }
+     }
+ 
++#define currentPms tmpPms[!useFauxPms]
++#define unusedPms tmpPms[useFauxPms]
++#define realPms tmpPms[1]
++#define fauxPms tmpPms[0]
++
+     /*
+      * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1
+      * as we can within the constraints of the PKCS#11 interface.
+      *
+      * 1. Unconditionally generate a bogus PMS (what RFC 5246
+      *    calls R).
+      * 2. Attempt the RSA decryption to recover the PMS (what
+      *    RFC 5246 calls M).
+@@ -9607,43 +9563,50 @@ ssl3_HandleRSAClientKeyExchange(sslSocke
+     }
+ 
+     /*
+      * unwrap pms out of the incoming buffer
+      * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
+      *  the unwrap.  Rather, it is the mechanism with which the
+      *      unwrapped pms will be used.
+      */
+-    pms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms,
+-                               CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
++    realPms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms,
++                                   CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
+     /* Temporarily use the PMS if unwrapping the real PMS fails. */
+-    ssl3_CSwapPK11SymKey(&pms, &fauxPms, pms == NULL);
++    useFauxPms |= (realPms == NULL);
+ 
+     /* Attempt to derive the MS from the PMS. This is the only way to
+      * check the version field in the RSA PMS. If this fails, we
+      * then use the faux PMS in place of the PMS. Note that this
+      * operation should never fail if we are using the faux PMS
+      * since it is correctly formatted. */
+-    rv = ssl3_ComputeMasterSecret(ss, pms, NULL);
+-
+-    /* If we succeeded, then select the true PMS, else select the FPMS. */
+-    ssl3_CSwapPK11SymKey(&pms, &fauxPms, (rv != SECSuccess) & (fauxPms != NULL));
++    rv = ssl3_ComputeMasterSecret(ss, currentPms, NULL);
++
++    /* If we succeeded, then select the true PMS and discard the
++     * FPMS. Else, select the FPMS and select the true PMS */
++    useFauxPms |= (rv != SECSuccess);
++
++    if (unusedPms) {
++        PK11_FreeSymKey(unusedPms);
++    }
+ 
+     /* This step will derive the MS from the PMS, among other things. */
+-    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
+-
+-    /* Clear both PMS. */
+-    PK11_FreeSymKey(pms);
+-    PK11_FreeSymKey(fauxPms);
++    rv = ssl3_InitPendingCipherSpecs(ss, currentPms, PR_TRUE);
++    PK11_FreeSymKey(currentPms);
+ 
+     if (rv != SECSuccess) {
+         (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
+         return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
+     }
+ 
++#undef currentPms
++#undef unusedPms
++#undef realPms
++#undef fauxPms
++
+     return SECSuccess;
+ }
+ 
+ static SECStatus
+ ssl3_HandleDHClientKeyExchange(sslSocket *ss,
+                                PRUint8 *b,
+                                PRUint32 length,
+                                sslKeyPair *serverKeyPair)
+@@ -11739,17 +11702,17 @@ ssl_RemoveTLSCBCPadding(sslBuffer *plain
+      * amount of padding possible. (Again, the length of the record is
+      * public information so we can use it.) */
+     toCheck = 256; /* maximum amount of padding + 1. */
+     if (toCheck > plaintext->len) {
+         toCheck = plaintext->len;
+     }
+ 
+     for (i = 0; i < toCheck; i++) {
+-        unsigned int t = paddingLength - i;
++        t = paddingLength - i;
+         /* If i <= paddingLength then the MSB of t is zero and mask is
+          * 0xff.  Otherwise, mask is 0. */
+         unsigned char mask = DUPLICATE_MSB_TO_ALL(~t);
+         unsigned char b = plaintext->buf[plaintext->len - 1 - i];
+         /* The final |paddingLength+1| bytes should all have the value
+          * |paddingLength|. Therefore the XOR should be zero. */
+         good &= ~(mask & (paddingLength ^ b));
+     }
+diff --git a/security/nss/lib/ssl/ssl3ecc.c b/security/nss/lib/ssl/ssl3ecc.c
+--- a/security/nss/lib/ssl/ssl3ecc.c
++++ b/security/nss/lib/ssl/ssl3ecc.c
+@@ -543,22 +543,22 @@ ssl3_HandleECDHServerKeyExchange(sslSock
+         desc = handshake_failure;
+         goto alert_loser;
+     }
+ 
+     PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2);
+     if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) {
+         rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
+         if (rv != SECSuccess) {
+-            goto loser; /* malformed or unsupported. */
++            goto alert_loser; /* malformed or unsupported. */
+         }
+         rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme,
+                                                  ss->sec.peerCert);
+         if (rv != SECSuccess) {
+-            goto loser;
++            goto alert_loser;
+         }
+         hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
+     } else {
+         /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
+         hashAlg = ssl_hash_none;
+         sigScheme = ssl_sig_none;
+     }
+ 
+diff --git a/security/nss/lib/util/nssutil.h b/security/nss/lib/util/nssutil.h
+--- a/security/nss/lib/util/nssutil.h
++++ b/security/nss/lib/util/nssutil.h
+@@ -14,22 +14,22 @@
+ 
+ /*
+  * NSS utilities's major version, minor version, patch level, build number,
+  * and whether this is a beta release.
+  *
+  * The format of the version string should be
+  *     "<major version>.<minor version>[.<patch level>[.<build number>]][ <Beta>]"
+  */
+-#define NSSUTIL_VERSION "3.36.8"
++#define NSSUTIL_VERSION "3.37 Beta"
+ #define NSSUTIL_VMAJOR 3
+-#define NSSUTIL_VMINOR 36
+-#define NSSUTIL_VPATCH 8
++#define NSSUTIL_VMINOR 37
++#define NSSUTIL_VPATCH 0
+ #define NSSUTIL_VBUILD 0
+-#define NSSUTIL_BETA PR_FALSE
++#define NSSUTIL_BETA PR_TRUE
+ 
+ SEC_BEGIN_PROTOS
+ 
+ /*
+  * Returns a const string of the UTIL library version.
+  */
+ extern const char *NSSUTIL_GetVersion(void);
+ 
+diff --git a/security/nss/lib/util/pkcs11t.h b/security/nss/lib/util/pkcs11t.h
+--- a/security/nss/lib/util/pkcs11t.h
++++ b/security/nss/lib/util/pkcs11t.h
+@@ -461,16 +461,18 @@ typedef CK_ULONG CK_ATTRIBUTE_TYPE;
+ #define CKA_MODULUS_BITS 0x00000121
+ #define CKA_PUBLIC_EXPONENT 0x00000122
+ #define CKA_PRIVATE_EXPONENT 0x00000123
+ #define CKA_PRIME_1 0x00000124
+ #define CKA_PRIME_2 0x00000125
+ #define CKA_EXPONENT_1 0x00000126
+ #define CKA_EXPONENT_2 0x00000127
+ #define CKA_COEFFICIENT 0x00000128
++/* CKA_PUBLIC_KEY_INFO is new for v2.40 */
++#define CKA_PUBLIC_KEY_INFO 0x00000129
+ #define CKA_PRIME 0x00000130
+ #define CKA_SUBPRIME 0x00000131
+ #define CKA_BASE 0x00000132
+ 
+ /* CKA_PRIME_BITS and CKA_SUB_PRIME_BITS are new for v2.11 */
+ #define CKA_PRIME_BITS 0x00000133
+ #define CKA_SUBPRIME_BITS 0x00000134
+ #define CKA_SUB_PRIME_BITS CKA_SUBPRIME_BITS
+diff --git a/security/nss/lib/util/quickder.c b/security/nss/lib/util/quickder.c
+--- a/security/nss/lib/util/quickder.c
++++ b/security/nss/lib/util/quickder.c
+@@ -752,23 +752,16 @@ DecodeItem(void* dest,
+                                     temp.data++;
+                                     temp.len--;
+                                 }
+                             }
+                             break;
+                         }
+ 
+                         case SEC_ASN1_BIT_STRING: {
+-                            /* Can't be 8 or more spare bits, or any spare bits
+-			     * if there are no octets. */
+-                            if (temp.data[0] >= 8 || (temp.data[0] > 0 && temp.len == 1)) {
+-                                PORT_SetError(SEC_ERROR_BAD_DER);
+-                                rv = SECFailure;
+-                                break;
+-                            }
+                             /* change the length in the SECItem to be the number
+                                of bits */
+                             temp.len = (temp.len - 1) * 8 - (temp.data[0] & 0x7);
+                             temp.data++;
+                             break;
+                         }
+ 
+                         default: {
+diff --git a/security/nss/lib/util/secasn1d.c b/security/nss/lib/util/secasn1d.c
+--- a/security/nss/lib/util/secasn1d.c
++++ b/security/nss/lib/util/secasn1d.c
+@@ -170,17 +170,17 @@ static int /* bool */
+             sprintf(buf, " %s", type_names[k]);
+             if ((k == SEC_ASN1_SET || k == SEC_ASN1_SEQUENCE) &&
+                 (kind & SEC_ASN1_GROUP)) {
+                 buf += strlen(buf);
+                 sprintf(buf, "_OF");
+             }
+         }
+     } else {
+-        sprintf(buf, " [%lu]", k);
++        sprintf(buf, " [%d]", k);
+     }
+     buf += strlen(buf);
+ 
+     for (k = kind >> 8, i = 0; k; k >>= 1, ++i) {
+         if (k & 1) {
+             sprintf(buf, " %s", flag_names[i]);
+             buf += strlen(buf);
+         }
+@@ -977,17 +977,17 @@ sec_asn1d_prepare_for_contents(sec_asn1d
+ {
+     SECItem *item;
+     PLArenaPool *poolp;
+     unsigned long alloc_len;
+     sec_asn1d_state *parent;
+ 
+ #ifdef DEBUG_ASN1D_STATES
+     {
+-        printf("Found Length %lu %s\n", state->contents_length,
++        printf("Found Length %d %s\n", state->contents_length,
+                state->indefinite ? "indefinite" : "");
+     }
+ #endif
+ 
+     /**
+      * The maximum length for a child element should be constrained to the
+      * length remaining in the first definite length element in the ancestor
+      * stack. If there is no definite length element in the ancestor stack,
+@@ -2712,25 +2712,26 @@ dump_states(SEC_ASN1DecoderContext *cx)
+ 
+     for (; state; state = state->child) {
+         int i;
+         for (i = 0; i < state->depth; i++) {
+             printf("  ");
+         }
+ 
+         i = formatKind(state->theTemplate->kind, kindBuf);
+-        printf("%s: tmpl kind %s",
++        printf("%s: tmpl %08x, kind%s",
+                (state == cx->current) ? "STATE" : "State",
++               state->theTemplate,
+                kindBuf);
+         printf(" %s", (state->place >= 0 && state->place <= notInUse) ? place_names[state->place] : "(undefined)");
+         if (!i)
+-            printf(", expect 0x%02lx",
++            printf(", expect 0x%02x",
+                    state->expect_tag_number | state->expect_tag_modifiers);
+ 
+-        printf("%s%s%s %lu\n",
++        printf("%s%s%s %d\n",
+                state->indefinite ? ", indef" : "",
+                state->missing ? ", miss" : "",
+                state->endofcontents ? ", EOC" : "",
+                state->pending);
+     }
+ 
+     return;
+ }
+@@ -2748,17 +2749,17 @@ SEC_ASN1DecoderUpdate(SEC_ASN1DecoderCon
+     if (cx->status == needBytes)
+         cx->status = keepGoing;
+ 
+     while (cx->status == keepGoing) {
+         state = cx->current;
+         what = SEC_ASN1_Contents;
+         consumed = 0;
+ #ifdef DEBUG_ASN1D_STATES
+-        printf("\nPLACE = %s, next byte = 0x%02x, %p[%lu]\n",
++        printf("\nPLACE = %s, next byte = 0x%02x, %08x[%d]\n",
+                (state->place >= 0 && state->place <= notInUse) ? place_names[state->place] : "(undefined)",
+                len ? (unsigned int)((unsigned char *)buf)[consumed] : 0,
+                buf, consumed);
+         dump_states(cx);
+ #endif /* DEBUG_ASN1D_STATES */
+         switch (state->place) {
+             case beforeIdentifier:
+                 consumed = sec_asn1d_parse_identifier(state, buf, len);
+@@ -2971,17 +2972,17 @@ SEC_ASN1DecoderUpdate(SEC_ASN1DecoderCon
+     return SECSuccess;
+ }
+ 
+ SECStatus
+ SEC_ASN1DecoderFinish(SEC_ASN1DecoderContext *cx)
+ {
+     SECStatus rv;
+ 
+-    if (!cx || cx->status == needBytes) {
++    if (cx->status == needBytes) {
+         PORT_SetError(SEC_ERROR_BAD_DER);
+         rv = SECFailure;
+     } else {
+         rv = SECSuccess;
+     }
+ 
+     /*
+      * XXX anything else that needs to be finished?
+diff --git a/security/nss/nss-tool/enc/enctool.cc b/security/nss/nss-tool/enc/enctool.cc
+--- a/security/nss/nss-tool/enc/enctool.cc
++++ b/security/nss/nss-tool/enc/enctool.cc
+@@ -266,17 +266,16 @@ bool EncTool::DoCipher(std::string file_
+     buf = std::cout.rdbuf();
+   }
+   std::ostream output(buf);
+ 
+   // Read from stdin.
+   if (file_name.empty()) {
+     std::vector<uint8_t> data = ReadInputData("");
+     std::vector<uint8_t> out(data.size() + 16);
+-    SECStatus rv;
+     if (encrypt) {
+       rv = PK11_Encrypt(symKey.get(), cipher_mech_, params.get(), out.data(),
+                         &outLen, data.size() + 16, data.data(), data.size());
+     } else {
+       rv = PK11_Decrypt(symKey.get(), cipher_mech_, params.get(), out.data(),
+                         &outLen, data.size() + 16, data.data(), data.size());
+     }
+     if (rv != SECSuccess) {
+diff --git a/security/nss/tests/all.sh b/security/nss/tests/all.sh
+--- a/security/nss/tests/all.sh
++++ b/security/nss/tests/all.sh
+@@ -304,17 +304,17 @@ tests="cipher lowhash libpkix cert dbtes
+ # Don't run chains tests when we have a gyp build.
+ if [ "$OBJDIR" != "Debug" -a "$OBJDIR" != "Release" ]; then
+   tests="$tests chains"
+ fi
+ TESTS=${NSS_TESTS:-$tests}
+ 
+ ALL_TESTS=${TESTS}
+ 
+-nss_ssl_tests="crl iopr policy"
++nss_ssl_tests="crl iopr policy normal_normal"
+ if [ $NO_INIT_SUPPORT -eq 0 ]; then
+     nss_ssl_tests="$nss_ssl_tests fips_normal normal_fips"
+ fi
+ NSS_SSL_TESTS="${NSS_SSL_TESTS:-$nss_ssl_tests}"
+ 
+ nss_ssl_run="cov auth stapling stress"
+ NSS_SSL_RUN="${NSS_SSL_RUN:-$nss_ssl_run}"
+ 
+diff --git a/security/nss/tests/bogo/bogo.sh b/security/nss/tests/bogo/bogo.sh
+--- a/security/nss/tests/bogo/bogo.sh
++++ b/security/nss/tests/bogo/bogo.sh
+@@ -20,17 +20,17 @@ bogo_init()
+     . ./init.sh
+   fi
+ 
+   mkdir -p "${HOSTDIR}/bogo"
+   cd "${HOSTDIR}/bogo"
+   BORING=${BORING:=boringssl}
+   if [ ! -d "$BORING" ]; then
+     git clone -q https://boringssl.googlesource.com/boringssl "$BORING"
+-    git -C "$BORING" checkout -q a513e86c1ebb1383930c9e504bdabcc302a85f30
++    git -C "$BORING" checkout -q ec55dc15d3a39e5f1a58bfd79148729f38f6acb4
+   fi
+ 
+   SCRIPTNAME="bogo.sh"
+   html_head "bogo test"
+ }
+ 
+ bogo_cleanup()
+ {
+diff --git a/security/nss/tests/chains/scenarios/realcerts.cfg b/security/nss/tests/chains/scenarios/realcerts.cfg
+--- a/security/nss/tests/chains/scenarios/realcerts.cfg
++++ b/security/nss/tests/chains/scenarios/realcerts.cfg
+@@ -16,14 +16,14 @@ import BrAirWaysBadSig:x:
+ 
+ verify TestUser50:x
+   result pass
+ 
+ verify TestUser51:x
+   result pass
+ 
+ verify PayPalEE:x
+-  policy OID.2.16.840.1.114412.2.1 
++  policy OID.2.16.840.1.114412.1.1 
+   result pass
+ 
+ verify BrAirWaysBadSig:x
+   result fail
+ 
+diff --git a/security/nss/tests/common/init.sh b/security/nss/tests/common/init.sh
+--- a/security/nss/tests/common/init.sh
++++ b/security/nss/tests/common/init.sh
+@@ -538,18 +538,18 @@ if [ -z "${INIT_SOURCED}" -o "${INIT_SOU
+     D_ECCURVES="ECCURVES.$version"
+     D_EXT_SERVER="ExtendedServer.$version"
+     D_EXT_CLIENT="ExtendedClient.$version"
+     D_IMPLICIT_INIT="ImplicitInit.$version"
+     D_CERT_EXTENSTIONS="CertExtensions.$version"
+     D_DISTRUST="Distrust.$version"
+     D_RSAPSS="RSAPSS.$version"
+ 
+-    # we need relative pathnames of these files abd directories, since our
+-    # tools can't handle the unix style absolut pathnames on cygnus
++    # we need relative pathnames of these files and directories, since our
++    # tools can't handle the unix style absolute pathnames on cygnus
+ 
+     R_CADIR=../CA
+     R_SERVERDIR=../server
+     R_CLIENTDIR=../client
+     R_IOPR_CADIR=../CA_iopr
+     R_IOPR_SSL_SERVERDIR=../server_ssl_iopr
+     R_IOPR_SSL_CLIENTDIR=../client_ssl_iopr
+     R_IOPR_OCSP_CLIENTDIR=../client_ocsp_iopr
+@@ -560,44 +560,47 @@ if [ -z "${INIT_SOURCED}" -o "${INIT_SOU
+     R_EXT_SERVERDIR=../ext_server
+     R_EXT_CLIENTDIR=../ext_client
+     R_IMPLICIT_INIT_DIR=../implicit_init
+     R_CERT_EXT=../cert_extensions
+     R_STAPLINGDIR=../stapling
+     R_NOLOGINDIR=../nologin
+     R_SSLGTESTDIR=../ssl_gtests
+     R_GTESTDIR=../gtests
++    R_RSAPSSDIR=../rsapss
+ 
+     #
+     # profiles are either paths or domains depending on the setting of
+     # MULTIACCESS_DBM
+     #
+     P_R_CADIR=${R_CADIR}
+     P_R_ALICEDIR=${R_ALICEDIR}
+     P_R_BOBDIR=${R_BOBDIR}
+     P_R_DAVEDIR=${R_DAVEDIR}
+     P_R_EVEDIR=${R_EVEDIR}
+     P_R_SERVERDIR=${R_SERVERDIR}
+     P_R_CLIENTDIR=${R_CLIENTDIR}
+     P_R_NOLOGINDIR=${R_NOLOGINDIR}
+     P_R_EXT_SERVERDIR=${R_EXT_SERVERDIR}
+     P_R_EXT_CLIENTDIR=${R_EXT_CLIENTDIR}
+     P_R_IMPLICIT_INIT_DIR=${R_IMPLICIT_INIT_DIR}
++    P_R_RSAPSSDIR=${R_RSAPSSDIR}
+     if [ -n "${MULTIACCESS_DBM}" ]; then
+         P_R_CADIR="multiaccess:${D_CA}"
+         P_R_ALICEDIR="multiaccess:${D_ALICE}"
+         P_R_BOBDIR="multiaccess:${D_BOB}"
+         P_R_DAVEDIR="multiaccess:${D_DAVE}"
+         P_R_EVEDIR="multiaccess:${D_EVE}"
+         P_R_SERVERDIR="multiaccess:${D_SERVER}"
+         P_R_CLIENTDIR="multiaccess:${D_CLIENT}"
+         P_R_NOLOGINDIR="multiaccess:${D_NOLOGIN}"
+         P_R_EXT_SERVERDIR="multiaccess:${D_EXT_SERVER}"
+         P_R_EXT_CLIENTDIR="multiaccess:${D_EXT_CLIENT}"
+         P_R_IMPLICIT_INIT_DIR="multiaccess:${D_IMPLICIT_INIT}"
++	P_R_RSAPSSDIR="multiaccess:${D_RSAPSS}"
+     fi
+ 
+     R_PWFILE=../tests.pw
+     R_EMPTY_FILE=../tests_empty
+     R_NOISE_FILE=../tests_noise
+ 
+     R_FIPSPWFILE=../tests.fipspw
+     R_FIPSBADPWFILE=../tests.fipsbadpw
+diff --git a/security/nss/tests/interop/interop.sh b/security/nss/tests/interop/interop.sh
+--- a/security/nss/tests/interop/interop.sh
++++ b/security/nss/tests/interop/interop.sh
+@@ -20,17 +20,17 @@ interop_init()
+     . ./init.sh
+   fi
+ 
+   mkdir -p "${HOSTDIR}/interop"
+   cd "${HOSTDIR}/interop"
+   INTEROP=${INTEROP:=tls_interop}
+   if [ ! -d "$INTEROP" ]; then
+     git clone -q https://github.com/ttaubert/tls-interop "$INTEROP"
+-    git -C "$INTEROP" checkout -q 07930b791827c1bdb6f4c19ca0aa63850fd59e22
++    git -C "$INTEROP" checkout -q d07b28ac32b390dea1c9bcca5c56716247d23e5e
+   fi
+   INTEROP=$(cd "$INTEROP";pwd -P)
+ 
+   # We use the BoringSSL keyfiles
+   BORING=${BORING:=boringssl}
+   if [ ! -d "$BORING" ]; then
+     git clone -q https://boringssl.googlesource.com/boringssl "$BORING"
+     git -C "$BORING" checkout -q ea80f9d5df4c302de391e999395e1c87f9c786b3
+diff --git a/security/nss/tests/libpkix/certs/PayPalEE.cert b/security/nss/tests/libpkix/certs/PayPalEE.cert
+index aef4086762a88dd5d7df06a7f4e23ea2f502c83c..d71fbb5016b2ac180a61303d2aa2732910aa7a4b
+GIT binary patch
+literal 1376
+zc$_n6VvR9qVsTl(%*4pVB*1j*!`#KcY~J;Vq_QlrJ*IEK%f_kI=F#?@mywa1mBFCE
+zklTQhjX9KsO_(V(*ih6!7{uWc=5fhP&vZ^LDpByvOE#1=5C;i!3k#H&m+PefrILYC
+zddc~@hWZA&ASq^HHMovo4@V;fkIeK81;^sz(xSw?<Wz;=)S|M~A_Zqh137VCLo-7|
+z0}}%<hyrpgfLudEBQV#X7S%<<27(|ChcK6OVoqjSeo<a#qM@JxKS+>Wm?JnbPr)m{
+zI2Fm|0g06Xi8(qThwB+i8Aw1}E(j4;2q?-=DNQcP%+G@v%`D7SkXTuem;>^UK@+1A
+zau_kPGB7tW@-qO%xtN+585vI16-T)q%WMh?<+)!TxxHFWc=5KLH20f)pNl<q{B!ZE
+z%kN^Erkro#vEW$L#HP&~4?f{43;&%_`oZd2$uXO4M@udgUhBUyOY4q!?+)hVtN+9u
+zxm}x1S1h$Ka4<aCVD`>n`e)^|mcydQT;$6Se7fADUiMHmy5cXl;DVdUMOSWi%BBWB
+zD)eTlEE37hTbd;r<;nl&@V7d@hsV8h{X|)KZhhfC>!`>6e9y956=yu3mb7kRT(v)Q
+zf1G$uq(r;w-O9FE?s}iX85q-JUM1gl%)By7;jfP=TU79W<BIT(RT;7zDWdmV>IFT*
+zoc<|ixp9f5m7UyJ*B&gF$6x-Fae<)CLndZM2FArrjE{jKa^FB67=W_MED{D{4I+UV
+z|0k?xVlTBhb2Bw1X_3&5$RcY4S&#xg7BLo)&l6NqpPH*aWeQJyqy1HD&LsxL6$YXp
+zX+ah~1D+=2NZ<nr^D{F3XJKJxVqE|+MU_R&K!lA$n~jl`m7SRp&SEks1xd@Z<Qe1`
+zm@F__V9=(QQBqQ1rLUh{lw*vNT=k1H5{+~-5_OBg=}|Y`R1c^IQ<n)bx_m&^DzLa3
+zI2)L=aVE5RFt+{8VPrJWGSGlIj)_rB24re6&{*`WqwgFLY{0?Bmfpw%%&7*A%`i=j
+zj4b5_r3NZ6z5!#K1k`Ey$;AaIh8Xz5RWY?W!aR@&k}gKI4VFDYxf7H*;dv91HJu%S
+zekw8G0r^Q76!J_43}}S~GbsHl?%p&zyXNcsWp4js+um<0pEaGwsXLB0_T!b?uibte
+z5Yb7n>YS_B=VI$JuYba--TS{qi#$;mQOcZa^Ox64<DmDG=e{E6zMRnzl4P8(7N4^#
+zVNYGw?o(4sr#$+4sv~nt*t}_9f1a^lwbP{O?1p`Z)!U0hJZ9YZp?_5JVOkJJ6z~7L
+zf;a2tKCv%*70~H3wO9CZ*7Jq-;gekS_BtH=6E^Qi`AnwUk8kwX+gUGbWBVOpHnUsC
+z=ayn<W7Z^9S(BF&4mkDqcD;0;rq?&&)$G)>D?Pq1legQK{M~KSsVDEdzZfLBn!dex
+il#jFb`lZ<WY;$k**RxM@{h%k;WAQU%y=m8(m#qL5@YweN
+
+diff --git a/security/nss/tests/libpkix/certs/PayPalICA.cert b/security/nss/tests/libpkix/certs/PayPalICA.cert
+index dd14c1b21886d9e63559403e819aa2ac2b516b9b..07e025defbc58b3190f341c520ba3d26fc4cd59e
+GIT binary patch
+literal 1205
+zc$_n6V%ccW#5{8WGZP~dlK{)Z=S%LyeEOVwK-+0Ytmu3LUN%mxHjlRNyo`+8tPBP@
+zhTI06Y|No7Y{E>T!G@v+!XOTpFpo=SdZu$~QHg?QUb3O2fjCH*TUemHyj(8@D3uJ9
+z(o4?IHPklH1W7RqE5UVmWTs~*I2IR|7A58-rz*IHDFo%`mnb+p8pw(B8X6lK7#SHF
+z82~|)IIocf64#)BQrGAk=t5kh2G<en;b?^Jq~O$|veY7wi<%gfkb{Jgm4Ug5k)Hu5
+z&c)Qk$jGqmf&L*CwiCH5@z>vTrLb+PRZ>e8Tj%63``n%R^UK)n4jY8FOYZca!WT6~
+zJ~V90AttT$7iPTUcDR1zf_2dek$LYYY!qC%?$U`J&Q>?MxvyTG`qg3m3E8*4bK=9d
+zw*_R({MvQv(s5S#71K}NS+cRIMfcd+rE`u;HZ5!Ak8_F8GVlLu`jMMM-6-no?(TU@
+z_6A;1e{|Q{$#^lV#*y6`XJ)O@R_3iZR{bolaJ!cs$M44NVqy#DDhv5Oy*`O!P3e+3
+zyUvPll5;Ultq)eUyePvpD_L4{Qb`7v`JqEW9;Yp%7HxYNd+_c8g&m5ECadL(cquv_
+zf15k|lZXCi=C6w~CI#!qJ!WENWMEv}#OMhO5my5tVBpFMGcx{X;V@tWQcR2t27Dkf
+zevlXoFv+zU$b$H)EMf*CY#iEbjI6Be%#3grlYt40&B(~2VW4K90^=Jnwn=1^loVL$
+z>*psI7ofzefj7udc@`G~Cj*BCb_;CUte{Ghi*ig*l<LDG9u(#97<UZ=B|&FLJ)n96
+zTaaN2EM^8K21aZwKqiBMmVpM$9ZZa3G9bf?fu^IUFMa2LV2B6#Sj1RF0yF+kSkJ^>
+zYIEjhYD&@~p&gM$)&}w*X=N4(1F;5?jdq7KnSbneXS^~)O^So*eR7KSVYD2`3`%7Z
+zT~j-mpXJ_<`6HY0%B#QmTA+S!wu{)jHOXHu<>j=@>|WJa*b@EL#Bam)%1N4MbQ`ih
+z^eH^7T=I|EUHH}4wo{RXwO?4KWnYeru>E)0P&G!vqGj>3`AvU&qGuTTovoNB^|$r3
+z=c-TY-7|~+*sZ$i$bIXo*~0xYdG4O|aW_3`m~Z~=_FOPS&B@{QwMl|YQn<oHj(nB9
+z#uS&m=G~EoSwcm>!X{t;zu%yh&0s%wz2E<E*10NgTMujhURJtdjjq`H+Di3JuMf@T
+zW`DJ+^)lmP1r5hYXN^mZk5_$rQ*B+o%^|6Q)zOvly*QiQy#vOx(=R9L6}3Of{3FB=
+M?jTq2Rqo^#0PL8d<^TWy
+
+diff --git a/security/nss/tests/libpkix/vfychain_test.lst b/security/nss/tests/libpkix/vfychain_test.lst
+--- a/security/nss/tests/libpkix/vfychain_test.lst
++++ b/security/nss/tests/libpkix/vfychain_test.lst
+@@ -1,4 +1,4 @@
+ # Status | Leaf Cert | Policies | Others(undef)
+ 0 TestUser50 undef
+ 0 TestUser51 undef
+-0 PayPalEE OID.2.16.840.1.114412.2.1
++0 PayPalEE OID.2.16.840.1.114412.1.1
+diff --git a/security/nss/tests/tools/TestRSAPSS.p12 b/security/nss/tests/tools/TestRSAPSS.p12
+new file mode 100644
+index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..91473891c8f593e6406f0c565ca67977b1e98b31
+GIT binary patch
+literal 2554
+zc$`(#X*d)L7YFc}F@~{qWlWUj;>yyD%qUC9K6Z6Swn9X*?~*-6wwbZZl07t)eJ4XB
+zOA_HCY3wF3WXU8;xO$%VeeZieoO7P@KhOF4L*t>_ARr4G52Zk$=VSC@esBZXfQ5Ky
+z1sD%~ejJyg@nE%oPLM)87=0X}KtRCpIQM@~Xdwv4e-<tv1kD3xhq|Ex-R|~dK_GTO
+z1fFH5)ZgygpBW8eAK#)z4EO{e8?DL0`l)9hZ!}h!5fTqxytx`M&`y^}mU|pAi5olf
+zE|@K$mW?Qoz(;q}`bPKZEW_kC?LR7G7?Rx)ne-kNy?hOLVqUo{piDDWG>QNA{hy-M
+zRjFOqd{X+HE)~|sj`Q;7LG0p3!gbY*UpIod?}z2$NmNQ(@Y8heBh0M^s@j*4=S#eC
+z4V)%~+|)Qrwu>|Asc=emo_*ta&73_OCdcR`TiYZkqypDf{yp67q7(qAlWWzyzKnj~
+z0lP!-BCTMpXLTzKh9OF`RxJgof;T!HhiA|i-ef%O@Sj<fd@&ZOEMI11h&!3ER69lA
+zPqai9RS@Tvb5FRI>H1xRuDoP8lXcQnE@<`v`8umu%=ZzH(CXUDgTuaGg0x@lZQsk3
+zGs+JB?p;gKNh$Gm99lgRO~g7#$skn&LfGK$;vgTMHk;U&9WATMRvJ#R1E1lW-*rY8
+zNB+1d`O1ki;(B;t%x<ublxT9u7oOMpd*AcE&fcz)56B8ti+RWO@rKpzZ1@pj&Xj#H
+zqBYJS^c%!ZnMe1jxIqL5{9bYWf@SLfaOWgmY6ayi2_Q@1!?2#!b7@oM34kZtl09zQ
+zHiX|z=*yqrAX&hJ_Ej=lHV*rNaAs0FC1~#4{*84XeK24-CWX?r*JR;eliD{T5|uKQ
+z|5~7WYD02+Se=Dvl?a~!+Fx>QckYialpT!`=GB-zoORbdn6ajLTj+NV*nl{8Xq}@b
+z&)!J|Xna)*#tnflSZNXAa>CkK8GTMa)ep{w^nW+Gl3(h*>sXDb**qeb#R4n`OKQav
+z3S);o<L}*Ak51QVxnY7<7?dF}l7{^1QM{HP33aRs26WFiu4c1g)|I<Ddac+sBb%4%
+zPT7C)vQGnh27LNXYIaVC+%+mZPp7>|x0i1!82gFTYE83}y`Tbi_#vshZfR!!zzK2?
+zZdPfxbSY$=dCh0}RsELVLDxgzqHj=FELPjK-Ze5FkiD5d;xGlHsr$<>4}1-xd3vq1
+zbG%J#`Mv8817>ltW!dCBkyF)NY|nTtt#z$fdVmq}4Ni^}CZ-FAF)6be0A<fX1~uM?
+z5L#9AfIF)pP_gnIz<BM9rg9Xr-=iWu+`3UP-ohmuEtQ8V8>{Y5)NG0=B8Q&*w31_8
+zP~yioYh}@QmDI{kjv)SZZ}mysCAD;b&m{g-vE;}mSBLl588o=vl32UF;Xh-dU8wZK
+z-Kc;R+9k%$Ie2CERJ8>E-OAmQBm|+OvXl6b(VI{qu`r62NzzkYPT~knx;W~ZCE9Hw
+zl;{!m&ALo1Qx?<PD+&1$$}mOzh6RNt2H9j&ehWb3S#SMI7uIWFJgebxtb1Hq5YGRy
+z!2tvv`?7Wn3*%p!u>8{G+$rnx`$WrYzcc~k!M)Zig^I$e35oMHMS<*b-KGw8yr#(%
+zq{Uc`))$3d27JGNu*YgOyb=bsmG!m=)=_WZjwIJ$>QNsj=G<FX{RgRSyJeph84mMc
+z>oW>ev@XB&PBA#s6lQJAHf{ba!QFX&$E84o9vXYQ03$6Unwe9MLv?oxv3>S<E2BHi
+zBp*FapYwuongsW{^Gv)yg`=)*AB3>!_1MjwMn3%T;=Pi_ZUfI(E<N^y4pVFfky)V6
+zlOs2AWr1cJi=Yi_ehOgrD#6*<Qe{Yd!Fs_9sv3O>=QxtdEiS$7CO^+|(K`=g2vuU<
+zUFM~aR1PV3SCbB)C7L(!+eyyR{qr5K*Ktrtkt8;-hN-~Twj0Rwg}vE@amysAd(0z9
+z?F7O5D_1_4m3jk}g_7tw;%-HaJ^5J|Z*tacd%J$f+#X+VPBy4k_2ScQN<-DO6-Q>k
+zZgj@4^$#y?l74F^D14E%O*$XBc3XVAilRxj)5|yPL)C3b$1nLLvgkgS+;~=NgDmXc
+zUQ%(^Kgho9P`p8sYCuJ|nJrA8cF<BJeZ3`EFFZa(7bqs~Kf|D9N9)KVIW4Y?$UW6N
+z4HspAZ!uTYa%PdDnC501ZrZr<Ucv?6Y*t2R2V!I3+vLD<Z&A>#`E^5!=%&*%Oi5#%
+zfk9501@;fgfKG5ES5B=tRb|nF3AJm{w^EF^N*NQx05`v1_rpC<Oz&4y+r48bPS58a
+zt!S{ffg%>#9fmwD^%V70Be^T?*94@n7zznIeXm94b>ruM3jvk%WDQeKs1jYu-i?IQ
+zE@7{(X;YE1`_255uHPE1gszK&H{CsECFTmF)&r_AZK{VmmLrRDLo)(FDX5f8pSJmm
+z$+V|wVHw@iW(AHL&*KJg)?n~-WeBY}Y8i!`itf+V@N+zsCL;XIj^EZiDgrwn<(Pfh
+zRiKQrVh2iY@~0T_Dvg)E4G-|$_cv;X+Az#zkk(NgkO}3ADbwL$b%&s-8o4n<)d(yB
+zr^a;4mENi;2$5zcv5+fP=Z3^iZ<SxNFM5*9E3p|uk3!2m_t_TIXns$9H1YhpTNsjS
+zRPSt<GPc3?KB8T2Oce&ViMgt{yrPG84K1D?BQvrW_tz%mAMv^<d7^0aQ*3E2SI~(Y
+zF8ed^+K66*4ix2TdW@e(dX<P-%?W-Qua`)f$JMH~al@|OlN`G8bqG{WpG~CCLHE#(
+zUobp5>>;&Mi_@6nvTEt02QwPlf60wXY<;8YyV{lF&bPl)!bMh;_J#+TQt3(-Z|GYa
+zbqGa}r};~-h!cDb;RbvM`m0N?x3ha1;{xwgZzxE>4WMIF5#@(@V2BRvbGWT$9jRkv
+zuVtbv$}#sDZY`Pc6`M*3=$vO<D;0Zk+iBGocRHRz7Y7NyVwG-7_HX)gbYxS{5wlMN
+zNKF1|=^r^<@@jKbC6!doo0@wfT0V@;k$RZATq1lEq2#^weyY^58CZ*t_eif)Uu@Y`
+zr>3fi`cNK`B@Yd>GXz?-xDHL6<7Yf>>P^a!gwHN9O(qSw?*s~qa7{YWRIMLjbV-}D
+zyq>Y81pDi@76FMSnma<hdAQL5QswoARXS>fc*ai2q_X69;wHa<=r{+1qIuM>-LZtx
+zM4$Pej!+ne2f+pK12_VF0Rg`{`j3B({1`YG#`IB8P?CpOn}0H&AaAs)V|jS$&=|A`
+x8VX@W^00tTvjV`dAHYDb{l|TXmmlPV?<nO!=>Sgzm|Ygx>h8f|@cI{_e*?Ju#wq{+
+
+diff --git a/security/nss/tests/tools/tools.sh b/security/nss/tests/tools/tools.sh
+--- a/security/nss/tests/tools/tools.sh
++++ b/security/nss/tests/tools/tools.sh
+@@ -100,16 +100,17 @@ tools_init()
+   mkdir -p ${COPYDIR}
+   mkdir -p ${SIGNDIR}
+   cp ${ALICEDIR}/* ${SIGNDIR}/
+   mkdir -p ${TOOLSDIR}/html
+   cp ${QADIR}/tools/sign*.html ${TOOLSDIR}/html
+   mkdir -p ${TOOLSDIR}/data
+   cp ${QADIR}/tools/TestOldCA.p12 ${TOOLSDIR}/data
+   cp ${QADIR}/tools/TestOldAES128CA.p12 ${TOOLSDIR}/data
++  cp ${QADIR}/tools/TestRSAPSS.p12 ${TOOLSDIR}/data
+ 
+   cd ${TOOLSDIR}
+ }
+ 
+ ########################## list_p12_file ###############################
+ # List the key and cert in the specified p12 file
+ ########################################################################
+ list_p12_file()
+@@ -431,28 +432,48 @@ tools_p12_import_old_files()
+ 
+   echo "pk12util -i TestOldAES128CA.p12 -d ${P_R_COPYDIR} -k ${R_PWFILE} -w ${R_PWFILE}"
+   ${BINDIR}/pk12util -i ${TOOLSDIR}/data/TestOldAES128CA.p12 -d ${P_R_COPYDIR} -k ${R_PWFILE} -w ${R_PWFILE} 2>&1
+   ret=$?
+   html_msg $ret 0 "Importing PKCS#12 file created with NSS 3.29.5 (PBES2 with incorrect AES-128-CBC algorithm ID)"
+   check_tmpfile
+ }
+ 
++tools_p12_import_rsa_pss_private_key()
++{
++  echo "$SCRIPTNAME: Importing RSA-PSS private key from PKCS#12 file --------------"
++  ${BINDIR}/pk12util -i ${TOOLSDIR}/data/TestRSAPSS.p12 -d ${P_R_COPYDIR} -k ${R_PWFILE} -W '' 2>&1
++  ret=$?
++  html_msg $ret 0 "Importing RSA-PSS private key from PKCS#12 file"
++  check_tmpfile
++
++  # Check if RSA-PSS identifier is included in the key listing
++  ${BINDIR}/certutil -d ${P_R_COPYDIR} -K -f ${R_PWFILE} | grep '^<[0-9 ]*> *rsaPss'
++  ret=$?
++  html_msg $ret 0 "Listing RSA-PSS private key imported from PKCS#12 file"
++  check_tmpfile
++
++  return $ret
++}
++
+ ############################## tools_p12 ###############################
+ # local shell function to test basic functionality of pk12util
+ ########################################################################
+ tools_p12()
+ {
+   tools_p12_export_list_import_with_default_ciphers
+   tools_p12_export_list_import_all_pkcs5v2_ciphers
+   tools_p12_export_list_import_all_pkcs5pbe_ciphers
+   tools_p12_export_list_import_all_pkcs12v2pbe_ciphers
+   tools_p12_export_with_none_ciphers
+   tools_p12_export_with_invalid_ciphers
+   tools_p12_import_old_files
++  if [ "${TEST_MODE}" = "SHARED_DB" ] ; then
++    tools_p12_import_rsa_pss_private_key
++  fi
+ }
+ 
+ ############################## tools_sign ##############################
+ # local shell function pk12util uses a hardcoded tmp file, if this exists
+ # and is owned by another user we don't get reasonable errormessages 
+ ########################################################################
+ check_tmpfile()
+ {

+ 238 - 0
rel-257/ian/patches/1445731-10-NSS337-61a1.patch

@@ -0,0 +1,238 @@
+# HG changeset patch
+# User J.C. Jones <jjones@mozilla.com>
+# Date 1524749544 -7200
+#      Thu Apr 26 15:32:24 2018 +0200
+# Node ID cf1d0f4340ef01e80e8fe568b7686593a9a3f105
+# Parent  7c19008dbf36eb5f61143b44333ec448d1511ef1
+Bug 1445731 - land NSS NSS_3_37_BETA2 UPGRADE_NSS_RELEASE, r=me
+
+diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO
+--- a/security/nss/TAG-INFO
++++ b/security/nss/TAG-INFO
+@@ -1,1 +1,1 @@
+-3e452651e282
++NSS_3_37_BETA2
+diff --git a/security/nss/coreconf/config.mk b/security/nss/coreconf/config.mk
+--- a/security/nss/coreconf/config.mk
++++ b/security/nss/coreconf/config.mk
+@@ -176,16 +176,20 @@ endif
+ # you should define NSS_FORCE_FIPS
+ #
+ # NSS_NO_INIT_SUPPORT is always defined on platforms that don't support
+ # executing the startup tests at library load time.
+ ifndef NSS_FORCE_FIPS
+ DEFINES += -DNSS_NO_INIT_SUPPORT
+ endif
+ 
++ifdef NSS_SEED_ONLY_DEV_URANDOM
++DEFINES += -DSEED_ONLY_DEV_URANDOM
++endif
++
+ # Avoid building object leak test code for optimized library
+ ifndef BUILD_OPT
+ ifdef PKIX_OBJECT_LEAK_TEST
+ DEFINES += -DPKIX_OBJECT_LEAK_TEST
+ endif
+ endif
+ 
+ # This allows all library and tools code to use the util function
+diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep
+--- a/security/nss/coreconf/coreconf.dep
++++ b/security/nss/coreconf/coreconf.dep
+@@ -5,8 +5,9 @@
+ 
+ /*
+  * A dummy header file that is a dependency for all the object files.
+  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
+  * depend builds.  See comments in rules.mk.
+  */
+ 
+ #error "Do not include this header file."
++
+diff --git a/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc
+@@ -615,16 +615,62 @@ TEST_P(TlsConnectGenericPre13, ConnectUn
+   client_->EnableCiphersByKeyExchange(ssl_kea_ecdh);
+ 
+   MakeTlsFilter<ECCServerKEXDamager>(server_, ec_type_named,
+                                      ssl_grp_ec_secp256r1);
+   ConnectExpectAlert(client_, kTlsAlertHandshakeFailure);
+   client_->CheckErrorCode(SEC_ERROR_UNSUPPORTED_EC_POINT_FORM);
+ }
+ 
++// Replace SignatureAndHashAlgorithm of a SKE.
++class ECCServerKEXSigAlgReplacer : public TlsHandshakeFilter {
++ public:
++  ECCServerKEXSigAlgReplacer(const std::shared_ptr<TlsAgent> &server,
++                             SSLSignatureScheme sig_scheme)
++      : TlsHandshakeFilter(server, {kTlsHandshakeServerKeyExchange}),
++        sig_scheme_(sig_scheme) {}
++
++ protected:
++  virtual PacketFilter::Action FilterHandshake(const HandshakeHeader &header,
++                                               const DataBuffer &input,
++                                               DataBuffer *output) {
++    *output = input;
++
++    uint32_t point_len;
++    EXPECT_TRUE(output->Read(3, 1, &point_len));
++    output->Write(4 + point_len, sig_scheme_, 2);
++
++    return CHANGE;
++  }
++
++ private:
++  SSLSignatureScheme sig_scheme_;
++};
++
++TEST_P(TlsConnectTls12, ConnectUnsupportedSigAlg) {
++  EnsureTlsSetup();
++  client_->DisableAllCiphers();
++  client_->EnableCiphersByKeyExchange(ssl_kea_ecdh);
++
++  MakeTlsFilter<ECCServerKEXSigAlgReplacer>(server_, ssl_sig_none);
++  ConnectExpectAlert(client_, kTlsAlertIllegalParameter);
++  client_->CheckErrorCode(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
++}
++
++TEST_P(TlsConnectTls12, ConnectIncorrectSigAlg) {
++  EnsureTlsSetup();
++  client_->DisableAllCiphers();
++  client_->EnableCiphersByKeyExchange(ssl_kea_ecdh);
++
++  MakeTlsFilter<ECCServerKEXSigAlgReplacer>(server_,
++                                            ssl_sig_ecdsa_secp256r1_sha256);
++  ConnectExpectAlert(client_, kTlsAlertIllegalParameter);
++  client_->CheckErrorCode(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
++}
++
+ INSTANTIATE_TEST_CASE_P(KeyExchangeTest, TlsKeyExchangeTest,
+                         ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll,
+                                            TlsConnectTestBase::kTlsV11Plus));
+ 
+ #ifndef NSS_DISABLE_TLS_1_3
+ INSTANTIATE_TEST_CASE_P(KeyExchangeTest, TlsKeyExchangeTest13,
+                         ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll,
+                                            TlsConnectTestBase::kTlsV13));
+diff --git a/security/nss/lib/ckfw/builtins/nssckbi.h b/security/nss/lib/ckfw/builtins/nssckbi.h
+--- a/security/nss/lib/ckfw/builtins/nssckbi.h
++++ b/security/nss/lib/ckfw/builtins/nssckbi.h
+@@ -27,17 +27,17 @@
+  * Please use the following rules when increasing the version number:
+  *
+  * - starting with version 2.14, NSS_BUILTINS_LIBRARY_VERSION_MINOR
+  *   must always be an EVEN number (e.g. 16, 18, 20 etc.)
+  *
+  * - whenever possible, if older branches require a modification to the
+  *   list, these changes should be made on the main line of development (trunk),
+  *   and the older branches should update to the most recent list.
+- * 
++ *
+  * - ODD minor version numbers are reserved to indicate a snapshot that has
+  *   deviated from the main line of development, e.g. if it was necessary
+  *   to modify the list on a stable branch.
+  *   Once the version has been changed to an odd number (e.g. 2.13) on a branch,
+  *   it should remain unchanged on that branch, even if further changes are
+  *   made on that branch.
+  *
+  * NSS_BUILTINS_LIBRARY_VERSION_MINOR is a CK_BYTE.  It's not clear
+diff --git a/security/nss/lib/freebl/unix_urandom.c b/security/nss/lib/freebl/unix_urandom.c
+--- a/security/nss/lib/freebl/unix_urandom.c
++++ b/security/nss/lib/freebl/unix_urandom.c
+@@ -1,18 +1,22 @@
+ /* This Source Code Form is subject to the terms of the Mozilla Public
+  * 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/. */
+ 
+ #include <fcntl.h>
+ #include <unistd.h>
++#include <errno.h>
+ #include "secerr.h"
+ #include "secrng.h"
+ #include "prprf.h"
+ 
++/* syscall getentropy() is limited to retrieving 256 bytes */
++#define GETENTROPY_MAX_BYTES 256
++
+ void
+ RNG_SystemInfoForRNG(void)
+ {
+     PRUint8 bytes[SYSTEM_RNG_SEED_COUNT];
+     size_t numBytes = RNG_SystemRNG(bytes, SYSTEM_RNG_SEED_COUNT);
+     if (!numBytes) {
+         /* error is set */
+         return;
+@@ -23,16 +27,45 @@ RNG_SystemInfoForRNG(void)
+ size_t
+ RNG_SystemRNG(void *dest, size_t maxLen)
+ {
+     int fd;
+     int bytes;
+     size_t fileBytes = 0;
+     unsigned char *buffer = dest;
+ 
++#if defined(LINUX) && defined(__GLIBC__) && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 25)))
++    int result;
++
++    while (fileBytes < maxLen) {
++        size_t getBytes = maxLen - fileBytes;
++        if (getBytes > GETENTROPY_MAX_BYTES) {
++            getBytes = GETENTROPY_MAX_BYTES;
++        }
++        result = getentropy(buffer, getBytes);
++        if (result == 0) { /* success */
++            fileBytes += getBytes;
++            buffer += getBytes;
++        } else {
++            break;
++        }
++    }
++    if (fileBytes == maxLen) { /* success */
++        return maxLen;
++    }
++    /* If we failed with an error other than ENOSYS, it means the destination
++     * buffer is not writeable. We don't need to try writing to it again. */
++    if (errno != ENOSYS) {
++        PORT_SetError(SEC_ERROR_NEED_RANDOM);
++        return 0;
++    }
++    /* ENOSYS means the kernel doesn't support getentropy()/getrandom().
++     * Reset the number of bytes to get and fall back to /dev/urandom. */
++    fileBytes = 0;
++#endif
+     fd = open("/dev/urandom", O_RDONLY);
+     if (fd < 0) {
+         PORT_SetError(SEC_ERROR_NEED_RANDOM);
+         return 0;
+     }
+     while (fileBytes < maxLen) {
+         bytes = read(fd, buffer, maxLen - fileBytes);
+         if (bytes <= 0) {
+diff --git a/security/nss/lib/ssl/ssl3ecc.c b/security/nss/lib/ssl/ssl3ecc.c
+--- a/security/nss/lib/ssl/ssl3ecc.c
++++ b/security/nss/lib/ssl/ssl3ecc.c
+@@ -543,21 +543,23 @@ ssl3_HandleECDHServerKeyExchange(sslSock
+         desc = handshake_failure;
+         goto alert_loser;
+     }
+ 
+     PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2);
+     if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) {
+         rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
+         if (rv != SECSuccess) {
++            errCode = PORT_GetError();
+             goto alert_loser; /* malformed or unsupported. */
+         }
+         rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme,
+                                                  ss->sec.peerCert);
+         if (rv != SECSuccess) {
++            errCode = PORT_GetError();
+             goto alert_loser;
+         }
+         hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
+     } else {
+         /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
+         hashAlg = ssl_hash_none;
+         sigScheme = ssl_sig_none;
+     }

+ 127 - 0
rel-257/ian/patches/1445731-11-NSS337-61a1.patch

@@ -0,0 +1,127 @@
+# HG changeset patch
+# User J.C. Jones <jjones@mozilla.com>
+# Date 1525455768 25200
+#      Fri May 04 10:42:48 2018 -0700
+# Node ID b95fbd8db183e66d9880c2b407c342ef9ed7230a
+# Parent  d558d8be55ca6d1ff309b16f194716074c3c8e18
+Bug 1445731 - land NSS NSS_3_37_RTM UPGRADE_NSS_RELEASE, r=me
+
+diff --git a/old-configure.in b/old-configure.in
+--- a/old-configure.in
++++ b/old-configure.in
+@@ -1738,17 +1738,17 @@ dnl = If NSS was not detected in the sys
+ dnl = use the one in the source tree (mozilla/security/nss)
+ dnl ========================================================
+ 
+ MOZ_ARG_WITH_BOOL(system-nss,
+ [  --with-system-nss       Use system installed NSS],
+     _USE_SYSTEM_NSS=1 )
+ 
+ if test -n "$_USE_SYSTEM_NSS"; then
+-    AM_PATH_NSS(3.36.8, [MOZ_SYSTEM_NSS=1], [AC_MSG_ERROR([you don't have NSS installed or your version is too old])])
++    AM_PATH_NSS(3.37, [MOZ_SYSTEM_NSS=1], [AC_MSG_ERROR([you don't have NSS installed or your version is too old])])
+ fi
+ 
+ if test -z "$MOZ_SYSTEM_NSS"; then
+    NSS_CFLAGS="-I${DIST}/include/nss"
+    case "${OS_ARCH}" in
+         # Only few platforms have been tested with GYP
+         WINNT|Darwin|Linux|DragonFly|FreeBSD|NetBSD|OpenBSD|SunOS)
+             ;;
+diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO
+--- a/security/nss/TAG-INFO
++++ b/security/nss/TAG-INFO
+@@ -1,1 +1,1 @@
+-NSS_3_37_BETA2
++NSS_3_37_RTM
+diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep
+--- a/security/nss/coreconf/coreconf.dep
++++ b/security/nss/coreconf/coreconf.dep
+@@ -6,9 +6,8 @@
+ /*
+  * A dummy header file that is a dependency for all the object files.
+  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
+  * depend builds.  See comments in rules.mk.
+  */
+ 
+ #error "Do not include this header file."
+ 
+-
+diff --git a/security/nss/lib/nss/nss.h b/security/nss/lib/nss/nss.h
+--- a/security/nss/lib/nss/nss.h
++++ b/security/nss/lib/nss/nss.h
+@@ -17,22 +17,22 @@
+ 
+ /*
+  * NSS's major version, minor version, patch level, build number, and whether
+  * this is a beta release.
+  *
+  * The format of the version string should be
+  *     "<major version>.<minor version>[.<patch level>[.<build number>]][ <ECC>][ <Beta>]"
+  */
+-#define NSS_VERSION "3.37" _NSS_CUSTOMIZED " Beta"
++#define NSS_VERSION "3.37" _NSS_CUSTOMIZED
+ #define NSS_VMAJOR 3
+ #define NSS_VMINOR 37
+ #define NSS_VPATCH 0
+ #define NSS_VBUILD 0
+-#define NSS_BETA PR_TRUE
++#define NSS_BETA PR_FALSE
+ 
+ #ifndef RC_INVOKED
+ 
+ #include "seccomon.h"
+ 
+ typedef struct NSSInitParametersStr NSSInitParameters;
+ 
+ /*
+diff --git a/security/nss/lib/softoken/softkver.h b/security/nss/lib/softoken/softkver.h
+--- a/security/nss/lib/softoken/softkver.h
++++ b/security/nss/lib/softoken/softkver.h
+@@ -12,16 +12,16 @@
+ 
+ /*
+  * Softoken's major version, minor version, patch level, build number,
+  * and whether this is a beta release.
+  *
+  * The format of the version string should be
+  *     "<major version>.<minor version>[.<patch level>[.<build number>]][ <ECC>][ <Beta>]"
+  */
+-#define SOFTOKEN_VERSION "3.37" SOFTOKEN_ECC_STRING " Beta"
++#define SOFTOKEN_VERSION "3.37" SOFTOKEN_ECC_STRING
+ #define SOFTOKEN_VMAJOR 3
+ #define SOFTOKEN_VMINOR 37
+ #define SOFTOKEN_VPATCH 0
+ #define SOFTOKEN_VBUILD 0
+-#define SOFTOKEN_BETA PR_TRUE
++#define SOFTOKEN_BETA PR_FALSE
+ 
+ #endif /* _SOFTKVER_H_ */
+diff --git a/security/nss/lib/util/nssutil.h b/security/nss/lib/util/nssutil.h
+--- a/security/nss/lib/util/nssutil.h
++++ b/security/nss/lib/util/nssutil.h
+@@ -14,22 +14,22 @@
+ 
+ /*
+  * NSS utilities's major version, minor version, patch level, build number,
+  * and whether this is a beta release.
+  *
+  * The format of the version string should be
+  *     "<major version>.<minor version>[.<patch level>[.<build number>]][ <Beta>]"
+  */
+-#define NSSUTIL_VERSION "3.37 Beta"
++#define NSSUTIL_VERSION "3.37"
+ #define NSSUTIL_VMAJOR 3
+ #define NSSUTIL_VMINOR 37
+ #define NSSUTIL_VPATCH 0
+ #define NSSUTIL_VBUILD 0
+-#define NSSUTIL_BETA PR_TRUE
++#define NSSUTIL_BETA PR_FALSE
+ 
+ SEC_BEGIN_PROTOS
+ 
+ /*
+  * Returns a const string of the UTIL library version.
+  */
+ extern const char *NSSUTIL_GetVersion(void);
+ 

+ 4503 - 0
rel-257/ian/patches/1445731-2-NSS337-61a1.patch

@@ -0,0 +1,4503 @@
+# HG changeset patch
+# User J.C. Jones <jjones@mozilla.com>
+# Date 1521566255 25200
+#      Tue Mar 20 10:17:35 2018 -0700
+# Node ID 8072ac80797bc789d36e27a1cf2f1c9cb2154699
+# Parent  d9a14c71ddab6fd13b16afc769efe1fc1c24f5a3
+Bug 1445731 - land NSS c5dffd6269ea UPGRADE_NSS_RELEASE, r=me
+
+diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO
+--- a/security/nss/TAG-INFO
++++ b/security/nss/TAG-INFO
+@@ -1,1 +1,1 @@
+-f0d4789c8916
++c5dffd6269ea
+diff --git a/security/nss/cmd/shlibsign/shlibsign.c b/security/nss/cmd/shlibsign/shlibsign.c
+--- a/security/nss/cmd/shlibsign/shlibsign.c
++++ b/security/nss/cmd/shlibsign/shlibsign.c
+@@ -143,17 +143,17 @@ writeItem(PRFileDesc *fd, CK_VOID_PTR pV
+ 
+     encodeInt(buf, ulValueLen);
+     bytesWritten = PR_Write(fd, buf, 4);
+     if (bytesWritten != 4) {
+         lperror(file);
+         return PR_FAILURE;
+     }
+     bytesWritten = PR_Write(fd, pValue, ulValueLen);
+-    if (bytesWritten != ulValueLen) {
++    if (bytesWritten < 0 || (CK_ULONG)bytesWritten != ulValueLen) {
+         lperror(file);
+         return PR_FAILURE;
+     }
+     return PR_SUCCESS;
+ }
+ 
+ static const unsigned char prime[] = { 0x00,
+                                        0x97, 0x44, 0x1d, 0xcc, 0x0d, 0x39, 0x0d, 0x8d,
+diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep
+--- a/security/nss/coreconf/coreconf.dep
++++ b/security/nss/coreconf/coreconf.dep
+@@ -5,8 +5,9 @@
+ 
+ /*
+  * A dummy header file that is a dependency for all the object files.
+  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
+  * depend builds.  See comments in rules.mk.
+  */
+ 
+ #error "Do not include this header file."
++
+diff --git a/security/nss/cpputil/tls_parser.cc b/security/nss/cpputil/tls_parser.cc
+--- a/security/nss/cpputil/tls_parser.cc
++++ b/security/nss/cpputil/tls_parser.cc
+@@ -41,16 +41,31 @@ bool TlsParser::Read(DataBuffer* val, si
+     return false;
+   }
+ 
+   val->Assign(ptr(), len);
+   consume(len);
+   return true;
+ }
+ 
++bool TlsParser::ReadFromMark(DataBuffer* val, size_t len, size_t mark) {
++  auto saved = offset_;
++  offset_ = mark;
++
++  if (remaining() < len) {
++    offset_ = saved;
++    return false;
++  }
++
++  val->Assign(ptr(), len);
++
++  offset_ = saved;
++  return true;
++}
++
+ bool TlsParser::ReadVariable(DataBuffer* val, size_t len_size) {
+   uint32_t len;
+   if (!Read(&len, len_size)) {
+     return false;
+   }
+   return Read(val, len);
+ }
+ 
+diff --git a/security/nss/cpputil/tls_parser.h b/security/nss/cpputil/tls_parser.h
+--- a/security/nss/cpputil/tls_parser.h
++++ b/security/nss/cpputil/tls_parser.h
+@@ -118,16 +118,17 @@ class TlsParser {
+   TlsParser(const uint8_t* data, size_t len) : buffer_(data, len), offset_(0) {}
+   explicit TlsParser(const DataBuffer& buf) : buffer_(buf), offset_(0) {}
+ 
+   bool Read(uint8_t* val);
+   // Read an integral type of specified width.
+   bool Read(uint32_t* val, size_t size);
+   // Reads len bytes into dest buffer, overwriting it.
+   bool Read(DataBuffer* dest, size_t len);
++  bool ReadFromMark(DataBuffer* val, size_t len, size_t mark);
+   // Reads bytes into dest buffer, overwriting it.  The number of bytes is
+   // determined by reading from len_size bytes from the stream first.
+   bool ReadVariable(DataBuffer* dest, size_t len_size);
+ 
+   bool Skip(size_t len);
+   bool SkipVariable(size_t len_size);
+ 
+   size_t consumed() const { return offset_; }
+diff --git a/security/nss/gtests/ssl_gtest/libssl_internals.c b/security/nss/gtests/ssl_gtest/libssl_internals.c
+--- a/security/nss/gtests/ssl_gtest/libssl_internals.c
++++ b/security/nss/gtests/ssl_gtest/libssl_internals.c
+@@ -232,32 +232,33 @@ PRBool SSLInt_SendAlert(PRFileDesc *fd, 
+ SECStatus SSLInt_AdvanceReadSeqNum(PRFileDesc *fd, PRUint64 to) {
+   sslSocket *ss;
+   ssl3CipherSpec *spec;
+ 
+   ss = ssl_FindSocket(fd);
+   if (!ss) {
+     return SECFailure;
+   }
+-  if (to >= RECORD_SEQ_MAX) {
++  if (to > RECORD_SEQ_MAX) {
+     PORT_SetError(SEC_ERROR_INVALID_ARGS);
+     return SECFailure;
+   }
+   ssl_GetSpecWriteLock(ss);
+   spec = ss->ssl3.crSpec;
+-  spec->seqNum = to;
++  spec->nextSeqNum = to;
+ 
+   /* For DTLS, we need to fix the record sequence number.  For this, we can just
+    * scrub the entire structure on the assumption that the new sequence number
+    * is far enough past the last received sequence number. */
+-  if (spec->seqNum <= spec->recvdRecords.right + DTLS_RECVD_RECORDS_WINDOW) {
++  if (spec->nextSeqNum <=
++      spec->recvdRecords.right + DTLS_RECVD_RECORDS_WINDOW) {
+     PORT_SetError(SEC_ERROR_INVALID_ARGS);
+     return SECFailure;
+   }
+-  dtls_RecordSetRecvd(&spec->recvdRecords, spec->seqNum);
++  dtls_RecordSetRecvd(&spec->recvdRecords, spec->nextSeqNum - 1);
+ 
+   ssl_ReleaseSpecWriteLock(ss);
+   return SECSuccess;
+ }
+ 
+ SECStatus SSLInt_AdvanceWriteSeqNum(PRFileDesc *fd, PRUint64 to) {
+   sslSocket *ss;
+ 
+@@ -265,31 +266,31 @@ SECStatus SSLInt_AdvanceWriteSeqNum(PRFi
+   if (!ss) {
+     return SECFailure;
+   }
+   if (to >= RECORD_SEQ_MAX) {
+     PORT_SetError(SEC_ERROR_INVALID_ARGS);
+     return SECFailure;
+   }
+   ssl_GetSpecWriteLock(ss);
+-  ss->ssl3.cwSpec->seqNum = to;
++  ss->ssl3.cwSpec->nextSeqNum = to;
+   ssl_ReleaseSpecWriteLock(ss);
+   return SECSuccess;
+ }
+ 
+ SECStatus SSLInt_AdvanceWriteSeqByAWindow(PRFileDesc *fd, PRInt32 extra) {
+   sslSocket *ss;
+   sslSequenceNumber to;
+ 
+   ss = ssl_FindSocket(fd);
+   if (!ss) {
+     return SECFailure;
+   }
+   ssl_GetSpecReadLock(ss);
+-  to = ss->ssl3.cwSpec->seqNum + DTLS_RECVD_RECORDS_WINDOW + extra;
++  to = ss->ssl3.cwSpec->nextSeqNum + DTLS_RECVD_RECORDS_WINDOW + extra;
+   ssl_ReleaseSpecReadLock(ss);
+   return SSLInt_AdvanceWriteSeqNum(fd, to);
+ }
+ 
+ SSLKEAType SSLInt_GetKEAType(SSLNamedGroup group) {
+   const sslNamedGroupDef *groupDef = ssl_LookupNamedGroup(group);
+   if (!groupDef) return ssl_kea_null;
+ 
+diff --git a/security/nss/gtests/ssl_gtest/ssl_agent_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_agent_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_agent_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_agent_unittest.cc
+@@ -3,30 +3,26 @@
+ /* This Source Code Form is subject to the terms of the Mozilla Public
+  * 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/. */
+ 
+ #include "ssl.h"
+ #include "sslerr.h"
+ #include "sslproto.h"
+ 
+-// This is an internal header, used to get TLS_1_3_DRAFT_VERSION.
+-#include "ssl3prot.h"
+-
+ #include <memory>
+ 
+ #include "databuffer.h"
+ #include "tls_agent.h"
+ #include "tls_connect.h"
+ #include "tls_filter.h"
+ #include "tls_parser.h"
+ 
+ namespace nss_test {
+ 
+-static const uint8_t kD13 = TLS_1_3_DRAFT_VERSION;
+ // This is a 1-RTT ClientHello with ECDHE.
+ const static uint8_t kCannedTls13ClientHello[] = {
+     0x01, 0x00, 0x00, 0xcf, 0x03, 0x03, 0x6c, 0xb3, 0x46, 0x81, 0xc8, 0x1a,
+     0xf9, 0xd2, 0x05, 0x97, 0x48, 0x7c, 0xa8, 0x31, 0x03, 0x1c, 0x06, 0xa8,
+     0x62, 0xb1, 0x90, 0xd6, 0x21, 0x44, 0x7f, 0xc1, 0x9b, 0x87, 0x3e, 0xad,
+     0x91, 0x85, 0x00, 0x00, 0x06, 0x13, 0x01, 0x13, 0x03, 0x13, 0x02, 0x01,
+     0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x09, 0x00, 0x00, 0x06,
+     0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0xff, 0x01, 0x00, 0x01, 0x00, 0x00,
+@@ -37,26 +33,17 @@ const static uint8_t kCannedTls13ClientH
+     0xbf, 0x73, 0x47, 0x3c, 0x9c, 0x65, 0x8c, 0x47, 0x6d, 0x57, 0x22, 0x8a,
+     0xc2, 0xb3, 0xc6, 0x80, 0x72, 0x86, 0x08, 0x86, 0x8f, 0x52, 0xc5, 0xcb,
+     0xbf, 0x2a, 0xb5, 0x59, 0x64, 0xcc, 0x0c, 0x49, 0x95, 0x36, 0xe4, 0xd9,
+     0x2f, 0xd4, 0x24, 0x66, 0x71, 0x6f, 0x5d, 0x70, 0xe2, 0xa0, 0xea, 0x26,
+     0x00, 0x2b, 0x00, 0x03, 0x02, 0x7f, kD13, 0x00, 0x0d, 0x00, 0x20, 0x00,
+     0x1e, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03, 0x02, 0x03, 0x08, 0x04, 0x08,
+     0x05, 0x08, 0x06, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01, 0x02, 0x01, 0x04,
+     0x02, 0x05, 0x02, 0x06, 0x02, 0x02, 0x02};
+-
+-const static uint8_t kCannedTls13ServerHello[] = {
+-    0x03, 0x03, 0x9c, 0xbc, 0x14, 0x9b, 0x0e, 0x2e, 0xfa, 0x0d, 0xf3,
+-    0xf0, 0x5c, 0x70, 0x7a, 0xe0, 0xd1, 0x9b, 0x3e, 0x5a, 0x44, 0x6b,
+-    0xdf, 0xe5, 0xc2, 0x28, 0x64, 0xf7, 0x00, 0xc1, 0x9c, 0x08, 0x76,
+-    0x08, 0x00, 0x13, 0x01, 0x00, 0x00, 0x2e, 0x00, 0x33, 0x00, 0x24,
+-    0x00, 0x1d, 0x00, 0x20, 0xc2, 0xcf, 0x23, 0x17, 0x64, 0x23, 0x03,
+-    0xf0, 0xfb, 0x45, 0x98, 0x26, 0xd1, 0x65, 0x24, 0xa1, 0x6c, 0xa9,
+-    0x80, 0x8f, 0x2c, 0xac, 0x0a, 0xea, 0x53, 0x3a, 0xcb, 0xe3, 0x08,
+-    0x84, 0xae, 0x19, 0x00, 0x2b, 0x00, 0x02, 0x7f, kD13};
++static const size_t kFirstFragmentSize = 20;
+ static const char *k0RttData = "ABCDEF";
+ 
+ TEST_P(TlsAgentTest, EarlyFinished) {
+   DataBuffer buffer;
+   MakeTrivialHandshakeRecord(kTlsHandshakeFinished, 0, &buffer);
+   ExpectAlert(kTlsAlertUnexpectedMessage);
+   ProcessMessage(buffer, TlsAgent::STATE_ERROR,
+                  SSL_ERROR_RX_UNEXPECTED_FINISHED);
+@@ -69,75 +56,79 @@ TEST_P(TlsAgentTest, EarlyCertificateVer
+   ProcessMessage(buffer, TlsAgent::STATE_ERROR,
+                  SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
+ }
+ 
+ TEST_P(TlsAgentTestClient13, CannedHello) {
+   DataBuffer buffer;
+   EnsureInit();
+   DataBuffer server_hello;
+-  MakeHandshakeMessage(kTlsHandshakeServerHello, kCannedTls13ServerHello,
+-                       sizeof(kCannedTls13ServerHello), &server_hello);
++  auto sh = MakeCannedTls13ServerHello();
++  MakeHandshakeMessage(kTlsHandshakeServerHello, sh.data(), sh.len(),
++                       &server_hello);
+   MakeRecord(kTlsHandshakeType, SSL_LIBRARY_VERSION_TLS_1_3,
+              server_hello.data(), server_hello.len(), &buffer);
+   ProcessMessage(buffer, TlsAgent::STATE_CONNECTING);
+ }
+ 
+ TEST_P(TlsAgentTestClient13, EncryptedExtensionsInClear) {
+   DataBuffer server_hello;
+-  MakeHandshakeMessage(kTlsHandshakeServerHello, kCannedTls13ServerHello,
+-                       sizeof(kCannedTls13ServerHello), &server_hello);
++  auto sh = MakeCannedTls13ServerHello();
++  MakeHandshakeMessage(kTlsHandshakeServerHello, sh.data(), sh.len(),
++                       &server_hello);
+   DataBuffer encrypted_extensions;
+   MakeHandshakeMessage(kTlsHandshakeEncryptedExtensions, nullptr, 0,
+                        &encrypted_extensions, 1);
+   server_hello.Append(encrypted_extensions);
+   DataBuffer buffer;
+   MakeRecord(kTlsHandshakeType, SSL_LIBRARY_VERSION_TLS_1_3,
+              server_hello.data(), server_hello.len(), &buffer);
+   EnsureInit();
+   ExpectAlert(kTlsAlertUnexpectedMessage);
+   ProcessMessage(buffer, TlsAgent::STATE_ERROR,
+                  SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
+ }
+ 
+ TEST_F(TlsAgentStreamTestClient, EncryptedExtensionsInClearTwoPieces) {
+   DataBuffer server_hello;
+-  MakeHandshakeMessage(kTlsHandshakeServerHello, kCannedTls13ServerHello,
+-                       sizeof(kCannedTls13ServerHello), &server_hello);
++  auto sh = MakeCannedTls13ServerHello();
++  MakeHandshakeMessage(kTlsHandshakeServerHello, sh.data(), sh.len(),
++                       &server_hello);
+   DataBuffer encrypted_extensions;
+   MakeHandshakeMessage(kTlsHandshakeEncryptedExtensions, nullptr, 0,
+                        &encrypted_extensions, 1);
+   server_hello.Append(encrypted_extensions);
+   DataBuffer buffer;
+   MakeRecord(kTlsHandshakeType, SSL_LIBRARY_VERSION_TLS_1_3,
+-             server_hello.data(), 20, &buffer);
++             server_hello.data(), kFirstFragmentSize, &buffer);
+ 
+   DataBuffer buffer2;
+   MakeRecord(kTlsHandshakeType, SSL_LIBRARY_VERSION_TLS_1_3,
+-             server_hello.data() + 20, server_hello.len() - 20, &buffer2);
++             server_hello.data() + kFirstFragmentSize,
++             server_hello.len() - kFirstFragmentSize, &buffer2);
+ 
+   EnsureInit();
+   agent_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_3,
+                           SSL_LIBRARY_VERSION_TLS_1_3);
+   ProcessMessage(buffer, TlsAgent::STATE_CONNECTING);
+   ExpectAlert(kTlsAlertUnexpectedMessage);
+   ProcessMessage(buffer2, TlsAgent::STATE_ERROR,
+                  SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
+ }
+ 
+ TEST_F(TlsAgentDgramTestClient, EncryptedExtensionsInClearTwoPieces) {
++  auto sh = MakeCannedTls13ServerHello();
+   DataBuffer server_hello_frag1;
+-  MakeHandshakeMessageFragment(
+-      kTlsHandshakeServerHello, kCannedTls13ServerHello,
+-      sizeof(kCannedTls13ServerHello), &server_hello_frag1, 0, 0, 20);
++  MakeHandshakeMessageFragment(kTlsHandshakeServerHello, sh.data(), sh.len(),
++                               &server_hello_frag1, 0, 0, kFirstFragmentSize);
+   DataBuffer server_hello_frag2;
+-  MakeHandshakeMessageFragment(
+-      kTlsHandshakeServerHello, kCannedTls13ServerHello + 20,
+-      sizeof(kCannedTls13ServerHello), &server_hello_frag2, 0, 20,
+-      sizeof(kCannedTls13ServerHello) - 20);
++  MakeHandshakeMessageFragment(kTlsHandshakeServerHello,
++                               sh.data() + kFirstFragmentSize, sh.len(),
++                               &server_hello_frag2, 0, kFirstFragmentSize,
++                               sh.len() - kFirstFragmentSize);
+   DataBuffer encrypted_extensions;
+   MakeHandshakeMessage(kTlsHandshakeEncryptedExtensions, nullptr, 0,
+                        &encrypted_extensions, 1);
+   server_hello_frag2.Append(encrypted_extensions);
+   DataBuffer buffer;
+   MakeRecord(kTlsHandshakeType, SSL_LIBRARY_VERSION_TLS_1_3,
+              server_hello_frag1.data(), server_hello_frag1.len(), &buffer);
+ 
+diff --git a/security/nss/gtests/ssl_gtest/ssl_ciphersuite_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_ciphersuite_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_ciphersuite_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_ciphersuite_unittest.cc
+@@ -161,18 +161,18 @@ class TlsCipherSuiteTestBase : public Tl
+       case ssl_calg_rc2:
+       case ssl_calg_des:
+       case ssl_calg_idea:
+       case ssl_calg_fortezza:
+       case ssl_calg_camellia:
+       case ssl_calg_seed:
+         break;
+     }
+-    EXPECT_TRUE(false) << "No limit for " << csinfo_.cipherSuiteName;
+-    return 1ULL < 48;
++    ADD_FAILURE() << "No limit for " << csinfo_.cipherSuiteName;
++    return 0;
+   }
+ 
+   uint64_t last_safe_write() const {
+     uint64_t limit = record_limit() - 1;
+     if (version_ < SSL_LIBRARY_VERSION_TLS_1_1 &&
+         (csinfo_.symCipher == ssl_calg_3des ||
+          csinfo_.symCipher == ssl_calg_aes)) {
+       // 1/n-1 record splitting needs space for two records.
+@@ -241,22 +241,23 @@ TEST_P(TlsCipherSuiteTest, ReadLimit) {
+   ConnectAndCheckCipherSuite();
+   if (version_ < SSL_LIBRARY_VERSION_TLS_1_3) {
+     uint64_t last = last_safe_write();
+     EXPECT_EQ(SECSuccess, SSLInt_AdvanceWriteSeqNum(client_->ssl_fd(), last));
+     EXPECT_EQ(SECSuccess, SSLInt_AdvanceReadSeqNum(server_->ssl_fd(), last));
+ 
+     client_->SendData(10, 10);
+     server_->ReadBytes();  // This should be OK.
++    server_->ReadBytes();  // Read twice to flush any 1,N-1 record splitting.
+   } else {
+     // In TLS 1.3, reading or writing triggers a KeyUpdate.  That would mean
+     // that the sequence numbers would reset and we wouldn't hit the limit.  So
+-    // we move the sequence number to one less than the limit directly and don't
+-    // test sending and receiving just before the limit.
+-    uint64_t last = record_limit() - 1;
++    // move the sequence number to the limit directly and don't test sending and
++    // receiving just before the limit.
++    uint64_t last = record_limit();
+     EXPECT_EQ(SECSuccess, SSLInt_AdvanceReadSeqNum(server_->ssl_fd(), last));
+   }
+ 
+   // The payload needs to be big enough to pass for encrypted.  The code checks
+   // the limit before it tries to decrypt.
+   static const uint8_t payload[32] = {6};
+   DataBuffer record;
+   uint64_t epoch;
+diff --git a/security/nss/gtests/ssl_gtest/ssl_drop_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_drop_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_drop_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_drop_unittest.cc
+@@ -61,27 +61,31 @@ TEST_P(TlsConnectDatagramPre13, DropClie
+ }
+ 
+ // This drops the server's second flight three times.
+ TEST_P(TlsConnectDatagramPre13, DropServerSecondFlightThrice) {
+   server_->SetFilter(std::make_shared<SelectiveDropFilter>(0xe));
+   Connect();
+ }
+ 
+-class TlsDropDatagram13 : public TlsConnectDatagram13 {
++class TlsDropDatagram13 : public TlsConnectDatagram13,
++                          public ::testing::WithParamInterface<bool> {
+  public:
+   TlsDropDatagram13()
+       : client_filters_(),
+         server_filters_(),
+         expected_client_acks_(0),
+         expected_server_acks_(1) {}
+ 
+   void SetUp() override {
+     TlsConnectDatagram13::SetUp();
+     ConfigureSessionCache(RESUME_NONE, RESUME_NONE);
++    int short_header = GetParam() ? PR_TRUE : PR_FALSE;
++    client_->SetOption(SSL_ENABLE_DTLS_SHORT_HEADER, short_header);
++    server_->SetOption(SSL_ENABLE_DTLS_SHORT_HEADER, short_header);
+     SetFilters();
+   }
+ 
+   void SetFilters() {
+     EnsureTlsSetup();
+     client_filters_.Init(client_);
+     server_filters_.Init(server_);
+   }
+@@ -181,66 +185,66 @@ class TlsDropDatagram13 : public TlsConn
+   size_t expected_client_acks_;
+   size_t expected_server_acks_;
+ };
+ 
+ // All of these tests produce a minimum one ACK, from the server
+ // to the client upon receiving the client Finished.
+ // Dropping complete first and second flights does not produce
+ // ACKs
+-TEST_F(TlsDropDatagram13, DropClientFirstFlightOnce) {
++TEST_P(TlsDropDatagram13, DropClientFirstFlightOnce) {
+   client_filters_.drop_->Reset({0});
+   StartConnect();
+   client_->Handshake();
+   server_->Handshake();
+   CheckedHandshakeSendReceive();
+   CheckAcks(server_filters_, 0, {0x0002000000000000ULL});
+ }
+ 
+-TEST_F(TlsDropDatagram13, DropServerFirstFlightOnce) {
++TEST_P(TlsDropDatagram13, DropServerFirstFlightOnce) {
+   server_filters_.drop_->Reset(0xff);
+   StartConnect();
+   client_->Handshake();
+   // Send the first flight, all dropped.
+   server_->Handshake();
+   server_filters_.drop_->Disable();
+   CheckedHandshakeSendReceive();
+   CheckAcks(server_filters_, 0, {0x0002000000000000ULL});
+ }
+ 
+ // Dropping the server's first record also does not produce
+ // an ACK because the next record is ignored.
+ // TODO(ekr@rtfm.com): We should generate an empty ACK.
+-TEST_F(TlsDropDatagram13, DropServerFirstRecordOnce) {
++TEST_P(TlsDropDatagram13, DropServerFirstRecordOnce) {
+   server_filters_.drop_->Reset({0});
+   StartConnect();
+   client_->Handshake();
+   server_->Handshake();
+   Handshake();
+   CheckedHandshakeSendReceive();
+   CheckAcks(server_filters_, 0, {0x0002000000000000ULL});
+ }
+ 
+ // Dropping the second packet of the server's flight should
+ // produce an ACK.
+-TEST_F(TlsDropDatagram13, DropServerSecondRecordOnce) {
++TEST_P(TlsDropDatagram13, DropServerSecondRecordOnce) {
+   server_filters_.drop_->Reset({1});
+   StartConnect();
+   client_->Handshake();
+   server_->Handshake();
+   HandshakeAndAck(client_);
+   expected_client_acks_ = 1;
+   CheckedHandshakeSendReceive();
+   CheckAcks(client_filters_, 0, {0});  // ServerHello
+   CheckAcks(server_filters_, 0, {0x0002000000000000ULL});
+ }
+ 
+ // Drop the server ACK and verify that the client retransmits
+ // the ClientHello.
+-TEST_F(TlsDropDatagram13, DropServerAckOnce) {
++TEST_P(TlsDropDatagram13, DropServerAckOnce) {
+   StartConnect();
+   client_->Handshake();
+   server_->Handshake();
+   // At this point the server has sent it's first flight,
+   // so make it drop the ACK.
+   server_filters_.drop_->Reset({0});
+   client_->Handshake();  // Send the client Finished.
+   server_->Handshake();  // Receive the Finished and send the ACK.
+@@ -258,17 +262,17 @@ TEST_F(TlsDropDatagram13, DropServerAckO
+   EXPECT_EQ(PR_WOULD_BLOCK_ERROR, PORT_GetError());
+   CheckPostHandshake();
+   // There should be two copies of the finished ACK
+   CheckAcks(server_filters_, 0, {0x0002000000000000ULL});
+   CheckAcks(server_filters_, 1, {0x0002000000000000ULL});
+ }
+ 
+ // Drop the client certificate verify.
+-TEST_F(TlsDropDatagram13, DropClientCertVerify) {
++TEST_P(TlsDropDatagram13, DropClientCertVerify) {
+   StartConnect();
+   client_->SetupClientAuth();
+   server_->RequestClientAuth(true);
+   client_->Handshake();
+   server_->Handshake();
+   // Have the client drop Cert Verify
+   client_filters_.drop_->Reset({1});
+   expected_server_acks_ = 2;
+@@ -279,17 +283,17 @@ TEST_F(TlsDropDatagram13, DropClientCert
+   CheckAcks(
+       server_filters_, 1,
+       {0x0002000000000000ULL,    // CH (we drop everything after this on client)
+        0x0002000000000003ULL,    // CT (2)
+        0x0002000000000004ULL});  // FIN (2)
+ }
+ 
+ // Shrink the MTU down so that certs get split and drop the first piece.
+-TEST_F(TlsDropDatagram13, DropFirstHalfOfServerCertificate) {
++TEST_P(TlsDropDatagram13, DropFirstHalfOfServerCertificate) {
+   server_filters_.drop_->Reset({2});
+   StartConnect();
+   ShrinkPostServerHelloMtu();
+   client_->Handshake();
+   server_->Handshake();
+   // Check that things got split.
+   EXPECT_EQ(6UL,
+             server_filters_.records_->count());  // SH, EE, CT1, CT2, CV, FIN
+@@ -306,17 +310,17 @@ TEST_F(TlsDropDatagram13, DropFirstHalfO
+   CheckAcks(client_filters_, 0,
+             {0,                        // SH
+              0x0002000000000000ULL,    // EE
+              0x0002000000000002ULL});  // CT2
+   CheckAcks(server_filters_, 0, {0x0002000000000000ULL});
+ }
+ 
+ // Shrink the MTU down so that certs get split and drop the second piece.
+-TEST_F(TlsDropDatagram13, DropSecondHalfOfServerCertificate) {
++TEST_P(TlsDropDatagram13, DropSecondHalfOfServerCertificate) {
+   server_filters_.drop_->Reset({3});
+   StartConnect();
+   ShrinkPostServerHelloMtu();
+   client_->Handshake();
+   server_->Handshake();
+   // Check that things got split.
+   EXPECT_EQ(6UL,
+             server_filters_.records_->count());  // SH, EE, CT1, CT2, CV, FIN
+@@ -519,21 +523,21 @@ class TlsFragmentationAndRecoveryTest : 
+ 
+   size_t server_record_len(size_t index) const {
+     return server_filters_.records_->record(index).buffer.len();
+   }
+ 
+   size_t cert_len_;
+ };
+ 
+-TEST_F(TlsFragmentationAndRecoveryTest, DropFirstHalf) { RunTest(0); }
++TEST_P(TlsFragmentationAndRecoveryTest, DropFirstHalf) { RunTest(0); }
+ 
+-TEST_F(TlsFragmentationAndRecoveryTest, DropSecondHalf) { RunTest(1); }
++TEST_P(TlsFragmentationAndRecoveryTest, DropSecondHalf) { RunTest(1); }
+ 
+-TEST_F(TlsDropDatagram13, NoDropsDuringZeroRtt) {
++TEST_P(TlsDropDatagram13, NoDropsDuringZeroRtt) {
+   SetupForZeroRtt();
+   SetFilters();
+   std::cerr << "Starting second handshake" << std::endl;
+   client_->Set0RttEnabled(true);
+   server_->Set0RttEnabled(true);
+   ExpectResumption(RESUME_TICKET);
+   ZeroRttSendReceive(true, true);
+   Handshake();
+@@ -541,17 +545,17 @@ TEST_F(TlsDropDatagram13, NoDropsDuringZ
+   CheckConnected();
+   SendReceive();
+   EXPECT_EQ(0U, client_filters_.ack_->count());
+   CheckAcks(server_filters_, 0,
+             {0x0001000000000001ULL,    // EOED
+              0x0002000000000000ULL});  // Finished
+ }
+ 
+-TEST_F(TlsDropDatagram13, DropEEDuringZeroRtt) {
++TEST_P(TlsDropDatagram13, DropEEDuringZeroRtt) {
+   SetupForZeroRtt();
+   SetFilters();
+   std::cerr << "Starting second handshake" << std::endl;
+   client_->Set0RttEnabled(true);
+   server_->Set0RttEnabled(true);
+   ExpectResumption(RESUME_TICKET);
+   server_filters_.drop_->Reset({1});
+   ZeroRttSendReceive(true, true);
+@@ -586,17 +590,17 @@ class TlsReorderDatagram13 : public TlsD
+     for (auto i : indices) {
+       agent->SendRecordDirect(records->record(i));
+     }
+   }
+ };
+ 
+ // Reorder the server records so that EE comes at the end
+ // of the flight and will still produce an ACK.
+-TEST_F(TlsDropDatagram13, ReorderServerEE) {
++TEST_P(TlsDropDatagram13, ReorderServerEE) {
+   server_filters_.drop_->Reset({1});
+   StartConnect();
+   client_->Handshake();
+   server_->Handshake();
+   // We dropped EE, now reinject.
+   server_->SendRecordDirect(server_filters_.record(1));
+   expected_client_acks_ = 1;
+   HandshakeAndAck(client_);
+@@ -642,70 +646,70 @@ class TlsSendCipherSpecCapturer {
+                           SSLInt_CipherSpecToIv(newSpec));
+     EXPECT_EQ(true, ret);
+     self->send_cipher_specs_.push_back(spec);
+   }
+ 
+   std::vector<std::shared_ptr<TlsCipherSpec>> send_cipher_specs_;
+ };
+ 
+-TEST_F(TlsDropDatagram13, SendOutOfOrderAppWithHandshakeKey) {
++TEST_P(TlsDropDatagram13, SendOutOfOrderAppWithHandshakeKey) {
+   StartConnect();
+   TlsSendCipherSpecCapturer capturer(client_);
+   client_->Handshake();
+   server_->Handshake();
+   client_->Handshake();
+   EXPECT_EQ(TlsAgent::STATE_CONNECTED, client_->state());
+   server_->Handshake();
+   EXPECT_EQ(TlsAgent::STATE_CONNECTED, server_->state());
+   // After the client sends Finished, inject an app data record
+   // with the handshake key. This should produce an alert.
+   uint8_t buf[] = {'a', 'b', 'c'};
+   auto spec = capturer.spec(0);
+   ASSERT_NE(nullptr, spec.get());
+   ASSERT_EQ(2, spec->epoch());
+-  ASSERT_TRUE(client_->SendEncryptedRecord(
+-      spec, SSL_LIBRARY_VERSION_DTLS_1_2_WIRE, 0x0002000000000002,
+-      kTlsApplicationDataType, DataBuffer(buf, sizeof(buf))));
++  ASSERT_TRUE(client_->SendEncryptedRecord(spec, 0x0002000000000002,
++                                           kTlsApplicationDataType,
++                                           DataBuffer(buf, sizeof(buf))));
+ 
+   // Now have the server consume the bogus message.
+   server_->ExpectSendAlert(illegal_parameter, kTlsAlertFatal);
+   server_->Handshake();
+   EXPECT_EQ(TlsAgent::STATE_ERROR, server_->state());
+   EXPECT_EQ(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE, PORT_GetError());
+ }
+ 
+-TEST_F(TlsDropDatagram13, SendOutOfOrderHsNonsenseWithHandshakeKey) {
++TEST_P(TlsDropDatagram13, SendOutOfOrderHsNonsenseWithHandshakeKey) {
+   StartConnect();
+   TlsSendCipherSpecCapturer capturer(client_);
+   client_->Handshake();
+   server_->Handshake();
+   client_->Handshake();
+   EXPECT_EQ(TlsAgent::STATE_CONNECTED, client_->state());
+   server_->Handshake();
+   EXPECT_EQ(TlsAgent::STATE_CONNECTED, server_->state());
+   // Inject a new bogus handshake record, which the server responds
+   // to by just ACKing the original one (we ignore the contents).
+   uint8_t buf[] = {'a', 'b', 'c'};
+   auto spec = capturer.spec(0);
+   ASSERT_NE(nullptr, spec.get());
+   ASSERT_EQ(2, spec->epoch());
+-  ASSERT_TRUE(client_->SendEncryptedRecord(
+-      spec, SSL_LIBRARY_VERSION_DTLS_1_2_WIRE, 0x0002000000000002,
+-      kTlsHandshakeType, DataBuffer(buf, sizeof(buf))));
++  ASSERT_TRUE(client_->SendEncryptedRecord(spec, 0x0002000000000002,
++                                           kTlsHandshakeType,
++                                           DataBuffer(buf, sizeof(buf))));
+   server_->Handshake();
+   EXPECT_EQ(2UL, server_filters_.ack_->count());
+   // The server acknowledges client Finished twice.
+   CheckAcks(server_filters_, 0, {0x0002000000000000ULL});
+   CheckAcks(server_filters_, 1, {0x0002000000000000ULL});
+ }
+ 
+ // Shrink the MTU down so that certs get split and then swap the first and
+ // second pieces of the server certificate.
+-TEST_F(TlsReorderDatagram13, ReorderServerCertificate) {
++TEST_P(TlsReorderDatagram13, ReorderServerCertificate) {
+   StartConnect();
+   ShrinkPostServerHelloMtu();
+   client_->Handshake();
+   // Drop the entire handshake flight so we can reorder.
+   server_filters_.drop_->Reset(0xff);
+   server_->Handshake();
+   // Check that things got split.
+   EXPECT_EQ(6UL,
+@@ -717,17 +721,17 @@ TEST_F(TlsReorderDatagram13, ReorderServ
+   server_filters_.records_->Clear();
+   // Wait for client to send ACK.
+   ShiftDtlsTimers();
+   CheckedHandshakeSendReceive();
+   EXPECT_EQ(2UL, server_filters_.records_->count());  // ACK + Data
+   CheckAcks(server_filters_, 0, {0x0002000000000000ULL});
+ }
+ 
+-TEST_F(TlsReorderDatagram13, DataAfterEOEDDuringZeroRtt) {
++TEST_P(TlsReorderDatagram13, DataAfterEOEDDuringZeroRtt) {
+   SetupForZeroRtt();
+   SetFilters();
+   std::cerr << "Starting second handshake" << std::endl;
+   client_->Set0RttEnabled(true);
+   server_->Set0RttEnabled(true);
+   ExpectResumption(RESUME_TICKET);
+   // Send the client's first flight of zero RTT data.
+   ZeroRttSendReceive(true, true);
+@@ -756,17 +760,17 @@ TEST_F(TlsReorderDatagram13, DataAfterEO
+   // Acknowledgements for EOED and Finished.
+   CheckAcks(server_filters_, 0, {0x0001000000000002ULL, 0x0002000000000000ULL});
+   uint8_t buf[8];
+   rv = PR_Read(server_->ssl_fd(), buf, sizeof(buf));
+   EXPECT_EQ(-1, rv);
+   EXPECT_EQ(PR_WOULD_BLOCK_ERROR, PORT_GetError());
+ }
+ 
+-TEST_F(TlsReorderDatagram13, DataAfterFinDuringZeroRtt) {
++TEST_P(TlsReorderDatagram13, DataAfterFinDuringZeroRtt) {
+   SetupForZeroRtt();
+   SetFilters();
+   std::cerr << "Starting second handshake" << std::endl;
+   client_->Set0RttEnabled(true);
+   server_->Set0RttEnabled(true);
+   ExpectResumption(RESUME_TICKET);
+   // Send the client's first flight of zero RTT data.
+   ZeroRttSendReceive(true, true);
+@@ -807,38 +811,54 @@ static void GetCipherAndLimit(uint16_t v
+ 
+   if (version < SSL_LIBRARY_VERSION_TLS_1_2) {
+     *cipher = TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA;
+     *limit = 0x5aULL << 28;
+   } else if (version == SSL_LIBRARY_VERSION_TLS_1_2) {
+     *cipher = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256;
+     *limit = (1ULL << 48) - 1;
+   } else {
++    // This test probably isn't especially useful for TLS 1.3, which has a much
++    // shorter sequence number encoding.  That space can probably be searched in
++    // a reasonable amount of time.
+     *cipher = TLS_CHACHA20_POLY1305_SHA256;
+-    *limit = (1ULL << 48) - 1;
++    // Assume that we are starting with an expected sequence number of 0.
++    *limit = (1ULL << 29) - 1;
+   }
+ }
+ 
+ // This simulates a huge number of drops on one side.
++// See Bug 12965514 where a large gap was handled very inefficiently.
+ TEST_P(TlsConnectDatagram, MissLotsOfPackets) {
+   uint16_t cipher;
+   uint64_t limit;
+ 
+   GetCipherAndLimit(version_, &cipher, &limit);
+ 
+   EnsureTlsSetup();
+   server_->EnableSingleCipher(cipher);
+   Connect();
+ 
+   // Note that the limit for ChaCha is 2^48-1.
+   EXPECT_EQ(SECSuccess,
+             SSLInt_AdvanceWriteSeqNum(client_->ssl_fd(), limit - 10));
+   SendReceive();
+ }
+ 
++// Send a sequence number of 0xfffffffd and it should be interpreted as that
++// (and not -3 or UINT64_MAX - 2).
++TEST_F(TlsConnectDatagram13, UnderflowSequenceNumber) {
++  Connect();
++  // This is only valid if short headers are disabled.
++  client_->SetOption(SSL_ENABLE_DTLS_SHORT_HEADER, PR_FALSE);
++  EXPECT_EQ(SECSuccess,
++            SSLInt_AdvanceWriteSeqNum(client_->ssl_fd(), (1ULL << 30) - 3));
++  SendReceive();
++}
++
+ class TlsConnectDatagram12Plus : public TlsConnectDatagram {
+  public:
+   TlsConnectDatagram12Plus() : TlsConnectDatagram() {}
+ };
+ 
+ // This simulates missing a window's worth of packets.
+ TEST_P(TlsConnectDatagram12Plus, MissAWindow) {
+   EnsureTlsSetup();
+@@ -860,10 +880,16 @@ TEST_P(TlsConnectDatagram12Plus, MissAWi
+   EXPECT_EQ(SECSuccess, SSLInt_AdvanceWriteSeqByAWindow(client_->ssl_fd(), 1));
+   SendReceive();
+ }
+ 
+ INSTANTIATE_TEST_CASE_P(Datagram12Plus, TlsConnectDatagram12Plus,
+                         TlsConnectTestBase::kTlsV12Plus);
+ INSTANTIATE_TEST_CASE_P(DatagramPre13, TlsConnectDatagramPre13,
+                         TlsConnectTestBase::kTlsV11V12);
++INSTANTIATE_TEST_CASE_P(DatagramDrop13, TlsDropDatagram13,
++                        ::testing::Values(true, false));
++INSTANTIATE_TEST_CASE_P(DatagramReorder13, TlsReorderDatagram13,
++                        ::testing::Values(true, false));
++INSTANTIATE_TEST_CASE_P(DatagramFragment13, TlsFragmentationAndRecoveryTest,
++                        ::testing::Values(true, false));
+ 
+ }  // namespace nss_test
+diff --git a/security/nss/gtests/ssl_gtest/ssl_fragment_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_fragment_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_fragment_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_fragment_unittest.cc
+@@ -15,34 +15,36 @@
+ #include "tls_filter.h"
+ #include "tls_parser.h"
+ 
+ namespace nss_test {
+ 
+ // This class cuts every unencrypted handshake record into two parts.
+ class RecordFragmenter : public PacketFilter {
+  public:
+-  RecordFragmenter() : sequence_number_(0), splitting_(true) {}
++  RecordFragmenter(bool is_dtls13)
++      : is_dtls13_(is_dtls13), sequence_number_(0), splitting_(true) {}
+ 
+  private:
+   class HandshakeSplitter {
+    public:
+-    HandshakeSplitter(const DataBuffer& input, DataBuffer* output,
+-                      uint64_t* sequence_number)
+-        : input_(input),
++    HandshakeSplitter(bool is_dtls13, const DataBuffer& input,
++                      DataBuffer* output, uint64_t* sequence_number)
++        : is_dtls13_(is_dtls13),
++          input_(input),
+           output_(output),
+           cursor_(0),
+           sequence_number_(sequence_number) {}
+ 
+    private:
+     void WriteRecord(TlsRecordHeader& record_header,
+                      DataBuffer& record_fragment) {
+-      TlsRecordHeader fragment_header(record_header.version(),
+-                                      record_header.content_type(),
+-                                      *sequence_number_);
++      TlsRecordHeader fragment_header(
++          record_header.variant(), record_header.version(),
++          record_header.content_type(), *sequence_number_);
+       ++*sequence_number_;
+       if (::g_ssl_gtest_verbose) {
+         std::cerr << "Fragment: " << fragment_header << ' ' << record_fragment
+                   << std::endl;
+       }
+       cursor_ = fragment_header.Write(output_, cursor_, record_fragment);
+     }
+ 
+@@ -83,17 +85,17 @@ class RecordFragmenter : public PacketFi
+     }
+ 
+    public:
+     bool Split() {
+       TlsParser parser(input_);
+       while (parser.remaining()) {
+         TlsRecordHeader header;
+         DataBuffer record;
+-        if (!header.Parse(0, &parser, &record)) {
++        if (!header.Parse(is_dtls13_, 0, &parser, &record)) {
+           ADD_FAILURE() << "bad record header";
+           return false;
+         }
+ 
+         if (::g_ssl_gtest_verbose) {
+           std::cerr << "Record: " << header << ' ' << record << std::endl;
+         }
+ 
+@@ -113,51 +115,55 @@ class RecordFragmenter : public PacketFi
+         if (!SplitRecord(header, record)) {
+           return false;
+         }
+       }
+       return true;
+     }
+ 
+    private:
++    bool is_dtls13_;
+     const DataBuffer& input_;
+     DataBuffer* output_;
+     size_t cursor_;
+     uint64_t* sequence_number_;
+   };
+ 
+  protected:
+   virtual PacketFilter::Action Filter(const DataBuffer& input,
+                                       DataBuffer* output) override {
+     if (!splitting_) {
+       return KEEP;
+     }
+ 
+     output->Allocate(input.len());
+-    HandshakeSplitter splitter(input, output, &sequence_number_);
++    HandshakeSplitter splitter(is_dtls13_, input, output, &sequence_number_);
+     if (!splitter.Split()) {
+       // If splitting fails, we obviously reached encrypted packets.
+       // Stop splitting from that point onward.
+       splitting_ = false;
+       return KEEP;
+     }
+ 
+     return CHANGE;
+   }
+ 
+  private:
++  bool is_dtls13_;
+   uint64_t sequence_number_;
+   bool splitting_;
+ };
+ 
+ TEST_P(TlsConnectDatagram, FragmentClientPackets) {
+-  client_->SetFilter(std::make_shared<RecordFragmenter>());
++  bool is_dtls13 = version_ >= SSL_LIBRARY_VERSION_TLS_1_3;
++  client_->SetFilter(std::make_shared<RecordFragmenter>(is_dtls13));
+   Connect();
+   SendReceive();
+ }
+ 
+ TEST_P(TlsConnectDatagram, FragmentServerPackets) {
+-  server_->SetFilter(std::make_shared<RecordFragmenter>());
++  bool is_dtls13 = version_ >= SSL_LIBRARY_VERSION_TLS_1_3;
++  server_->SetFilter(std::make_shared<RecordFragmenter>(is_dtls13));
+   Connect();
+   SendReceive();
+ }
+ 
+ }  // namespace nss_test
+diff --git a/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc
+@@ -76,18 +76,19 @@ class CorrectMessageSeqAfterHrrFilter : 
+   PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+                                     const DataBuffer& record, size_t* offset,
+                                     DataBuffer* output) {
+     if (filtered_packets() > 0 || header.content_type() != content_handshake) {
+       return KEEP;
+     }
+ 
+     DataBuffer buffer(record);
+-    TlsRecordHeader new_header = {header.version(), header.content_type(),
+-                                  header.sequence_number() + 1};
++    TlsRecordHeader new_header(header.variant(), header.version(),
++                               header.content_type(),
++                               header.sequence_number() + 1);
+ 
+     // Correct message_seq.
+     buffer.Write(4, 1U, 2);
+ 
+     *offset = new_header.Write(output, *offset, buffer);
+     return CHANGE;
+   }
+ };
+@@ -562,26 +563,49 @@ void TriggerHelloRetryRequest(std::share
+                                                       RetryHello, &cb_called));
+ 
+   // Start the handshake.
+   client->StartConnect();
+   server->StartConnect();
+   client->Handshake();
+   server->Handshake();
+   EXPECT_EQ(1U, cb_called);
++  // Stop the callback from being called in future handshakes.
++  EXPECT_EQ(SECSuccess,
++            SSL_HelloRetryRequestCallback(server->ssl_fd(), nullptr, nullptr));
++}
++
++TEST_P(TlsConnectTls13, VersionNumbersAfterRetry) {
++  ConfigureSelfEncrypt();
++  EnsureTlsSetup();
++  auto r = MakeTlsFilter<TlsRecordRecorder>(client_);
++  TriggerHelloRetryRequest(client_, server_);
++  Handshake();
++  ASSERT_GT(r->count(), 1UL);
++  auto ch1 = r->record(0);
++  if (ch1.header.is_dtls()) {
++    ASSERT_EQ(SSL_LIBRARY_VERSION_TLS_1_1, ch1.header.version());
++  } else {
++    ASSERT_EQ(SSL_LIBRARY_VERSION_TLS_1_0, ch1.header.version());
++  }
++  auto ch2 = r->record(1);
++  ASSERT_EQ(SSL_LIBRARY_VERSION_TLS_1_2, ch2.header.version());
++
++  CheckConnected();
+ }
+ 
+ TEST_P(TlsConnectTls13, RetryStateless) {
+   ConfigureSelfEncrypt();
+   EnsureTlsSetup();
+ 
+   TriggerHelloRetryRequest(client_, server_);
+   MakeNewServer();
+ 
+   Handshake();
++  CheckConnected();
+   SendReceive();
+ }
+ 
+ TEST_P(TlsConnectTls13, RetryStatefulDropCookie) {
+   ConfigureSelfEncrypt();
+   EnsureTlsSetup();
+ 
+   TriggerHelloRetryRequest(client_, server_);
+@@ -902,17 +926,20 @@ class HelloRetryRequestAgentTest : publi
+     DataBuffer hrr_data;
+     const uint8_t ssl_hello_retry_random[] = {
+         0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C,
+         0x02, 0x1E, 0x65, 0xB8, 0x91, 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB,
+         0x8C, 0x5E, 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C};
+ 
+     hrr_data.Allocate(len + 6);
+     size_t i = 0;
+-    i = hrr_data.Write(i, 0x0303, 2);
++    i = hrr_data.Write(i, variant_ == ssl_variant_datagram
++                              ? SSL_LIBRARY_VERSION_DTLS_1_2_WIRE
++                              : SSL_LIBRARY_VERSION_TLS_1_2,
++                       2);
+     i = hrr_data.Write(i, ssl_hello_retry_random,
+                        sizeof(ssl_hello_retry_random));
+     i = hrr_data.Write(i, static_cast<uint32_t>(0), 1);  // session_id
+     i = hrr_data.Write(i, TLS_AES_128_GCM_SHA256, 2);
+     i = hrr_data.Write(i, ssl_compression_null, 1);
+     // Add extensions.  First a length, which includes the supported version.
+     i = hrr_data.Write(i, static_cast<uint32_t>(len) + 6, 2);
+     // Now the supported version.
+diff --git a/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc
+@@ -378,17 +378,18 @@ class TlsPreCCSHeaderInjector : public T
+   virtual PacketFilter::Action FilterRecord(
+       const TlsRecordHeader& record_header, const DataBuffer& input,
+       size_t* offset, DataBuffer* output) override {
+     if (record_header.content_type() != kTlsChangeCipherSpecType) return KEEP;
+ 
+     std::cerr << "Injecting Finished header before CCS\n";
+     const uint8_t hhdr[] = {kTlsHandshakeFinished, 0x00, 0x00, 0x0c};
+     DataBuffer hhdr_buf(hhdr, sizeof(hhdr));
+-    TlsRecordHeader nhdr(record_header.version(), kTlsHandshakeType, 0);
++    TlsRecordHeader nhdr(record_header.variant(), record_header.version(),
++                         kTlsHandshakeType, 0);
+     *offset = nhdr.Write(output, *offset, hhdr_buf);
+     *offset = record_header.Write(output, *offset, input);
+     return CHANGE;
+   }
+ };
+ 
+ TEST_P(TlsConnectStreamPre13, ClientFinishedHeaderBeforeCCS) {
+   MakeTlsFilter<TlsPreCCSHeaderInjector>(client_);
+diff --git a/security/nss/gtests/ssl_gtest/ssl_record_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_record_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_record_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_record_unittest.cc
+@@ -163,16 +163,39 @@ TEST_F(TlsConnectStreamTls13, TooLargeRe
+   EXPECT_EQ(SSL_ERROR_RX_RECORD_TOO_LONG, PORT_GetError());
+ 
+   // Read the server alert.
+   rv = PR_Read(client_->ssl_fd(), buf, sizeof(buf));
+   EXPECT_GT(0, rv);
+   EXPECT_EQ(SSL_ERROR_RECORD_OVERFLOW_ALERT, PORT_GetError());
+ }
+ 
++class ShortHeaderChecker : public PacketFilter {
++ public:
++  PacketFilter::Action Filter(const DataBuffer& input, DataBuffer* output) {
++    // The first octet should be 0b001xxxxx.
++    EXPECT_EQ(1, input.data()[0] >> 5);
++    return KEEP;
++  }
++};
++
++TEST_F(TlsConnectDatagram13, ShortHeadersClient) {
++  Connect();
++  client_->SetOption(SSL_ENABLE_DTLS_SHORT_HEADER, PR_TRUE);
++  client_->SetFilter(std::make_shared<ShortHeaderChecker>());
++  SendReceive();
++}
++
++TEST_F(TlsConnectDatagram13, ShortHeadersServer) {
++  Connect();
++  server_->SetOption(SSL_ENABLE_DTLS_SHORT_HEADER, PR_TRUE);
++  server_->SetFilter(std::make_shared<ShortHeaderChecker>());
++  SendReceive();
++}
++
+ const static size_t kContentSizesArr[] = {
+     1, kMacSize - 1, kMacSize, 30, 31, 32, 36, 256, 257, 287, 288};
+ 
+ auto kContentSizes = ::testing::ValuesIn(kContentSizesArr);
+ const static bool kTrueFalseArr[] = {true, false};
+ auto kTrueFalse = ::testing::ValuesIn(kTrueFalseArr);
+ 
+ INSTANTIATE_TEST_CASE_P(TlsPadding, TlsPaddingTest,
+diff --git a/security/nss/gtests/ssl_gtest/tls_agent.cc b/security/nss/gtests/ssl_gtest/tls_agent.cc
+--- a/security/nss/gtests/ssl_gtest/tls_agent.cc
++++ b/security/nss/gtests/ssl_gtest/tls_agent.cc
+@@ -39,16 +39,26 @@ const std::string TlsAgent::kServerRsaPs
+ const std::string TlsAgent::kServerRsaDecrypt = "rsa_decrypt";
+ const std::string TlsAgent::kServerEcdsa256 = "ecdsa256";
+ const std::string TlsAgent::kServerEcdsa384 = "ecdsa384";
+ const std::string TlsAgent::kServerEcdsa521 = "ecdsa521";
+ const std::string TlsAgent::kServerEcdhRsa = "ecdh_rsa";
+ const std::string TlsAgent::kServerEcdhEcdsa = "ecdh_ecdsa";
+ const std::string TlsAgent::kServerDsa = "dsa";
+ 
++static const uint8_t kCannedTls13ServerHello[] = {
++    0x03, 0x03, 0x9c, 0xbc, 0x14, 0x9b, 0x0e, 0x2e, 0xfa, 0x0d, 0xf3,
++    0xf0, 0x5c, 0x70, 0x7a, 0xe0, 0xd1, 0x9b, 0x3e, 0x5a, 0x44, 0x6b,
++    0xdf, 0xe5, 0xc2, 0x28, 0x64, 0xf7, 0x00, 0xc1, 0x9c, 0x08, 0x76,
++    0x08, 0x00, 0x13, 0x01, 0x00, 0x00, 0x2e, 0x00, 0x33, 0x00, 0x24,
++    0x00, 0x1d, 0x00, 0x20, 0xc2, 0xcf, 0x23, 0x17, 0x64, 0x23, 0x03,
++    0xf0, 0xfb, 0x45, 0x98, 0x26, 0xd1, 0x65, 0x24, 0xa1, 0x6c, 0xa9,
++    0x80, 0x8f, 0x2c, 0xac, 0x0a, 0xea, 0x53, 0x3a, 0xcb, 0xe3, 0x08,
++    0x84, 0xae, 0x19, 0x00, 0x2b, 0x00, 0x02, 0x7f, kD13};
++
+ TlsAgent::TlsAgent(const std::string& nm, Role rl, SSLProtocolVariant var)
+     : name_(nm),
+       variant_(var),
+       role_(rl),
+       server_key_bits_(0),
+       adapter_(new DummyPrSocket(role_str(), var)),
+       ssl_fd_(nullptr),
+       state_(STATE_INIT),
+@@ -942,22 +952,23 @@ void TlsAgent::SendBuffer(const DataBuff
+     error_code_ = PR_GetError();
+     expect_readwrite_error_ = false;
+   } else {
+     ASSERT_EQ(buf.len(), static_cast<size_t>(rv));
+   }
+ }
+ 
+ bool TlsAgent::SendEncryptedRecord(const std::shared_ptr<TlsCipherSpec>& spec,
+-                                   uint16_t wireVersion, uint64_t seq,
+-                                   uint8_t ct, const DataBuffer& buf) {
+-  LOGV("Writing " << buf.len() << " bytes");
+-  // Ensure we are a TLS 1.3 cipher agent.
++                                   uint64_t seq, uint8_t ct,
++                                   const DataBuffer& buf) {
++  LOGV("Encrypting " << buf.len() << " bytes");
++  // Ensure that we are doing TLS 1.3.
+   EXPECT_GE(expected_version_, SSL_LIBRARY_VERSION_TLS_1_3);
+-  TlsRecordHeader header(wireVersion, kTlsApplicationDataType, seq);
++  TlsRecordHeader header(variant_, expected_version_, kTlsApplicationDataType,
++                         seq);
+   DataBuffer padded = buf;
+   padded.Write(padded.len(), ct, 1);
+   DataBuffer ciphertext;
+   if (!spec->Protect(header, padded, &ciphertext)) {
+     return false;
+   }
+ 
+   DataBuffer record;
+@@ -1069,25 +1080,30 @@ void TlsAgentTestBase::ProcessMessage(co
+   if (expected_state == TlsAgent::STATE_ERROR) {
+     ASSERT_EQ(error_code, agent_->error_code());
+   }
+ }
+ 
+ void TlsAgentTestBase::MakeRecord(SSLProtocolVariant variant, uint8_t type,
+                                   uint16_t version, const uint8_t* buf,
+                                   size_t len, DataBuffer* out,
+-                                  uint64_t seq_num) {
++                                  uint64_t sequence_number) {
+   size_t index = 0;
+   index = out->Write(index, type, 1);
+   if (variant == ssl_variant_stream) {
+     index = out->Write(index, version, 2);
++  } else if (version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
++             type == kTlsApplicationDataType) {
++    uint32_t epoch = (sequence_number >> 48) & 0x3;
++    uint32_t seqno = sequence_number & ((1ULL << 30) - 1);
++    index = out->Write(index, (epoch << 30) | seqno, 4);
+   } else {
+     index = out->Write(index, TlsVersionToDtlsVersion(version), 2);
+-    index = out->Write(index, seq_num >> 32, 4);
+-    index = out->Write(index, seq_num & PR_UINT32_MAX, 4);
++    index = out->Write(index, sequence_number >> 32, 4);
++    index = out->Write(index, sequence_number & PR_UINT32_MAX, 4);
+   }
+   index = out->Write(index, len, 2);
+   out->Write(index, buf, len);
+ }
+ 
+ void TlsAgentTestBase::MakeRecord(uint8_t type, uint16_t version,
+                                   const uint8_t* buf, size_t len,
+                                   DataBuffer* out, uint64_t seq_num) const {
+@@ -1135,9 +1151,17 @@ void TlsAgentTestBase::MakeTrivialHandsh
+ 
+   index = out->Write(index, hs_type, 1);  // Handshake record type.
+   index = out->Write(index, hs_len, 3);   // Handshake length
+   for (size_t i = 0; i < hs_len; ++i) {
+     index = out->Write(index, 1, 1);
+   }
+ }
+ 
++DataBuffer TlsAgentTestBase::MakeCannedTls13ServerHello() {
++  DataBuffer sh(kCannedTls13ServerHello, sizeof(kCannedTls13ServerHello));
++  if (variant_ == ssl_variant_datagram) {
++    sh.Write(0, SSL_LIBRARY_VERSION_DTLS_1_2_WIRE, 2);
++  }
++  return sh;
++}
++
+ }  // namespace nss_test
+diff --git a/security/nss/gtests/ssl_gtest/tls_agent.h b/security/nss/gtests/ssl_gtest/tls_agent.h
+--- a/security/nss/gtests/ssl_gtest/tls_agent.h
++++ b/security/nss/gtests/ssl_gtest/tls_agent.h
+@@ -5,16 +5,19 @@
+  * You can obtain one at http://mozilla.org/MPL/2.0/. */
+ 
+ #ifndef tls_agent_h_
+ #define tls_agent_h_
+ 
+ #include "prio.h"
+ #include "ssl.h"
+ 
++// This is an internal header, used to get TLS_1_3_DRAFT_VERSION.
++#include "ssl3prot.h"
++
+ #include <functional>
+ #include <iostream>
+ 
+ #include "test_io.h"
+ 
+ #define GTEST_HAS_RTTI 0
+ #include "gtest/gtest.h"
+ #include "scoped_ptrs.h"
+@@ -52,16 +55,18 @@ typedef std::function<SECStatus(TlsAgent
+     AuthCertificateCallbackFunction;
+ 
+ typedef std::function<void(TlsAgent* agent)> HandshakeCallbackFunction;
+ 
+ typedef std::function<int32_t(TlsAgent* agent, const SECItem* srvNameArr,
+                               PRUint32 srvNameArrSize)>
+     SniCallbackFunction;
+ 
++static const uint8_t kD13 = TLS_1_3_DRAFT_VERSION;
++
+ class TlsAgent : public PollTarget {
+  public:
+   enum Role { CLIENT, SERVER };
+   enum State { STATE_INIT, STATE_CONNECTING, STATE_CONNECTED, STATE_ERROR };
+ 
+   static const std::string kClient;     // the client key is sign only
+   static const std::string kRsa2048;    // bigger sign and encrypt for either
+   static const std::string kServerRsa;  // both sign and encrypt
+@@ -138,18 +143,17 @@ class TlsAgent : public PollTarget {
+   void EnableSrtp();
+   void CheckSrtp() const;
+   void CheckErrorCode(int32_t expected) const;
+   void WaitForErrorCode(int32_t expected, uint32_t delay) const;
+   // Send data on the socket, encrypting it.
+   void SendData(size_t bytes, size_t blocksize = 1024);
+   void SendBuffer(const DataBuffer& buf);
+   bool SendEncryptedRecord(const std::shared_ptr<TlsCipherSpec>& spec,
+-                           uint16_t wireVersion, uint64_t seq, uint8_t ct,
+-                           const DataBuffer& buf);
++                           uint64_t seq, uint8_t ct, const DataBuffer& buf);
+   // Send data directly to the underlying socket, skipping the TLS layer.
+   void SendDirect(const DataBuffer& buf);
+   void SendRecordDirect(const TlsRecord& record);
+   void ReadBytes(size_t max = 16384U);
+   void ResetSentBytes();  // Hack to test drops.
+   void EnableExtendedMasterSecret();
+   void CheckExtendedMasterSecret(bool expected);
+   void CheckEarlyDataAccepted(bool expected);
+@@ -438,16 +442,17 @@ class TlsAgentTestBase : public ::testin
+   void MakeRecord(uint8_t type, uint16_t version, const uint8_t* buf,
+                   size_t len, DataBuffer* out, uint64_t seq_num = 0) const;
+   void MakeHandshakeMessage(uint8_t hs_type, const uint8_t* data, size_t hs_len,
+                             DataBuffer* out, uint64_t seq_num = 0) const;
+   void MakeHandshakeMessageFragment(uint8_t hs_type, const uint8_t* data,
+                                     size_t hs_len, DataBuffer* out,
+                                     uint64_t seq_num, uint32_t fragment_offset,
+                                     uint32_t fragment_length) const;
++  DataBuffer MakeCannedTls13ServerHello();
+   static void MakeTrivialHandshakeRecord(uint8_t hs_type, size_t hs_len,
+                                          DataBuffer* out);
+   static inline TlsAgent::Role ToRole(const std::string& str) {
+     return str == "CLIENT" ? TlsAgent::CLIENT : TlsAgent::SERVER;
+   }
+ 
+   void Init(const std::string& server_name = TlsAgent::kServerRsa);
+   void Reset(const std::string& server_name = TlsAgent::kServerRsa);
+diff --git a/security/nss/gtests/ssl_gtest/tls_filter.cc b/security/nss/gtests/ssl_gtest/tls_filter.cc
+--- a/security/nss/gtests/ssl_gtest/tls_filter.cc
++++ b/security/nss/gtests/ssl_gtest/tls_filter.cc
+@@ -25,21 +25,19 @@ void TlsVersioned::WriteStream(std::ostr
+   stream << (is_dtls() ? "DTLS " : "TLS ");
+   switch (version()) {
+     case 0:
+       stream << "(no version)";
+       break;
+     case SSL_LIBRARY_VERSION_TLS_1_0:
+       stream << "1.0";
+       break;
+-    case SSL_LIBRARY_VERSION_DTLS_1_0_WIRE:
+     case SSL_LIBRARY_VERSION_TLS_1_1:
+       stream << (is_dtls() ? "1.0" : "1.1");
+       break;
+-    case SSL_LIBRARY_VERSION_DTLS_1_2_WIRE:
+     case SSL_LIBRARY_VERSION_TLS_1_2:
+       stream << "1.2";
+       break;
+     case SSL_LIBRARY_VERSION_TLS_1_3:
+       stream << "1.3";
+       break;
+     default:
+       stream << "Invalid version: " << version();
+@@ -62,53 +60,85 @@ void TlsRecordFilter::CipherSpecChanged(
+               << (sending ? "send" : "receive")
+               << " cipher spec changed:  " << newSpec->epoch << " ("
+               << newSpec->phase << ")" << std::endl;
+   }
+   if (!sending) {
+     return;
+   }
+ 
+-  self->in_sequence_number_ = 0;
+-  self->out_sequence_number_ = 0;
++  uint64_t seq_no;
++  if (self->agent()->variant() == ssl_variant_datagram) {
++    seq_no = static_cast<uint64_t>(SSLInt_CipherSpecToEpoch(newSpec)) << 48;
++  } else {
++    seq_no = 0;
++  }
++  self->in_sequence_number_ = seq_no;
++  self->out_sequence_number_ = seq_no;
+   self->dropped_record_ = false;
+   self->cipher_spec_.reset(new TlsCipherSpec());
+   bool ret = self->cipher_spec_->Init(
+       SSLInt_CipherSpecToEpoch(newSpec), SSLInt_CipherSpecToAlgorithm(newSpec),
+       SSLInt_CipherSpecToKey(newSpec), SSLInt_CipherSpecToIv(newSpec));
+   EXPECT_EQ(true, ret);
+ }
+ 
++bool TlsRecordFilter::is_dtls13() const {
++  if (agent()->variant() != ssl_variant_datagram) {
++    return false;
++  }
++  if (agent()->state() == TlsAgent::STATE_CONNECTED) {
++    return agent()->version() >= SSL_LIBRARY_VERSION_TLS_1_3;
++  }
++  SSLPreliminaryChannelInfo info;
++  EXPECT_EQ(SECSuccess, SSL_GetPreliminaryChannelInfo(agent()->ssl_fd(), &info,
++                                                      sizeof(info)));
++  return (info.protocolVersion >= SSL_LIBRARY_VERSION_TLS_1_3) ||
++         info.canSendEarlyData;
++}
++
+ PacketFilter::Action TlsRecordFilter::Filter(const DataBuffer& input,
+                                              DataBuffer* output) {
++  // Disable during shutdown.
++  if (!agent()) {
++    return KEEP;
++  }
++
+   bool changed = false;
+   size_t offset = 0U;
++
+   output->Allocate(input.len());
+-
+   TlsParser parser(input);
+ 
+   while (parser.remaining()) {
+     TlsRecordHeader header;
+     DataBuffer record;
+ 
+-    if (!header.Parse(in_sequence_number_, &parser, &record)) {
++    if (!header.Parse(is_dtls13(), in_sequence_number_, &parser, &record)) {
+       ADD_FAILURE() << "not a valid record";
+       return KEEP;
+     }
+ 
+-    // Track the sequence number, which is necessary for stream mode (the
+-    // sequence number is in the header for datagram).
++    // Track the sequence number, which is necessary for stream mode when
++    // decrypting and for TLS 1.3 datagram to recover the sequence number.
+     //
+-    // This isn't perfectly robust.  If there is a change from an active cipher
++    // We reset the counter when the cipher spec changes, but that notification
++    // appears before a record is sent.  If multiple records are sent with
++    // different cipher specs, this would fail.  This filters out cleartext
++    // records, so we don't get confused by handshake messages that are sent at
++    // the same time as encrypted records.  Sequence numbers are therefore
++    // likely to be incorrect for cleartext records.
++    //
++    // This isn't perfectly robust: if there is a change from an active cipher
+     // spec to another active cipher spec (KeyUpdate for instance) AND writes
+-    // are consolidated across that change AND packets were dropped from the
+-    // older epoch, we will not correctly re-encrypt records in the old epoch to
+-    // update their sequence numbers.
+-    if (cipher_spec_ && header.content_type() == kTlsApplicationDataType) {
+-      ++in_sequence_number_;
++    // are consolidated across that change, this code could use the wrong
++    // sequence numbers when re-encrypting records with the old keys.
++    if (header.content_type() == kTlsApplicationDataType) {
++      in_sequence_number_ =
++          (std::max)(in_sequence_number_, header.sequence_number() + 1);
+     }
+ 
+     if (FilterRecord(header, record, &offset, output) != KEEP) {
+       changed = true;
+     } else {
+       offset = header.Write(output, offset, record);
+     }
+   }
+@@ -126,21 +156,24 @@ PacketFilter::Action TlsRecordFilter::Fi
+ PacketFilter::Action TlsRecordFilter::FilterRecord(
+     const TlsRecordHeader& header, const DataBuffer& record, size_t* offset,
+     DataBuffer* output) {
+   DataBuffer filtered;
+   uint8_t inner_content_type;
+   DataBuffer plaintext;
+ 
+   if (!Unprotect(header, record, &inner_content_type, &plaintext)) {
++    if (g_ssl_gtest_verbose) {
++      std::cerr << "unprotect failed: " << header << ":" << record << std::endl;
++    }
+     return KEEP;
+   }
+ 
+-  TlsRecordHeader real_header = {header.version(), inner_content_type,
+-                                 header.sequence_number()};
++  TlsRecordHeader real_header(header.variant(), header.version(),
++                              inner_content_type, header.sequence_number());
+ 
+   PacketFilter::Action action = FilterRecord(real_header, plaintext, &filtered);
+   // In stream mode, even if something doesn't change we need to re-encrypt if
+   // previous packets were dropped.
+   if (action == KEEP) {
+     if (header.is_dtls() || !dropped_record_) {
+       return KEEP;
+     }
+@@ -161,68 +194,186 @@ PacketFilter::Action TlsRecordFilter::Fi
+ 
+   uint64_t seq_num;
+   if (header.is_dtls() || !cipher_spec_ ||
+       header.content_type() != kTlsApplicationDataType) {
+     seq_num = header.sequence_number();
+   } else {
+     seq_num = out_sequence_number_++;
+   }
+-  TlsRecordHeader out_header = {header.version(), header.content_type(),
+-                                seq_num};
++  TlsRecordHeader out_header(header.variant(), header.version(),
++                             header.content_type(), seq_num);
+ 
+   DataBuffer ciphertext;
+   bool rv = Protect(out_header, inner_content_type, filtered, &ciphertext);
+   EXPECT_TRUE(rv);
+   if (!rv) {
+     return KEEP;
+   }
+   *offset = out_header.Write(output, *offset, ciphertext);
+   return CHANGE;
+ }
+ 
+-bool TlsRecordHeader::Parse(uint64_t seqno, TlsParser* parser,
++size_t TlsRecordHeader::header_length() const {
++  // If we have a header, return it's length.
++  if (header_.len()) {
++    return header_.len();
++  }
++
++  // Otherwise make a dummy header and return the length.
++  DataBuffer buf;
++  return WriteHeader(&buf, 0, 0);
++}
++
++uint64_t TlsRecordHeader::RecoverSequenceNumber(uint64_t expected,
++                                                uint32_t partial,
++                                                size_t partial_bits) {
++  EXPECT_GE(32U, partial_bits);
++  uint64_t mask = (1 << partial_bits) - 1;
++  // First we determine the highest possible value.  This is half the
++  // expressible range above the expected value.
++  uint64_t cap = expected + (1ULL << (partial_bits - 1));
++  // Add the partial piece in.  e.g., xxxx789a and 1234 becomes xxxx1234.
++  uint64_t seq_no = (cap & ~mask) | partial;
++  // If the partial value is higher than the same partial piece from the cap,
++  // then the real value has to be lower.  e.g., xxxx1234 can't become xxxx5678.
++  if (partial > (cap & mask)) {
++    seq_no -= 1ULL << partial_bits;
++  }
++  return seq_no;
++}
++
++// Determine the full epoch and sequence number from an expected and raw value.
++// The expected and output values are packed as they are in DTLS 1.2 and
++// earlier: with 16 bits of epoch and 48 bits of sequence number.
++uint64_t TlsRecordHeader::ParseSequenceNumber(uint64_t expected, uint32_t raw,
++                                              size_t seq_no_bits,
++                                              size_t epoch_bits) {
++  uint64_t epoch_mask = (1ULL << epoch_bits) - 1;
++  uint64_t epoch = RecoverSequenceNumber(
++      expected >> 48, (raw >> seq_no_bits) & epoch_mask, epoch_bits);
++  if (epoch > (expected >> 48)) {
++    // If the epoch has changed, reset the expected sequence number.
++    expected = 0;
++  } else {
++    // Otherwise, retain just the sequence number part.
++    expected &= (1ULL << 48) - 1;
++  }
++  uint64_t seq_no_mask = (1ULL << seq_no_bits) - 1;
++  uint64_t seq_no =
++      RecoverSequenceNumber(expected, raw & seq_no_mask, seq_no_bits);
++  return (epoch << 48) | seq_no;
++}
++
++bool TlsRecordHeader::Parse(bool is_dtls13, uint64_t seqno, TlsParser* parser,
+                             DataBuffer* body) {
++  auto mark = parser->consumed();
++
+   if (!parser->Read(&content_type_)) {
+     return false;
+   }
+ 
++  if (is_dtls13) {
++    variant_ = ssl_variant_datagram;
++    version_ = SSL_LIBRARY_VERSION_TLS_1_3;
++
++#ifndef UNSAFE_FUZZER_MODE
++    // Deal with the 7 octet header.
++    if (content_type_ == kTlsApplicationDataType) {
++      uint32_t tmp;
++      if (!parser->Read(&tmp, 4)) {
++        return false;
++      }
++      sequence_number_ = ParseSequenceNumber(seqno, tmp, 30, 2);
++      if (!parser->ReadFromMark(&header_, parser->consumed() + 2 - mark,
++                                mark)) {
++        return false;
++      }
++      return parser->ReadVariable(body, 2);
++    }
++
++    // The short, 2 octet header.
++    if ((content_type_ & 0xe0) == 0x20) {
++      uint32_t tmp;
++      if (!parser->Read(&tmp, 1)) {
++        return false;
++      }
++      // Need to use the low 5 bits of the first octet too.
++      tmp |= (content_type_ & 0x1f) << 8;
++      content_type_ = kTlsApplicationDataType;
++      sequence_number_ = ParseSequenceNumber(seqno, tmp, 12, 1);
++
++      if (!parser->ReadFromMark(&header_, parser->consumed() - mark, mark)) {
++        return false;
++      }
++      return parser->Read(body, parser->remaining());
++    }
++
++    // The full 13 octet header can only be used for a few types.
++    EXPECT_TRUE(content_type_ == kTlsAlertType ||
++                content_type_ == kTlsHandshakeType ||
++                content_type_ == kTlsAckType);
++#endif
++  }
++
+   uint32_t ver;
+   if (!parser->Read(&ver, 2)) {
+     return false;
+   }
+-  version_ = ver;
++  if (!is_dtls13) {
++    variant_ = IsDtls(ver) ? ssl_variant_datagram : ssl_variant_stream;
++  }
++  version_ = NormalizeTlsVersion(ver);
+ 
+-  // If this is DTLS, overwrite the sequence number.
+-  if (IsDtls(ver)) {
++  if (is_dtls()) {
++    // If this is DTLS, read the sequence number.
+     uint32_t tmp;
+     if (!parser->Read(&tmp, 4)) {
+       return false;
+     }
+     sequence_number_ = static_cast<uint64_t>(tmp) << 32;
+     if (!parser->Read(&tmp, 4)) {
+       return false;
+     }
+     sequence_number_ |= static_cast<uint64_t>(tmp);
+   } else {
+     sequence_number_ = seqno;
+   }
++  if (!parser->ReadFromMark(&header_, parser->consumed() + 2 - mark, mark)) {
++    return false;
++  }
+   return parser->ReadVariable(body, 2);
+ }
+ 
++size_t TlsRecordHeader::WriteHeader(DataBuffer* buffer, size_t offset,
++                                    size_t body_len) const {
++  offset = buffer->Write(offset, content_type_, 1);
++  if (is_dtls() && version_ >= SSL_LIBRARY_VERSION_TLS_1_3 &&
++      content_type() == kTlsApplicationDataType) {
++    // application_data records in TLS 1.3 have a different header format.
++    // Always use the long header here for simplicity.
++    uint32_t e = (sequence_number_ >> 48) & 0x3;
++    uint32_t seqno = sequence_number_ & ((1ULL << 30) - 1);
++    offset = buffer->Write(offset, (e << 30) | seqno, 4);
++  } else {
++    uint16_t v = is_dtls() ? TlsVersionToDtlsVersion(version_) : version_;
++    offset = buffer->Write(offset, v, 2);
++    if (is_dtls()) {
++      // write epoch (2 octet), and seqnum (6 octet)
++      offset = buffer->Write(offset, sequence_number_ >> 32, 4);
++      offset = buffer->Write(offset, sequence_number_ & 0xffffffff, 4);
++    }
++  }
++  offset = buffer->Write(offset, body_len, 2);
++  return offset;
++}
++
+ size_t TlsRecordHeader::Write(DataBuffer* buffer, size_t offset,
+                               const DataBuffer& body) const {
+-  offset = buffer->Write(offset, content_type_, 1);
+-  offset = buffer->Write(offset, version_, 2);
+-  if (is_dtls()) {
+-    // write epoch (2 octet), and seqnum (6 octet)
+-    offset = buffer->Write(offset, sequence_number_ >> 32, 4);
+-    offset = buffer->Write(offset, sequence_number_ & 0xffffffff, 4);
+-  }
+-  offset = buffer->Write(offset, body.len(), 2);
++  offset = WriteHeader(buffer, offset, body.len());
+   offset = buffer->Write(offset, body);
+   return offset;
+ }
+ 
+ bool TlsRecordFilter::Unprotect(const TlsRecordHeader& header,
+                                 const DataBuffer& ciphertext,
+                                 uint8_t* inner_content_type,
+                                 DataBuffer* plaintext) {
+@@ -401,16 +552,17 @@ bool TlsHandshakeFilter::HandshakeHeader
+   return true;
+ }
+ 
+ bool TlsHandshakeFilter::HandshakeHeader::Parse(
+     TlsParser* parser, const TlsRecordHeader& record_header,
+     const DataBuffer& preceding_fragment, DataBuffer* body, bool* complete) {
+   *complete = false;
+ 
++  variant_ = record_header.variant();
+   version_ = record_header.version();
+   if (!parser->Read(&handshake_type_)) {
+     return false;  // malformed
+   }
+ 
+   uint32_t length;
+   if (!ReadLength(parser, record_header, preceding_fragment.len(), &length,
+                   complete)) {
+diff --git a/security/nss/gtests/ssl_gtest/tls_filter.h b/security/nss/gtests/ssl_gtest/tls_filter.h
+--- a/security/nss/gtests/ssl_gtest/tls_filter.h
++++ b/security/nss/gtests/ssl_gtest/tls_filter.h
+@@ -6,66 +6,83 @@
+ 
+ #ifndef tls_filter_h_
+ #define tls_filter_h_
+ 
+ #include <functional>
+ #include <memory>
+ #include <set>
+ #include <vector>
+-
++#include "sslt.h"
+ #include "test_io.h"
+ #include "tls_agent.h"
+ #include "tls_parser.h"
+ #include "tls_protect.h"
+ 
+ extern "C" {
+ #include "libssl_internals.h"
+ }
+ 
+ namespace nss_test {
+ 
+ class TlsCipherSpec;
+ 
+ class TlsVersioned {
+  public:
+-  TlsVersioned() : version_(0) {}
+-  explicit TlsVersioned(uint16_t v) : version_(v) {}
++  TlsVersioned() : variant_(ssl_variant_stream), version_(0) {}
++  TlsVersioned(SSLProtocolVariant var, uint16_t ver)
++      : variant_(var), version_(ver) {}
+ 
+-  bool is_dtls() const { return IsDtls(version_); }
++  bool is_dtls() const { return variant_ == ssl_variant_datagram; }
++  SSLProtocolVariant variant() const { return variant_; }
+   uint16_t version() const { return version_; }
+ 
+   void WriteStream(std::ostream& stream) const;
+ 
+  protected:
++  SSLProtocolVariant variant_;
+   uint16_t version_;
+ };
+ 
+ class TlsRecordHeader : public TlsVersioned {
+  public:
+-  TlsRecordHeader() : TlsVersioned(), content_type_(0), sequence_number_(0) {}
+-  TlsRecordHeader(uint16_t ver, uint8_t ct, uint64_t seqno)
+-      : TlsVersioned(ver), content_type_(ct), sequence_number_(seqno) {}
++  TlsRecordHeader()
++      : TlsVersioned(), content_type_(0), sequence_number_(0), header_() {}
++  TlsRecordHeader(SSLProtocolVariant var, uint16_t ver, uint8_t ct,
++                  uint64_t seqno)
++      : TlsVersioned(var, ver),
++        content_type_(ct),
++        sequence_number_(seqno),
++        header_() {}
+ 
+   uint8_t content_type() const { return content_type_; }
+   uint64_t sequence_number() const { return sequence_number_; }
+   uint16_t epoch() const {
+     return static_cast<uint16_t>(sequence_number_ >> 48);
+   }
+-  size_t header_length() const { return is_dtls() ? 13 : 5; }
++  size_t header_length() const;
++  const DataBuffer& header() const { return header_; }
+ 
+   // Parse the header; return true if successful; body in an outparam if OK.
+-  bool Parse(uint64_t sequence_number, TlsParser* parser, DataBuffer* body);
++  bool Parse(bool is_dtls13, uint64_t sequence_number, TlsParser* parser,
++             DataBuffer* body);
+   // Write the header and body to a buffer at the given offset.
+   // Return the offset of the end of the write.
+   size_t Write(DataBuffer* buffer, size_t offset, const DataBuffer& body) const;
++  size_t WriteHeader(DataBuffer* buffer, size_t offset, size_t body_len) const;
+ 
+  private:
++  static uint64_t RecoverSequenceNumber(uint64_t expected, uint32_t partial,
++                                        size_t partial_bits);
++  static uint64_t ParseSequenceNumber(uint64_t expected, uint32_t raw,
++                                      size_t seq_no_bits, size_t epoch_bits);
++
+   uint8_t content_type_;
+   uint64_t sequence_number_;
++  DataBuffer header_;
+ };
+ 
+ struct TlsRecord {
+   const TlsRecordHeader header;
+   const DataBuffer buffer;
+ };
+ 
+ // Make a filter and install it on a TlsAgent.
+@@ -122,16 +139,18 @@ class TlsRecordFilter : public PacketFil
+   // It returns an action (KEEP, CHANGE, DROP).  It writes to the `changed`
+   // outparam with the new record contents if it chooses to CHANGE the record.
+   virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+                                             const DataBuffer& data,
+                                             DataBuffer* changed) {
+     return KEEP;
+   }
+ 
++  bool is_dtls13() const;
++
+  private:
+   static void CipherSpecChanged(void* arg, PRBool sending,
+                                 ssl3CipherSpec* newSpec);
+ 
+   std::weak_ptr<TlsAgent> agent_;
+   size_t count_;
+   std::unique_ptr<TlsCipherSpec> cipher_spec_;
+   // Whether we dropped a record since the cipher spec changed.
+diff --git a/security/nss/gtests/ssl_gtest/tls_protect.cc b/security/nss/gtests/ssl_gtest/tls_protect.cc
+--- a/security/nss/gtests/ssl_gtest/tls_protect.cc
++++ b/security/nss/gtests/ssl_gtest/tls_protect.cc
+@@ -49,46 +49,47 @@ bool AeadCipher::AeadInner(bool decrypt,
+   } else {
+     rv = PK11_Encrypt(key_, mech_, &param, out, &uoutlen, maxlen, in, inlen);
+   }
+   *outlen = (int)uoutlen;
+ 
+   return rv == SECSuccess;
+ }
+ 
+-bool AeadCipherAesGcm::Aead(bool decrypt, uint64_t seq, const uint8_t *in,
+-                            size_t inlen, uint8_t *out, size_t *outlen,
+-                            size_t maxlen) {
++bool AeadCipherAesGcm::Aead(bool decrypt, const uint8_t *hdr, size_t hdr_len,
++                            uint64_t seq, const uint8_t *in, size_t inlen,
++                            uint8_t *out, size_t *outlen, size_t maxlen) {
+   CK_GCM_PARAMS aeadParams;
+   unsigned char nonce[12];
+ 
+   memset(&aeadParams, 0, sizeof(aeadParams));
+   aeadParams.pIv = nonce;
+   aeadParams.ulIvLen = sizeof(nonce);
+-  aeadParams.pAAD = NULL;
+-  aeadParams.ulAADLen = 0;
++  aeadParams.pAAD = const_cast<uint8_t *>(hdr);
++  aeadParams.ulAADLen = hdr_len;
+   aeadParams.ulTagBits = 128;
+ 
+   FormatNonce(seq, nonce);
+   return AeadInner(decrypt, (unsigned char *)&aeadParams, sizeof(aeadParams),
+                    in, inlen, out, outlen, maxlen);
+ }
+ 
+-bool AeadCipherChacha20Poly1305::Aead(bool decrypt, uint64_t seq,
++bool AeadCipherChacha20Poly1305::Aead(bool decrypt, const uint8_t *hdr,
++                                      size_t hdr_len, uint64_t seq,
+                                       const uint8_t *in, size_t inlen,
+                                       uint8_t *out, size_t *outlen,
+                                       size_t maxlen) {
+   CK_NSS_AEAD_PARAMS aeadParams;
+   unsigned char nonce[12];
+ 
+   memset(&aeadParams, 0, sizeof(aeadParams));
+   aeadParams.pNonce = nonce;
+   aeadParams.ulNonceLen = sizeof(nonce);
+-  aeadParams.pAAD = NULL;
+-  aeadParams.ulAADLen = 0;
++  aeadParams.pAAD = const_cast<uint8_t *>(hdr);
++  aeadParams.ulAADLen = hdr_len;
+   aeadParams.ulTagLen = 16;
+ 
+   FormatNonce(seq, nonce);
+   return AeadInner(decrypt, (unsigned char *)&aeadParams, sizeof(aeadParams),
+                    in, inlen, out, outlen, maxlen);
+ }
+ 
+ bool TlsCipherSpec::Init(uint16_t epoc, SSLCipherAlgorithm cipher,
+@@ -109,37 +110,43 @@ bool TlsCipherSpec::Init(uint16_t epoc, 
+ }
+ 
+ bool TlsCipherSpec::Unprotect(const TlsRecordHeader &header,
+                               const DataBuffer &ciphertext,
+                               DataBuffer *plaintext) {
+   // Make space.
+   plaintext->Allocate(ciphertext.len());
+ 
++  auto header_bytes = header.header();
+   size_t len;
+   bool ret =
+-      aead_->Aead(true, header.sequence_number(), ciphertext.data(),
+-                  ciphertext.len(), plaintext->data(), &len, plaintext->len());
++      aead_->Aead(true, header_bytes.data(), header_bytes.len(),
++                  header.sequence_number(), ciphertext.data(), ciphertext.len(),
++                  plaintext->data(), &len, plaintext->len());
+   if (!ret) return false;
+ 
+   plaintext->Truncate(len);
+ 
+   return true;
+ }
+ 
+ bool TlsCipherSpec::Protect(const TlsRecordHeader &header,
+                             const DataBuffer &plaintext,
+                             DataBuffer *ciphertext) {
+   // Make a padded buffer.
+ 
+   ciphertext->Allocate(plaintext.len() +
+                        32);  // Room for any plausible auth tag
+   size_t len;
++
++  DataBuffer header_bytes;
++  (void)header.WriteHeader(&header_bytes, 0, plaintext.len() + 16);
+   bool ret =
+-      aead_->Aead(false, header.sequence_number(), plaintext.data(),
+-                  plaintext.len(), ciphertext->data(), &len, ciphertext->len());
++      aead_->Aead(false, header_bytes.data(), header_bytes.len(),
++                  header.sequence_number(), plaintext.data(), plaintext.len(),
++                  ciphertext->data(), &len, ciphertext->len());
+   if (!ret) return false;
+   ciphertext->Truncate(len);
+ 
+   return true;
+ }
+ 
+ }  // namespace nss_test
+diff --git a/security/nss/gtests/ssl_gtest/tls_protect.h b/security/nss/gtests/ssl_gtest/tls_protect.h
+--- a/security/nss/gtests/ssl_gtest/tls_protect.h
++++ b/security/nss/gtests/ssl_gtest/tls_protect.h
+@@ -18,18 +18,19 @@ namespace nss_test {
+ class TlsRecordHeader;
+ 
+ class AeadCipher {
+  public:
+   AeadCipher(CK_MECHANISM_TYPE mech) : mech_(mech), key_(nullptr) {}
+   virtual ~AeadCipher();
+ 
+   bool Init(PK11SymKey *key, const uint8_t *iv);
+-  virtual bool Aead(bool decrypt, uint64_t seq, const uint8_t *in, size_t inlen,
+-                    uint8_t *out, size_t *outlen, size_t maxlen) = 0;
++  virtual bool Aead(bool decrypt, const uint8_t *hdr, size_t hdr_len,
++                    uint64_t seq, const uint8_t *in, size_t inlen, uint8_t *out,
++                    size_t *outlen, size_t maxlen) = 0;
+ 
+  protected:
+   void FormatNonce(uint64_t seq, uint8_t *nonce);
+   bool AeadInner(bool decrypt, void *params, size_t param_length,
+                  const uint8_t *in, size_t inlen, uint8_t *out, size_t *outlen,
+                  size_t maxlen);
+ 
+   CK_MECHANISM_TYPE mech_;
+@@ -37,27 +38,29 @@ class AeadCipher {
+   uint8_t iv_[12];
+ };
+ 
+ class AeadCipherChacha20Poly1305 : public AeadCipher {
+  public:
+   AeadCipherChacha20Poly1305() : AeadCipher(CKM_NSS_CHACHA20_POLY1305) {}
+ 
+  protected:
+-  bool Aead(bool decrypt, uint64_t seq, const uint8_t *in, size_t inlen,
+-            uint8_t *out, size_t *outlen, size_t maxlen);
++  bool Aead(bool decrypt, const uint8_t *hdr, size_t hdr_len, uint64_t seq,
++            const uint8_t *in, size_t inlen, uint8_t *out, size_t *outlen,
++            size_t maxlen);
+ };
+ 
+ class AeadCipherAesGcm : public AeadCipher {
+  public:
+   AeadCipherAesGcm() : AeadCipher(CKM_AES_GCM) {}
+ 
+  protected:
+-  bool Aead(bool decrypt, uint64_t seq, const uint8_t *in, size_t inlen,
+-            uint8_t *out, size_t *outlen, size_t maxlen);
++  bool Aead(bool decrypt, const uint8_t *hdr, size_t hdr_len, uint64_t seq,
++            const uint8_t *in, size_t inlen, uint8_t *out, size_t *outlen,
++            size_t maxlen);
+ };
+ 
+ // Our analog of ssl3CipherSpec
+ class TlsCipherSpec {
+  public:
+   TlsCipherSpec() : epoch_(0), aead_() {}
+ 
+   bool Init(uint16_t epoch, SSLCipherAlgorithm cipher, PK11SymKey *key,
+diff --git a/security/nss/lib/ssl/dtls13con.c b/security/nss/lib/ssl/dtls13con.c
+--- a/security/nss/lib/ssl/dtls13con.c
++++ b/security/nss/lib/ssl/dtls13con.c
+@@ -6,16 +6,53 @@
+ /*
+  * DTLS 1.3 Protocol
+  */
+ 
+ #include "ssl.h"
+ #include "sslimpl.h"
+ #include "sslproto.h"
+ 
++SECStatus
++dtls13_InsertCipherTextHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
++                              sslBuffer *wrBuf, PRBool *needsLength)
++{
++    PRUint32 seq;
++    SECStatus rv;
++
++    /* Avoid using short records for the handshake.  We pack multiple records
++     * into the one datagram for the handshake. */
++    if (ss->opt.enableDtlsShortHeader &&
++        cwSpec->epoch != TrafficKeyHandshake) {
++        *needsLength = PR_FALSE;
++        /* The short header is comprised of two octets in the form
++         * 0b001essssssssssss where 'e' is the low bit of the epoch and 's' is
++         * the low 12 bits of the sequence number. */
++        seq = 0x2000 |
++              (((uint64_t)cwSpec->epoch & 1) << 12) |
++              (cwSpec->nextSeqNum & 0xfff);
++        return sslBuffer_AppendNumber(wrBuf, seq, 2);
++    }
++
++    rv = sslBuffer_AppendNumber(wrBuf, content_application_data, 1);
++    if (rv != SECSuccess) {
++        return SECFailure;
++    }
++
++    /* The epoch and sequence number are encoded on 4 octets, with the epoch
++     * consuming the first two bits. */
++    seq = (((uint64_t)cwSpec->epoch & 3) << 30) | (cwSpec->nextSeqNum & 0x3fffffff);
++    rv = sslBuffer_AppendNumber(wrBuf, seq, 4);
++    if (rv != SECSuccess) {
++        return SECFailure;
++    }
++    *needsLength = PR_TRUE;
++    return SECSuccess;
++}
++
+ /* DTLS 1.3 Record map for ACK processing.
+  * This represents a single fragment, so a record which includes
+  * multiple fragments will have one entry for each fragment on the
+  * sender. We use the same structure on the receiver for convenience
+  * but the only value we actually use is |record|.
+  */
+ typedef struct DTLSHandshakeRecordEntryStr {
+     PRCList link;
+diff --git a/security/nss/lib/ssl/dtls13con.h b/security/nss/lib/ssl/dtls13con.h
+--- a/security/nss/lib/ssl/dtls13con.h
++++ b/security/nss/lib/ssl/dtls13con.h
+@@ -4,16 +4,20 @@
+  *
+  * This Source Code Form is subject to the terms of the Mozilla Public
+  * 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/. */
+ 
+ #ifndef __dtls13con_h_
+ #define __dtls13con_h_
+ 
++SECStatus dtls13_InsertCipherTextHeader(const sslSocket *ss,
++                                        ssl3CipherSpec *cwSpec,
++                                        sslBuffer *wrBuf,
++                                        PRBool *needsLength);
+ SECStatus dtls13_RememberFragment(sslSocket *ss, PRCList *list,
+                                   PRUint32 sequence, PRUint32 offset,
+                                   PRUint32 length, DTLSEpoch epoch,
+                                   sslSequenceNumber record);
+ PRBool dtls_NextUnackedRange(sslSocket *ss, PRUint16 msgSeq, PRUint32 offset,
+                              PRUint32 len, PRUint32 *startOut, PRUint32 *endOut);
+ SECStatus dtls13_SetupAcks(sslSocket *ss);
+ SECStatus dtls13_HandleOutOfEpochRecord(sslSocket *ss, const ssl3CipherSpec *spec,
+diff --git a/security/nss/lib/ssl/dtlscon.c b/security/nss/lib/ssl/dtlscon.c
+--- a/security/nss/lib/ssl/dtlscon.c
++++ b/security/nss/lib/ssl/dtlscon.c
+@@ -771,17 +771,17 @@ dtls_FragmentHandshake(sslSocket *ss, DT
+             fragment = SSL_BUFFER_BASE(&tmp);
+         }
+ 
+         /* Record that we are sending first, because encrypting
+          * increments the sequence number. */
+         rv = dtls13_RememberFragment(ss, &ss->ssl3.hs.dtlsSentHandshake,
+                                      msgSeq, fragmentOffset, fragmentLen,
+                                      msg->cwSpec->epoch,
+-                                     msg->cwSpec->seqNum);
++                                     msg->cwSpec->nextSeqNum);
+         if (rv != SECSuccess) {
+             return SECFailure;
+         }
+ 
+         rv = dtls_SendFragment(ss, msg, fragment,
+                                fragmentLen + DTLS_HS_HDR_LEN);
+         if (rv != SECSuccess) {
+             return SECFailure;
+@@ -1314,16 +1314,117 @@ DTLS_GetHandshakeTimeout(PRFileDesc *soc
+     if (!found) {
+         PORT_SetError(SSL_ERROR_NO_TIMERS_FOUND);
+         return SECFailure;
+     }
+ 
+     return SECSuccess;
+ }
+ 
++PRBool
++dtls_IsLongHeader(SSL3ProtocolVersion version, PRUint8 firstOctet)
++{
++#ifndef UNSAFE_FUZZER_MODE
++    return version < SSL_LIBRARY_VERSION_TLS_1_3 ||
++           firstOctet == content_handshake ||
++           firstOctet == content_ack ||
++           firstOctet == content_alert;
++#else
++    return PR_TRUE;
++#endif
++}
++
++DTLSEpoch
++dtls_ReadEpoch(const ssl3CipherSpec *crSpec, const PRUint8 *hdr)
++{
++    DTLSEpoch epoch;
++    DTLSEpoch maxEpoch;
++    DTLSEpoch partial;
++
++    if (dtls_IsLongHeader(crSpec->version, hdr[0])) {
++        return ((DTLSEpoch)hdr[3] << 8) | hdr[4];
++    }
++
++    /* A lot of how we recover the epoch here will depend on how we plan to
++     * manage KeyUpdate.  In the case that we decide to install a new read spec
++     * as a KeyUpdate is handled, crSpec will always be the highest epoch we can
++     * possibly receive.  That makes this easier to manage. */
++    if ((hdr[0] & 0xe0) == 0x20) {
++        /* Use crSpec->epoch, or crSpec->epoch - 1 if the last bit differs. */
++        if (((hdr[0] >> 4) & 1) == (crSpec->epoch & 1)) {
++            return crSpec->epoch;
++        }
++        return crSpec->epoch - 1;
++    }
++
++    /* dtls_GatherData should ensure that this works. */
++    PORT_Assert(hdr[0] == content_application_data);
++
++    /* This uses the same method as is used to recover the sequence number in
++     * dtls_ReadSequenceNumber, except that the maximum value is set to the
++     * current epoch. */
++    partial = hdr[1] >> 6;
++    maxEpoch = PR_MAX(crSpec->epoch, 3);
++    epoch = (maxEpoch & 0xfffc) | partial;
++    if (partial > (maxEpoch & 0x03)) {
++        epoch -= 4;
++    }
++    return epoch;
++}
++
++static sslSequenceNumber
++dtls_ReadSequenceNumber(const ssl3CipherSpec *spec, const PRUint8 *hdr)
++{
++    sslSequenceNumber cap;
++    sslSequenceNumber partial;
++    sslSequenceNumber seqNum;
++    sslSequenceNumber mask;
++
++    if (dtls_IsLongHeader(spec->version, hdr[0])) {
++        static const unsigned int seqNumOffset = 5; /* type, version, epoch */
++        static const unsigned int seqNumLength = 6;
++        sslReader r = SSL_READER(hdr + seqNumOffset, seqNumLength);
++        (void)sslRead_ReadNumber(&r, seqNumLength, &seqNum);
++        return seqNum;
++    }
++
++    /* Only the least significant bits of the sequence number is available here.
++     * This recovers the value based on the next expected sequence number.
++     *
++     * This works by determining the maximum possible sequence number, which is
++     * half the range of possible values above the expected next value (the
++     * expected next value is in |spec->seqNum|).  Then, the last part of the
++     * sequence number is replaced.  If that causes the value to exceed the
++     * maximum, subtract an entire range.
++     */
++    if ((hdr[0] & 0xe0) == 0x20) {
++        /* A 12-bit sequence number. */
++        cap = spec->nextSeqNum + (1ULL << 11);
++        partial = (((sslSequenceNumber)hdr[0] & 0xf) << 8) |
++                  (sslSequenceNumber)hdr[1];
++        mask = (1ULL << 12) - 1;
++    } else {
++        /* A 30-bit sequence number. */
++        cap = spec->nextSeqNum + (1ULL << 29);
++        partial = (((sslSequenceNumber)hdr[1] & 0x3f) << 24) |
++                  ((sslSequenceNumber)hdr[2] << 16) |
++                  ((sslSequenceNumber)hdr[3] << 8) |
++                  (sslSequenceNumber)hdr[4];
++        mask = (1ULL << 30) - 1;
++    }
++    seqNum = (cap & ~mask) | partial;
++    /* The second check prevents the value from underflowing if we get a large
++     * gap at the start of a connection, where this subtraction would cause the
++     * sequence number to wrap to near UINT64_MAX. */
++    if ((partial > (cap & mask)) && (seqNum > mask)) {
++        seqNum -= mask + 1;
++    }
++    return seqNum;
++}
++
+ /*
+  * DTLS relevance checks:
+  * Note that this code currently ignores all out-of-epoch packets,
+  * which means we lose some in the case of rehandshake +
+  * loss/reordering. Since DTLS is explicitly unreliable, this
+  * seems like a good tradeoff for implementation effort and is
+  * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1.
+  *
+@@ -1331,17 +1432,17 @@ DTLS_GetHandshakeTimeout(PRFileDesc *soc
+  * is relevant, this function returns PR_TRUE and sets |*seqNumOut| to the
+  * packet sequence number (removing the epoch).
+  */
+ PRBool
+ dtls_IsRelevant(sslSocket *ss, const ssl3CipherSpec *spec,
+                 const SSL3Ciphertext *cText,
+                 sslSequenceNumber *seqNumOut)
+ {
+-    sslSequenceNumber seqNum = cText->seq_num & RECORD_SEQ_MASK;
++    sslSequenceNumber seqNum = dtls_ReadSequenceNumber(spec, cText->hdr);
+     if (dtls_RecordGetRecvd(&spec->recvdRecords, seqNum) != 0) {
+         SSL_TRC(10, ("%d: SSL3[%d]: dtls_IsRelevant, rejecting "
+                      "potentially replayed packet",
+                      SSL_GETPID(), ss->fd));
+         return PR_FALSE;
+     }
+ 
+     *seqNumOut = seqNum;
+diff --git a/security/nss/lib/ssl/dtlscon.h b/security/nss/lib/ssl/dtlscon.h
+--- a/security/nss/lib/ssl/dtlscon.h
++++ b/security/nss/lib/ssl/dtlscon.h
+@@ -36,13 +36,15 @@ extern int dtls_RecordGetRecvd(const DTL
+                                sslSequenceNumber seq);
+ extern void dtls_RecordSetRecvd(DTLSRecvdRecords *records,
+                                 sslSequenceNumber seq);
+ extern void dtls_RehandshakeCleanup(sslSocket *ss);
+ extern SSL3ProtocolVersion
+ dtls_TLSVersionToDTLSVersion(SSL3ProtocolVersion tlsv);
+ extern SSL3ProtocolVersion
+ dtls_DTLSVersionToTLSVersion(SSL3ProtocolVersion dtlsv);
++DTLSEpoch dtls_ReadEpoch(const ssl3CipherSpec *crSpec, const PRUint8 *hdr);
+ extern PRBool dtls_IsRelevant(sslSocket *ss, const ssl3CipherSpec *spec,
+                               const SSL3Ciphertext *cText,
+                               sslSequenceNumber *seqNum);
+ void dtls_ReceivedFirstMessageInFlight(sslSocket *ss);
++PRBool dtls_IsLongHeader(SSL3ProtocolVersion version, PRUint8 firstOctet);
+ #endif
+diff --git a/security/nss/lib/ssl/ssl.h b/security/nss/lib/ssl/ssl.h
+--- a/security/nss/lib/ssl/ssl.h
++++ b/security/nss/lib/ssl/ssl.h
+@@ -249,16 +249,27 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRF
+ #define SSL_ENABLE_0RTT_DATA 33
+ 
+ /* Enables TLS 1.3 compatibility mode.  In this mode, the client includes a fake
+  * session ID in the handshake and sends a ChangeCipherSpec.  A server will
+  * always use the setting chosen by the client, so the value of this option has
+  * no effect for a server. This setting is ignored for DTLS. */
+ #define SSL_ENABLE_TLS13_COMPAT_MODE 35
+ 
++/* Enables the sending of DTLS records using the short (two octet) record
++ * header.  Only do this if there are 2^10 or fewer packets in flight at a time;
++ * using this with a larger number of packets in flight could mean that packets
++ * are dropped if there is reordering.
++ *
++ * This applies to TLS 1.3 only.  This is not a parameter that is negotiated
++ * during the TLS handshake. Unlike other socket options, this option can be
++ * changed after a handshake is complete.
++ */
++#define SSL_ENABLE_DTLS_SHORT_HEADER 36
++
+ #ifdef SSL_DEPRECATED_FUNCTION
+ /* Old deprecated function names */
+ SSL_IMPORT SECStatus SSL_Enable(PRFileDesc *fd, int option, PRIntn on);
+ SSL_IMPORT SECStatus SSL_EnableDefault(int option, PRIntn on);
+ #endif
+ 
+ /* Set (and get) options for sockets and defaults for newly created sockets.
+  *
+diff --git a/security/nss/lib/ssl/ssl3con.c b/security/nss/lib/ssl/ssl3con.c
+--- a/security/nss/lib/ssl/ssl3con.c
++++ b/security/nss/lib/ssl/ssl3con.c
+@@ -985,37 +985,32 @@ ssl_ClientReadVersion(sslSocket *ss, PRU
+     SSL3ProtocolVersion v;
+     PRUint32 temp;
+     SECStatus rv;
+ 
+     rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, b, len);
+     if (rv != SECSuccess) {
+         return SECFailure; /* alert has been sent */
+     }
+-
+-#ifdef TLS_1_3_DRAFT_VERSION
+-    if (temp == SSL_LIBRARY_VERSION_TLS_1_3) {
+-        (void)SSL3_SendAlert(ss, alert_fatal, protocol_version);
+-        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
+-        return SECFailure;
+-    }
+-    if (temp == tls13_EncodeDraftVersion(SSL_LIBRARY_VERSION_TLS_1_3)) {
+-        v = SSL_LIBRARY_VERSION_TLS_1_3;
+-    } else {
+-        v = (SSL3ProtocolVersion)temp;
+-    }
+-#else
+     v = (SSL3ProtocolVersion)temp;
+-#endif
+ 
+     if (IS_DTLS(ss)) {
+-        /* If this fails, we get 0 back and the next check to fails. */
+         v = dtls_DTLSVersionToTLSVersion(v);
+-    }
+-
++        /* Check for failure. */
++        if (!v || v > SSL_LIBRARY_VERSION_MAX_SUPPORTED) {
++            SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
++            return SECFailure;
++        }
++    }
++
++    /* You can't negotiate TLS 1.3 this way. */
++    if (v >= SSL_LIBRARY_VERSION_TLS_1_3) {
++        SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
++        return SECFailure;
++    }
+     *version = v;
+     return SECSuccess;
+ }
+ 
+ static SECStatus
+ ssl3_GetNewRandom(SSL3Random random)
+ {
+     SECStatus rv;
+@@ -1410,17 +1405,17 @@ ssl3_SetupPendingCipherSpec(sslSocket *s
+     if (!spec) {
+         return SECFailure;
+     }
+ 
+     spec->cipherDef = ssl_GetBulkCipherDef(suiteDef);
+     spec->macDef = ssl_GetMacDef(ss, suiteDef);
+ 
+     spec->epoch = prev->epoch + 1;
+-    spec->seqNum = 0;
++    spec->nextSeqNum = 0;
+     if (IS_DTLS(ss) && direction == CipherSpecRead) {
+         dtls_InitRecvdRecords(&spec->recvdRecords);
+     }
+     ssl_SetSpecVersions(ss, spec);
+ 
+     ssl_SaveCipherSpec(ss, spec);
+     *specp = spec;
+     return SECSuccess;
+@@ -1999,82 +1994,89 @@ ssl3_MACEncryptRecord(ssl3CipherSpec *cw
+ {
+     SECStatus rv;
+     PRUint32 macLen = 0;
+     PRUint32 fragLen;
+     PRUint32 p1Len, p2Len, oddLen = 0;
+     unsigned int ivLen = 0;
+     unsigned char pseudoHeaderBuf[13];
+     sslBuffer pseudoHeader = SSL_BUFFER(pseudoHeaderBuf);
++    int len;
+ 
+     if (cwSpec->cipherDef->type == type_block &&
+         cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
+         /* Prepend the per-record explicit IV using technique 2b from
+          * RFC 4346 section 6.2.3.2: The IV is a cryptographically
+          * strong random number XORed with the CBC residue from the previous
+          * record.
+          */
+         ivLen = cwSpec->cipherDef->iv_size;
+-        if (ivLen > wrBuf->space) {
++        if (ivLen > SSL_BUFFER_SPACE(wrBuf)) {
+             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+             return SECFailure;
+         }
+-        rv = PK11_GenerateRandom(wrBuf->buf, ivLen);
++        rv = PK11_GenerateRandom(SSL_BUFFER_NEXT(wrBuf), ivLen);
+         if (rv != SECSuccess) {
+             ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
+             return rv;
+         }
+         rv = cwSpec->cipher(cwSpec->cipherContext,
+-                            wrBuf->buf,         /* output */
+-                            (int *)&wrBuf->len, /* outlen */
+-                            ivLen,              /* max outlen */
+-                            wrBuf->buf,         /* input */
+-                            ivLen);             /* input len */
+-        if (rv != SECSuccess || wrBuf->len != ivLen) {
++                            SSL_BUFFER_NEXT(wrBuf), /* output */
++                            &len,                   /* outlen */
++                            ivLen,                  /* max outlen */
++                            SSL_BUFFER_NEXT(wrBuf), /* input */
++                            ivLen);                 /* input len */
++        if (rv != SECSuccess || len != ivLen) {
+             PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
+             return SECFailure;
+         }
++
++        rv = sslBuffer_Skip(wrBuf, len, NULL);
++        PORT_Assert(rv == SECSuccess); /* Can't fail. */
+     }
+ 
+     rv = ssl3_BuildRecordPseudoHeader(
+-        cwSpec->epoch, cwSpec->seqNum, type,
++        cwSpec->epoch, cwSpec->nextSeqNum, type,
+         cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->recordVersion,
+         isDTLS, contentLen, &pseudoHeader);
+     PORT_Assert(rv == SECSuccess);
+     if (cwSpec->cipherDef->type == type_aead) {
+         const int nonceLen = cwSpec->cipherDef->explicit_nonce_size;
+         const int tagLen = cwSpec->cipherDef->tag_size;
+ 
+-        if (nonceLen + contentLen + tagLen > wrBuf->space) {
++        if (nonceLen + contentLen + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
+             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+             return SECFailure;
+         }
+ 
+         rv = cwSpec->aead(
+             &cwSpec->keyMaterial,
+-            PR_FALSE,           /* do encrypt */
+-            wrBuf->buf,         /* output  */
+-            (int *)&wrBuf->len, /* out len */
+-            wrBuf->space,       /* max out */
+-            pIn, contentLen,    /* input   */
++            PR_FALSE,                /* do encrypt */
++            SSL_BUFFER_NEXT(wrBuf),  /* output  */
++            &len,                    /* out len */
++            SSL_BUFFER_SPACE(wrBuf), /* max out */
++            pIn, contentLen,         /* input   */
+             SSL_BUFFER_BASE(&pseudoHeader), SSL_BUFFER_LEN(&pseudoHeader));
+         if (rv != SECSuccess) {
+             PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
+             return SECFailure;
+         }
++
++        rv = sslBuffer_Skip(wrBuf, len, NULL);
++        PORT_Assert(rv == SECSuccess); /* Can't fail. */
+     } else {
+         int blockSize = cwSpec->cipherDef->block_size;
+ 
+         /*
+          * Add the MAC
+          */
+         rv = ssl3_ComputeRecordMAC(cwSpec, SSL_BUFFER_BASE(&pseudoHeader),
+                                    SSL_BUFFER_LEN(&pseudoHeader),
+                                    pIn, contentLen,
+-                                   wrBuf->buf + ivLen + contentLen, &macLen);
++                                   SSL_BUFFER_NEXT(wrBuf) + contentLen, &macLen);
+         if (rv != SECSuccess) {
+             ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
+             return SECFailure;
+         }
+         p1Len = contentLen;
+         p2Len = macLen;
+         fragLen = contentLen + macLen; /* needs to be encrypted */
+         PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
+@@ -2090,81 +2092,87 @@ ssl3_MACEncryptRecord(ssl3CipherSpec *cw
+ 
+             oddLen = contentLen % blockSize;
+             /* Assume blockSize is a power of two */
+             padding_length = blockSize - 1 - ((fragLen) & (blockSize - 1));
+             fragLen += padding_length + 1;
+             PORT_Assert((fragLen % blockSize) == 0);
+ 
+             /* Pad according to TLS rules (also acceptable to SSL3). */
+-            pBuf = &wrBuf->buf[ivLen + fragLen - 1];
++            pBuf = SSL_BUFFER_NEXT(wrBuf) + fragLen - 1;
+             for (i = padding_length + 1; i > 0; --i) {
+                 *pBuf-- = padding_length;
+             }
+             /* now, if contentLen is not a multiple of block size, fix it */
+             p2Len = fragLen - p1Len;
+         }
+         if (p1Len < 256) {
+             oddLen = p1Len;
+             p1Len = 0;
+         } else {
+             p1Len -= oddLen;
+         }
+         if (oddLen) {
+             p2Len += oddLen;
+             PORT_Assert((blockSize < 2) ||
+                         (p2Len % blockSize) == 0);
+-            memmove(wrBuf->buf + ivLen + p1Len, pIn + p1Len, oddLen);
++            memmove(SSL_BUFFER_NEXT(wrBuf) + p1Len, pIn + p1Len, oddLen);
+         }
+         if (p1Len > 0) {
+             int cipherBytesPart1 = -1;
+             rv = cwSpec->cipher(cwSpec->cipherContext,
+-                                wrBuf->buf + ivLen, /* output */
+-                                &cipherBytesPart1,  /* actual outlen */
+-                                p1Len,              /* max outlen */
++                                SSL_BUFFER_NEXT(wrBuf), /* output */
++                                &cipherBytesPart1,      /* actual outlen */
++                                p1Len,                  /* max outlen */
+                                 pIn,
+                                 p1Len); /* input, and inputlen */
+             PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int)p1Len);
+             if (rv != SECSuccess || cipherBytesPart1 != (int)p1Len) {
+                 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
+                 return SECFailure;
+             }
+-            wrBuf->len += cipherBytesPart1;
++            rv = sslBuffer_Skip(wrBuf, p1Len, NULL);
++            PORT_Assert(rv == SECSuccess);
+         }
+         if (p2Len > 0) {
+             int cipherBytesPart2 = -1;
+             rv = cwSpec->cipher(cwSpec->cipherContext,
+-                                wrBuf->buf + ivLen + p1Len,
++                                SSL_BUFFER_NEXT(wrBuf),
+                                 &cipherBytesPart2, /* output and actual outLen */
+                                 p2Len,             /* max outlen */
+-                                wrBuf->buf + ivLen + p1Len,
++                                SSL_BUFFER_NEXT(wrBuf),
+                                 p2Len); /* input and inputLen*/
+             PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int)p2Len);
+             if (rv != SECSuccess || cipherBytesPart2 != (int)p2Len) {
+                 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
+                 return SECFailure;
+             }
+-            wrBuf->len += cipherBytesPart2;
++            rv = sslBuffer_Skip(wrBuf, p2Len, NULL);
++            PORT_Assert(rv == SECSuccess);
+         }
+     }
+ 
+     return SECSuccess;
+ }
+ 
+ /* Note: though this can report failure, it shouldn't. */
+-static SECStatus
++SECStatus
+ ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
+-                       SSL3ContentType contentType, unsigned int len,
+-                       sslBuffer *wrBuf)
++                       SSL3ContentType contentType, sslBuffer *wrBuf,
++                       PRBool *needsLength)
+ {
+     SECStatus rv;
+ 
+ #ifndef UNSAFE_FUZZER_MODE
+     if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+-        cwSpec->cipherDef->calg != ssl_calg_null) {
++        cwSpec->epoch > TrafficKeyClearText) {
++        if (IS_DTLS(ss)) {
++            return dtls13_InsertCipherTextHeader(ss, cwSpec, wrBuf,
++                                                 needsLength);
++        }
+         contentType = content_application_data;
+     }
+ #endif
+     rv = sslBuffer_AppendNumber(wrBuf, contentType, 1);
+     if (rv != SECSuccess) {
+         return SECFailure;
+     }
+ 
+@@ -2172,93 +2180,90 @@ ssl_InsertRecordHeader(const sslSocket *
+     if (rv != SECSuccess) {
+         return SECFailure;
+     }
+     if (IS_DTLS(ss)) {
+         rv = sslBuffer_AppendNumber(wrBuf, cwSpec->epoch, 2);
+         if (rv != SECSuccess) {
+             return SECFailure;
+         }
+-        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->seqNum, 6);
++        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->nextSeqNum, 6);
+         if (rv != SECSuccess) {
+             return SECFailure;
+         }
+     }
+-    rv = sslBuffer_AppendNumber(wrBuf, len, 2);
+-    if (rv != SECSuccess) {
+-        return SECFailure;
+-    }
+-
++    *needsLength = PR_TRUE;
+     return SECSuccess;
+ }
+ 
+ SECStatus
+ ssl_ProtectRecord(sslSocket *ss, ssl3CipherSpec *cwSpec, SSL3ContentType type,
+                   const PRUint8 *pIn, PRUint32 contentLen, sslBuffer *wrBuf)
+ {
+-    unsigned int headerLen = IS_DTLS(ss) ? DTLS_RECORD_HEADER_LENGTH
+-                                         : SSL3_RECORD_HEADER_LENGTH;
+-    sslBuffer protBuf = SSL_BUFFER_FIXED(SSL_BUFFER_BASE(wrBuf) + headerLen,
+-                                         SSL_BUFFER_SPACE(wrBuf) - headerLen);
+-    PRBool isTLS13;
++    PRBool needsLength;
++    unsigned int lenOffset;
+     SECStatus rv;
+ 
+     PORT_Assert(cwSpec->direction == CipherSpecWrite);
+     PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
+     PORT_Assert(cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX);
+-    if (cwSpec->seqNum >= cwSpec->cipherDef->max_records) {
++
++    if (cwSpec->nextSeqNum >= cwSpec->cipherDef->max_records) {
+         /* We should have automatically updated before here in TLS 1.3. */
+         PORT_Assert(cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_3);
+         SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx",
+-                    SSL_GETPID(), cwSpec->seqNum));
++                    SSL_GETPID(), cwSpec->nextSeqNum));
+         PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
+         return SECFailure;
+     }
+ 
+-    isTLS13 = (PRBool)(cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3);
++    rv = ssl_InsertRecordHeader(ss, cwSpec, type, wrBuf, &needsLength);
++    if (rv != SECSuccess) {
++        return SECFailure;
++    }
++    if (needsLength) {
++        rv = sslBuffer_Skip(wrBuf, 2, &lenOffset);
++        if (rv != SECSuccess) {
++            return SECFailure;
++        }
++    }
+ 
+ #ifdef UNSAFE_FUZZER_MODE
+     {
+         int len;
+-        rv = Null_Cipher(NULL, SSL_BUFFER_BASE(&protBuf), &len,
+-                         SSL_BUFFER_SPACE(&protBuf), pIn, contentLen);
++        rv = Null_Cipher(NULL, SSL_BUFFER_NEXT(wrBuf), &len,
++                         SSL_BUFFER_SPACE(wrBuf), pIn, contentLen);
+         if (rv != SECSuccess) {
+             return SECFailure; /* error was set */
+         }
+-        rv = sslBuffer_Skip(&protBuf, len, NULL);
++        rv = sslBuffer_Skip(wrBuf, len, NULL);
+         PORT_Assert(rv == SECSuccess); /* Can't fail. */
+     }
+ #else
+-    if (isTLS13) {
+-        rv = tls13_ProtectRecord(ss, cwSpec, type, pIn, contentLen, &protBuf);
++    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
++        rv = tls13_ProtectRecord(ss, cwSpec, type, pIn, contentLen, wrBuf);
+     } else {
+         rv = ssl3_MACEncryptRecord(cwSpec, ss->sec.isServer, IS_DTLS(ss), type,
+-                                   pIn, contentLen, &protBuf);
++                                   pIn, contentLen, wrBuf);
+     }
+ #endif
+     if (rv != SECSuccess) {
+         return SECFailure; /* error was set */
+     }
+ 
+-    PORT_Assert(protBuf.len <= MAX_FRAGMENT_LENGTH + (isTLS13 ? 256 : 1024));
+-
+-    rv = ssl_InsertRecordHeader(ss, cwSpec, type, SSL_BUFFER_LEN(&protBuf),
+-                                wrBuf);
+-    if (rv != SECSuccess) {
+-        return SECFailure;
+-    }
+-
+-    PORT_Assert(SSL_BUFFER_LEN(wrBuf) == headerLen);
+-    rv = sslBuffer_Skip(wrBuf, SSL_BUFFER_LEN(&protBuf), NULL);
+-    if (rv != SECSuccess) {
+-        PORT_Assert(0); /* Can't fail. */
+-        return SECFailure;
+-    }
+-    ++cwSpec->seqNum;
+-
++    if (needsLength) {
++        /* Insert the length. */
++        rv = sslBuffer_InsertLength(wrBuf, lenOffset, 2);
++        if (rv != SECSuccess) {
++            PORT_Assert(0); /* Can't fail. */
++            return SECFailure;
++        }
++    }
++
++    ++cwSpec->nextSeqNum;
+     return SECSuccess;
+ }
+ 
+ SECStatus
+ ssl_ProtectNextRecord(sslSocket *ss, ssl3CipherSpec *spec, SSL3ContentType type,
+                       const PRUint8 *pIn, unsigned int nIn,
+                       unsigned int *written)
+ {
+@@ -2286,16 +2291,17 @@ ssl_ProtectNextRecord(sslSocket *ss, ssl
+     if (rv != SECSuccess) {
+         return SECFailure;
+     }
+     PRINT_BUF(50, (ss, "send (encrypted) record data:",
+                    SSL_BUFFER_BASE(wrBuf), SSL_BUFFER_LEN(wrBuf)));
+     *written = contentLen;
+     return SECSuccess;
+ }
++
+ /* Process the plain text before sending it.
+  * Returns the number of bytes of plaintext that were successfully sent
+  *  plus the number of bytes of plaintext that were copied into the
+  *  output (write) buffer.
+  * Returns SECFailure on a hard IO error, memory error, or crypto error.
+  * Does NOT return SECWouldBlock.
+  *
+  * Notes on the use of the private ssl flags:
+@@ -2363,17 +2369,17 @@ ssl3_SendRecord(sslSocket *ss,
+     while (nIn > 0) {
+         unsigned int written = 0;
+         PRInt32 sent;
+ 
+         ssl_GetSpecReadLock(ss);
+         rv = ssl_ProtectNextRecord(ss, spec, type, pIn, nIn, &written);
+         ssl_ReleaseSpecReadLock(ss);
+         if (rv != SECSuccess) {
+-            return SECFailure;
++            goto loser;
+         }
+ 
+         PORT_Assert(written > 0);
+         /* DTLS should not fragment non-application data here. */
+         if (IS_DTLS(ss) && type != content_application_data) {
+             PORT_Assert(written == nIn);
+         }
+ 
+@@ -6160,17 +6166,16 @@ ssl3_HandleServerHello(sslSocket *ss, PR
+ {
+     PRUint32 cipher;
+     int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+     PRUint32 compression;
+     SECStatus rv;
+     SECItem sidBytes = { siBuffer, NULL, 0 };
+     PRBool isHelloRetry;
+     SSL3AlertDescription desc = illegal_parameter;
+-    TLSExtension *versionExtension;
+     const PRUint8 *savedMsg = b;
+     const PRUint32 savedLength = length;
+ #ifndef TLS_1_3_DRAFT_VERSION
+     SSL3ProtocolVersion downgradeCheckVersion;
+ #endif
+ 
+     SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
+                 SSL_GETPID(), ss->fd));
+@@ -6251,26 +6256,20 @@ ssl3_HandleServerHello(sslSocket *ss, PR
+             goto alert_loser;
+         }
+         rv = ssl3_ParseExtensions(ss, &b, &length);
+         if (rv != SECSuccess) {
+             goto alert_loser; /* malformed */
+         }
+     }
+ 
+-    /* Update the version based on the extension, as necessary. */
+-    versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
+-    if (versionExtension) {
+-        rv = ssl_ClientReadVersion(ss, &versionExtension->data.data,
+-                                   &versionExtension->data.len,
+-                                   &ss->version);
+-        if (rv != SECSuccess) {
+-            errCode = PORT_GetError();
+-            goto loser; /* An alert is sent by ssl_ClientReadVersion */
+-        }
++    /* Read supported_versions if present. */
++    rv = tls13_ClientReadSupportedVersion(ss);
++    if (rv != SECSuccess) {
++        goto loser;
+     }
+ 
+     PORT_Assert(!SSL_ALL_VERSIONS_DISABLED(&ss->vrange));
+     /* Check that the version is within the configured range. */
+     if (ss->vrange.min > ss->version || ss->vrange.max < ss->version) {
+         desc = (ss->version > SSL_LIBRARY_VERSION_3_0)
+                    ? protocol_version
+                    : handshake_failure;
+@@ -6345,18 +6344,19 @@ ssl3_HandleServerHello(sslSocket *ss, PR
+             goto alert_loser;
+         }
+     }
+ #endif
+ 
+     /* Finally, now all the version-related checks have passed. */
+     ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
+     /* Update the write cipher spec to match the version. But not after
+-     * HelloRetryRequest, because cwSpec might be a 0-RTT cipher spec. */
+-    if (!ss->firstHsDone && !ss->ssl3.hs.helloRetry) {
++     * HelloRetryRequest, because cwSpec might be a 0-RTT cipher spec,
++     * in which case this is a no-op. */
++    if (!ss->firstHsDone && !isHelloRetry) {
+         ssl_GetSpecWriteLock(ss);
+         ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
+         ssl_ReleaseSpecWriteLock(ss);
+     }
+ 
+     /* Check that the session ID is as expected. */
+     if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+         PRUint8 buf[SSL3_SESSIONID_BYTES];
+@@ -8843,22 +8843,20 @@ loser:
+ SECStatus
+ ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
+                          const sslBuffer *extensionBuf, sslBuffer *messageBuf)
+ {
+     SECStatus rv;
+     SSL3ProtocolVersion version;
+     sslSessionID *sid = ss->sec.ci.sid;
+ 
+-    if (IS_DTLS(ss) && ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+-        version = dtls_TLSVersionToDTLSVersion(ss->version);
+-    } else {
+-        version = PR_MIN(ss->version, SSL_LIBRARY_VERSION_TLS_1_2);
+-    }
+-
++    version = PR_MIN(ss->version, SSL_LIBRARY_VERSION_TLS_1_2);
++    if (IS_DTLS(ss)) {
++        version = dtls_TLSVersionToDTLSVersion(version);
++    }
+     rv = sslBuffer_AppendNumber(messageBuf, version, 2);
+     if (rv != SECSuccess) {
+         return SECFailure;
+     }
+     /* Random already generated in ssl3_HandleClientHello */
+     rv = sslBuffer_Append(messageBuf, helloRetry ? ssl_hello_retry_random : ss->ssl3.hs.server_random,
+                           SSL3_RANDOM_LENGTH);
+     if (rv != SECSuccess) {
+@@ -11842,16 +11840,17 @@ ssl3_UnprotectRecord(sslSocket *ss,
+                      SSL3Ciphertext *cText, sslBuffer *plaintext,
+                      SSL3AlertDescription *alert)
+ {
+     const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
+     PRBool isTLS;
+     unsigned int good;
+     unsigned int ivLen = 0;
+     SSL3ContentType rType;
++    SSL3ProtocolVersion rVersion;
+     unsigned int minLength;
+     unsigned int originalLen = 0;
+     PRUint8 headerBuf[13];
+     sslBuffer header = SSL_BUFFER(headerBuf);
+     PRUint8 hash[MAX_MAC_LENGTH];
+     PRUint8 givenHashBuf[MAX_MAC_LENGTH];
+     PRUint8 *givenHash;
+     unsigned int hashBytes = MAX_MAC_LENGTH + 1;
+@@ -11914,28 +11913,30 @@ ssl3_UnprotectRecord(sslSocket *ss,
+     isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
+ 
+     if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
+         *alert = record_overflow;
+         PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
+         return SECFailure;
+     }
+ 
+-    rType = cText->type;
++    rType = (SSL3ContentType)cText->hdr[0];
++    rVersion = ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
++               (SSL3ProtocolVersion)cText->hdr[2];
+     if (cipher_def->type == type_aead) {
+         /* XXX For many AEAD ciphers, the plaintext is shorter than the
+          * ciphertext by a fixed byte count, but it is not true in general.
+          * Each AEAD cipher should provide a function that returns the
+          * plaintext length for a given ciphertext. */
+         unsigned int decryptedLen =
+             cText->buf->len - cipher_def->explicit_nonce_size -
+             cipher_def->tag_size;
+         rv = ssl3_BuildRecordPseudoHeader(
+-            spec->epoch, IS_DTLS(ss) ? cText->seq_num : spec->seqNum,
+-            rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen, &header);
++            spec->epoch, cText->seqNum,
++            rType, isTLS, rVersion, IS_DTLS(ss), decryptedLen, &header);
+         PORT_Assert(rv == SECSuccess);
+         rv = spec->aead(&spec->keyMaterial,
+                         PR_TRUE,                /* do decrypt */
+                         plaintext->buf,         /* out */
+                         (int *)&plaintext->len, /* outlen */
+                         plaintext->space,       /* maxout */
+                         cText->buf->buf,        /* in */
+                         cText->buf->len,        /* inlen */
+@@ -11972,18 +11973,18 @@ ssl3_UnprotectRecord(sslSocket *ss,
+             } else {
+                 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
+                     plaintext, macSize));
+             }
+         }
+ 
+         /* compute the MAC */
+         rv = ssl3_BuildRecordPseudoHeader(
+-            spec->epoch, IS_DTLS(ss) ? cText->seq_num : spec->seqNum,
+-            rType, isTLS, cText->version, IS_DTLS(ss),
++            spec->epoch, cText->seqNum,
++            rType, isTLS, rVersion, IS_DTLS(ss),
+             plaintext->len - spec->macDef->mac_size, &header);
+         PORT_Assert(rv == SECSuccess);
+         if (cipher_def->type == type_block) {
+             rv = ssl3_ComputeRecordMACConstantTime(
+                 spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
+                 plaintext->buf, plaintext->len, originalLen,
+                 hash, &hashBytes);
+ 
+@@ -12023,23 +12024,29 @@ ssl3_UnprotectRecord(sslSocket *ss,
+         /* always log mac error, in case attacker can read server logs. */
+         PORT_SetError(SSL_ERROR_BAD_MAC_READ);
+         *alert = bad_record_mac;
+         return SECFailure;
+     }
+     return SECSuccess;
+ }
+ 
+-static SECStatus
++SECStatus
+ ssl3_HandleNonApplicationData(sslSocket *ss, SSL3ContentType rType,
+                               DTLSEpoch epoch, sslSequenceNumber seqNum,
+                               sslBuffer *databuf)
+ {
+     SECStatus rv;
+ 
++    /* check for Token Presence */
++    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
++        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
++        return SECFailure;
++    }
++
+     ssl_GetSSL3HandshakeLock(ss);
+ 
+     /* All the functions called in this switch MUST set error code if
+     ** they return SECFailure or SECWouldBlock.
+     */
+     switch (rType) {
+         case content_change_cipher_spec:
+             rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
+@@ -12075,25 +12082,26 @@ ssl3_HandleNonApplicationData(sslSocket 
+ 
+ /* Find the cipher spec to use for a given record. For TLS, this
+  * is the current cipherspec. For DTLS, we look up by epoch.
+  * In DTLS < 1.3 this just means the current epoch or nothing,
+  * but in DTLS >= 1.3, we keep multiple reading cipherspecs.
+  * Returns NULL if no appropriate cipher spec is found.
+  */
+ static ssl3CipherSpec *
+-ssl3_GetCipherSpec(sslSocket *ss, sslSequenceNumber seq)
++ssl3_GetCipherSpec(sslSocket *ss, SSL3Ciphertext *cText)
+ {
+     ssl3CipherSpec *crSpec = ss->ssl3.crSpec;
+     ssl3CipherSpec *newSpec = NULL;
+-    DTLSEpoch epoch = seq >> 48;
++    DTLSEpoch epoch;
+ 
+     if (!IS_DTLS(ss)) {
+         return crSpec;
+     }
++    epoch = dtls_ReadEpoch(crSpec, cText->hdr);
+     if (crSpec->epoch == epoch) {
+         return crSpec;
+     }
+     if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+         /* Try to find the cipher spec. */
+         newSpec = ssl_FindCipherSpecByEpoch(ss, CipherSpecRead,
+                                             epoch);
+         if (newSpec != NULL) {
+@@ -12123,141 +12131,124 @@ ssl3_GetCipherSpec(sslSocket *ss, sslSeq
+  *
+  * Caller must hold the RecvBufLock.
+  *
+  * This function aquires and releases the SSL3Handshake Lock, holding the
+  * lock around any calls to functions that handle records other than
+  * Application Data records.
+  */
+ SECStatus
+-ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
++ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText)
+ {
+     SECStatus rv;
+     PRBool isTLS;
+     DTLSEpoch epoch;
+-    sslSequenceNumber seqNum = 0;
+     ssl3CipherSpec *spec = NULL;
+     PRBool outOfOrderSpec = PR_FALSE;
+     SSL3ContentType rType;
+-    sslBuffer *plaintext;
++    sslBuffer *plaintext = &ss->gs.buf;
+     SSL3AlertDescription alert = internal_error;
+     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ 
+     /* check for Token Presence */
+     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
+         PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
+         return SECFailure;
+     }
+ 
+-    /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
+-     * This implies that databuf holds a previously deciphered SSL Handshake
+-     * message.
+-     */
+-    if (cText == NULL) {
+-        SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
+-                 SSL_GETPID(), ss->fd));
+-        /* Note that this doesn't pass the epoch and sequence number of the
+-         * record through, which DTLS 1.3 depends on.  DTLS doesn't support
+-         * asynchronous certificate validation, so that should be OK. */
+-        PORT_Assert(!IS_DTLS(ss));
+-        return ssl3_HandleNonApplicationData(ss, content_handshake,
+-                                             0, 0, databuf);
+-    }
++    /* Clear out the buffer in case this exits early.  Any data then won't be
++     * processed twice. */
++    plaintext->len = 0;
+ 
+     ssl_GetSpecReadLock(ss); /******************************************/
+-    spec = ssl3_GetCipherSpec(ss, cText->seq_num);
++    spec = ssl3_GetCipherSpec(ss, cText);
+     if (!spec) {
+         PORT_Assert(IS_DTLS(ss));
+         ssl_ReleaseSpecReadLock(ss); /*****************************/
+-        databuf->len = 0;            /* Needed to ensure data not left around */
+         return SECSuccess;
+     }
+     if (spec != ss->ssl3.crSpec) {
+         PORT_Assert(IS_DTLS(ss));
+         SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d",
+                     SSL_GETPID(), ss->fd, spec->epoch));
+         outOfOrderSpec = PR_TRUE;
+     }
+     isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
+     if (IS_DTLS(ss)) {
+-        if (!dtls_IsRelevant(ss, spec, cText, &seqNum)) {
++        if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) {
+             ssl_ReleaseSpecReadLock(ss); /*****************************/
+-            databuf->len = 0;            /* Needed to ensure data not left around */
+-
+             return SECSuccess;
+         }
+     } else {
+-        seqNum = spec->seqNum + 1;
+-    }
+-    if (seqNum >= spec->cipherDef->max_records) {
++        cText->seqNum = spec->nextSeqNum;
++    }
++    if (cText->seqNum >= spec->cipherDef->max_records) {
+         ssl_ReleaseSpecReadLock(ss); /*****************************/
+         SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx",
+-                    SSL_GETPID(), ss->fd, seqNum));
++                    SSL_GETPID(), ss->fd, cText->seqNum));
+         PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
+         return SECFailure;
+     }
+ 
+-    plaintext = databuf;
+-    plaintext->len = 0; /* filled in by Unprotect call below. */
+-
+     /* We're waiting for another ClientHello, which will appear unencrypted.
+      * Use the content type to tell whether this is should be discarded.
+      *
+      * XXX If we decide to remove the content type from encrypted records, this
+      *     will become much more difficult to manage. */
+     if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr &&
+-        cText->type == content_application_data) {
++        cText->hdr[0] == content_application_data) {
+         ssl_ReleaseSpecReadLock(ss); /*****************************/
+         PORT_Assert(ss->ssl3.hs.ws == wait_client_hello);
+-        databuf->len = 0;
+         return SECSuccess;
+     }
+ 
+     if (plaintext->space < MAX_FRAGMENT_LENGTH) {
+         rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048);
+         if (rv != SECSuccess) {
+             ssl_ReleaseSpecReadLock(ss); /*************************/
+             SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
+                      SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048));
+             /* sslBuffer_Grow has set a memory error code. */
+             /* Perhaps we should send an alert. (but we have no memory!) */
+             return SECFailure;
+         }
+     }
+ 
+ #ifdef UNSAFE_FUZZER_MODE
++    rType = cText->hdr[0];
+     rv = Null_Cipher(NULL, plaintext->buf, (int *)&plaintext->len,
+                      plaintext->space, cText->buf->buf, cText->buf->len);
+ #else
+     /* IMPORTANT: Unprotect functions MUST NOT send alerts
+      * because we still hold the spec read lock. Instead, if they
+      * return SECFailure, they set *alert to the alert to be sent. */
+     if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3 ||
+         spec->cipherDef->calg == ssl_calg_null) {
+         /* Unencrypted TLS 1.3 records use the pre-TLS 1.3 format. */
++        rType = cText->hdr[0];
+         rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert);
+     } else {
+-        rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &alert);
++        rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType, &alert);
+     }
+ #endif
+ 
+     if (rv != SECSuccess) {
+         ssl_ReleaseSpecReadLock(ss); /***************************/
+ 
+         SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
+ 
+         /* Ensure that we don't process this data again. */
+-        databuf->len = 0;
++        plaintext->len = 0;
+ 
+         /* Ignore a CCS if the alternative handshake is negotiated.  Note that
+          * this will fail if the server fails to negotiate the alternative
+          * handshake type in a 0-RTT session that is resumed from a session that
+          * did negotiate it.  We don't care about that corner case right now. */
+         if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+-            cText->type == content_change_cipher_spec &&
++            cText->hdr[0] == content_change_cipher_spec &&
+             ss->ssl3.hs.ws != idle_handshake &&
+             cText->buf->len == 1 &&
+             cText->buf->buf[0] == change_cipher_spec_choice) {
+             /* Ignore the CCS. */
+             return SECSuccess;
+         }
+         if (IS_DTLS(ss) ||
+             (ss->sec.isServer &&
+@@ -12270,62 +12261,65 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Cip
+             /* Reset the error code in case SSL3_SendAlert called
+              * PORT_SetError(). */
+             PORT_SetError(errCode);
+             return SECFailure;
+         }
+     }
+ 
+     /* SECSuccess */
+-    spec->seqNum = PR_MAX(spec->seqNum, seqNum);
+     if (IS_DTLS(ss)) {
+-        dtls_RecordSetRecvd(&spec->recvdRecords, seqNum);
++        dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum);
++        spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1);
++    } else {
++        ++spec->nextSeqNum;
+     }
+     epoch = spec->epoch;
+ 
+     ssl_ReleaseSpecReadLock(ss); /*****************************************/
+ 
+     /*
+      * The decrypted data is now in plaintext.
+      */
+-    rType = cText->type; /* This must go after decryption because TLS 1.3
+-                          * has encrypted content types. */
+ 
+     /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something
+      * from the wrong epoch. Divert to a divert processing function to make
+      * sure we don't accidentally use the data unsafely. */
+     if (outOfOrderSpec) {
+         PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+-        return dtls13_HandleOutOfEpochRecord(ss, spec, rType, databuf);
++        return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext);
+     }
+ 
+     /* Check the length of the plaintext. */
+-    if (isTLS && databuf->len > MAX_FRAGMENT_LENGTH) {
++    if (isTLS && plaintext->len > MAX_FRAGMENT_LENGTH) {
++        plaintext->len = 0;
+         SSL3_SendAlert(ss, alert_fatal, record_overflow);
+         PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
+         return SECFailure;
+     }
+ 
+     /* Application data records are processed by the caller of this
+     ** function, not by this function.
+     */
+     if (rType == content_application_data) {
+         if (ss->firstHsDone)
+             return SECSuccess;
+         if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+             ss->sec.isServer &&
+             ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
+-            return tls13_HandleEarlyApplicationData(ss, databuf);
+-        }
++            return tls13_HandleEarlyApplicationData(ss, plaintext);
++        }
++        plaintext->len = 0;
+         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
+         return SECFailure;
+     }
+ 
+-    return ssl3_HandleNonApplicationData(ss, rType, epoch, seqNum, databuf);
++    return ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum,
++                                         plaintext);
+ }
+ 
+ /*
+  * Initialization functions
+  */
+ 
+ void
+ ssl_InitSecState(sslSecurityInfo *sec)
+diff --git a/security/nss/lib/ssl/ssl3gthr.c b/security/nss/lib/ssl/ssl3gthr.c
+--- a/security/nss/lib/ssl/ssl3gthr.c
++++ b/security/nss/lib/ssl/ssl3gthr.c
+@@ -153,16 +153,17 @@ ssl3_GatherData(sslSocket *ss, sslGather
+                  * Always assume v3 after we received the first record. */
+                 if (!ssl2gs ||
+                     ss->gs.rejectV2Records ||
+                     ssl3_isLikelyV3Hello(gs->hdr)) {
+                     /* Should have a non-SSLv2 record header in gs->hdr. Extract
+                      * the length of the following encrypted data, and then
+                      * read in the rest of the record into gs->inbuf. */
+                     gs->remainder = (gs->hdr[3] << 8) | gs->hdr[4];
++                    gs->hdrLen = SSL3_RECORD_HEADER_LENGTH;
+                 } else {
+                     /* Probably an SSLv2 record header. No need to handle any
+                      * security escapes (gs->hdr[0] & 0x40) as we wouldn't get
+                      * here if one was set. See ssl3_isLikelyV3Hello(). */
+                     gs->remainder = ((gs->hdr[0] & 0x7f) << 8) | gs->hdr[1];
+                     ssl2gs->isV2 = PR_TRUE;
+                     v2HdrLength = 2;
+ 
+@@ -259,18 +260,19 @@ ssl3_GatherData(sslSocket *ss, sslGather
+  *      (a) an error or EOF occurs,
+  *  (b) PR_WOULD_BLOCK_ERROR,
+  *  (c) data (entire DTLS record) has been received.
+  */
+ static int
+ dtls_GatherData(sslSocket *ss, sslGather *gs, int flags)
+ {
+     int nb;
+-    int err;
+-    int rv = 1;
++    PRUint8 contentType;
++    unsigned int headerLen;
++    SECStatus rv;
+ 
+     SSL_TRC(30, ("dtls_GatherData"));
+ 
+     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ 
+     gs->state = GS_HEADER;
+     gs->offset = 0;
+ 
+@@ -280,91 +282,107 @@ dtls_GatherData(sslSocket *ss, sslGather
+ 
+         /* Resize to the maximum possible size so we can fit a full datagram */
+         /* This is the max fragment length for an encrypted fragment
+         ** plus the size of the record header.
+         ** This magic constant is copied from ssl3_GatherData, with 5 changed
+         ** to 13 (the size of the record header).
+         */
+         if (gs->dtlsPacket.space < MAX_FRAGMENT_LENGTH + 2048 + 13) {
+-            err = sslBuffer_Grow(&gs->dtlsPacket,
+-                                 MAX_FRAGMENT_LENGTH + 2048 + 13);
+-            if (err) { /* realloc has set error code to no mem. */
+-                return err;
++            rv = sslBuffer_Grow(&gs->dtlsPacket,
++                                MAX_FRAGMENT_LENGTH + 2048 + 13);
++            if (rv != SECSuccess) {
++                return -1; /* Code already set. */
+             }
+         }
+ 
+         /* recv() needs to read a full datagram at a time */
+         nb = ssl_DefRecv(ss, gs->dtlsPacket.buf, gs->dtlsPacket.space, flags);
+-
+         if (nb > 0) {
+             PRINT_BUF(60, (ss, "raw gather data:", gs->dtlsPacket.buf, nb));
+         } else if (nb == 0) {
+             /* EOF */
+             SSL_TRC(30, ("%d: SSL3[%d]: EOF", SSL_GETPID(), ss->fd));
+-            rv = 0;
+-            return rv;
++            return 0;
+         } else /* if (nb < 0) */ {
+             SSL_DBG(("%d: SSL3[%d]: recv error %d", SSL_GETPID(), ss->fd,
+                      PR_GetError()));
+-            rv = SECFailure;
+-            return rv;
++            return -1;
+         }
+ 
+         gs->dtlsPacket.len = nb;
+     }
+ 
++    contentType = gs->dtlsPacket.buf[gs->dtlsPacketOffset];
++    if (dtls_IsLongHeader(ss->version, contentType)) {
++        headerLen = 13;
++    } else if (contentType == content_application_data) {
++        headerLen = 7;
++    } else if ((contentType & 0xe0) == 0x20) {
++        headerLen = 2;
++    } else {
++        SSL_DBG(("%d: SSL3[%d]: invalid first octet (%d) for DTLS",
++                 SSL_GETPID(), ss->fd, contentType));
++        PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
++        gs->dtlsPacketOffset = 0;
++        gs->dtlsPacket.len = 0;
++        return -1;
++    }
++
+     /* At this point we should have >=1 complete records lined up in
+      * dtlsPacket. Read off the header.
+      */
+-    if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < 13) {
++    if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < headerLen) {
+         SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet "
+                  "too short to contain header",
+                  SSL_GETPID(), ss->fd));
+-        PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
++        PORT_SetError(PR_WOULD_BLOCK_ERROR);
+         gs->dtlsPacketOffset = 0;
+         gs->dtlsPacket.len = 0;
+-        rv = SECFailure;
+-        return rv;
++        return -1;
+     }
+-    memcpy(gs->hdr, gs->dtlsPacket.buf + gs->dtlsPacketOffset, 13);
+-    gs->dtlsPacketOffset += 13;
++    memcpy(gs->hdr, SSL_BUFFER_BASE(&gs->dtlsPacket) + gs->dtlsPacketOffset,
++           headerLen);
++    gs->hdrLen = headerLen;
++    gs->dtlsPacketOffset += headerLen;
+ 
+     /* Have received SSL3 record header in gs->hdr. */
+-    gs->remainder = (gs->hdr[11] << 8) | gs->hdr[12];
++    if (headerLen == 13) {
++        gs->remainder = (gs->hdr[11] << 8) | gs->hdr[12];
++    } else if (headerLen == 7) {
++        gs->remainder = (gs->hdr[5] << 8) | gs->hdr[6];
++    } else {
++        PORT_Assert(headerLen = 2);
++        gs->remainder = gs->dtlsPacket.len - gs->dtlsPacketOffset;
++    }
+ 
+     if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < gs->remainder) {
+         SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet too short "
+                  "to contain rest of body",
+                  SSL_GETPID(), ss->fd));
+-        PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
++        PORT_SetError(PR_WOULD_BLOCK_ERROR);
+         gs->dtlsPacketOffset = 0;
+         gs->dtlsPacket.len = 0;
+-        rv = SECFailure;
+-        return rv;
++        return -1;
+     }
+ 
+     /* OK, we have at least one complete packet, copy into inbuf */
+-    if (gs->remainder > gs->inbuf.space) {
+-        err = sslBuffer_Grow(&gs->inbuf, gs->remainder);
+-        if (err) { /* realloc has set error code to no mem. */
+-            return err;
+-        }
++    gs->inbuf.len = 0;
++    rv = sslBuffer_Append(&gs->inbuf,
++                          SSL_BUFFER_BASE(&gs->dtlsPacket) + gs->dtlsPacketOffset,
++                          gs->remainder);
++    if (rv != SECSuccess) {
++        return -1; /* code already set. */
+     }
+-
+-    SSL_TRC(20, ("%d: SSL3[%d]: dtls gathered record type=%d len=%d",
+-                 SSL_GETPID(), ss->fd, gs->hdr[0], gs->inbuf.len));
+-
+-    memcpy(gs->inbuf.buf, gs->dtlsPacket.buf + gs->dtlsPacketOffset,
+-           gs->remainder);
+-    gs->inbuf.len = gs->remainder;
+     gs->offset = gs->remainder;
+     gs->dtlsPacketOffset += gs->remainder;
+     gs->state = GS_INIT;
+ 
++    SSL_TRC(20, ("%d: SSL3[%d]: dtls gathered record type=%d len=%d",
++                 SSL_GETPID(), ss->fd, contentType, gs->inbuf.len));
+     return 1;
+ }
+ 
+ /* Gather in a record and when complete, Handle that record.
+  * Repeat this until the handshake is complete,
+  * or until application data is available.
+  *
+  * Returns  1 when the handshake is completed without error, or
+@@ -437,17 +455,21 @@ ssl3_GatherCompleteHandshake(sslSocket *
+         ssl_ReleaseSSL3HandshakeLock(ss);
+ 
+         if (handleRecordNow) {
+             /* ssl3_HandleHandshake previously returned SECWouldBlock and the
+              * as-yet-unprocessed plaintext of that previous handshake record.
+              * We need to process it now before we overwrite it with the next
+              * handshake record.
+              */
+-            rv = ssl3_HandleRecord(ss, NULL, &ss->gs.buf);
++            SSL_DBG(("%d: SSL3[%d]: resuming handshake",
++                     SSL_GETPID(), ss->fd));
++            PORT_Assert(!IS_DTLS(ss));
++            rv = ssl3_HandleNonApplicationData(ss, content_handshake,
++                                               0, 0, &ss->gs.buf);
+         } else {
+             /* State for SSLv2 client hello support. */
+             ssl2Gather ssl2gs = { PR_FALSE, 0 };
+             ssl2Gather *ssl2gs_ptr = NULL;
+ 
+             /* If we're a server and waiting for a client hello, accept v2. */
+             if (ss->sec.isServer && ss->ssl3.hs.ws == wait_client_hello) {
+                 ssl2gs_ptr = &ssl2gs;
+@@ -490,42 +512,35 @@ ssl3_GatherCompleteHandshake(sslSocket *
+                 if (rv < 0) {
+                     return rv;
+                 }
+             } else {
+                 /* decipher it, and handle it if it's a handshake.
+                  * If it's application data, ss->gs.buf will not be empty upon return.
+                  * If it's a change cipher spec, alert, or handshake message,
+                  * ss->gs.buf.len will be 0 when ssl3_HandleRecord returns SECSuccess.
++                 *
++                 * cText only needs to be valid for this next function call, so
++                 * it can borrow gs.hdr.
+                  */
+-                cText.type = (SSL3ContentType)ss->gs.hdr[0];
+-                cText.version = (ss->gs.hdr[1] << 8) | ss->gs.hdr[2];
+-
+-                if (IS_DTLS(ss)) {
+-                    sslSequenceNumber seq_num;
+-
+-                    /* DTLS sequence number */
+-                    PORT_Memcpy(&seq_num, &ss->gs.hdr[3], sizeof(seq_num));
+-                    cText.seq_num = PR_ntohll(seq_num);
+-                }
+-
++                cText.hdr = ss->gs.hdr;
++                cText.hdrLen = ss->gs.hdrLen;
+                 cText.buf = &ss->gs.inbuf;
+-                rv = ssl3_HandleRecord(ss, &cText, &ss->gs.buf);
++                rv = ssl3_HandleRecord(ss, &cText);
+             }
+         }
+         if (rv < 0) {
+             return ss->recvdCloseNotify ? 0 : rv;
+         }
+         if (ss->gs.buf.len > 0) {
+             /* We have application data to return to the application. This
+              * prioritizes returning application data to the application over
+              * completing any renegotiation handshake we may be doing.
+              */
+             PORT_Assert(ss->firstHsDone);
+-            PORT_Assert(cText.type == content_application_data);
+             break;
+         }
+ 
+         PORT_Assert(keepGoing);
+         ssl_GetSSL3HandshakeLock(ss);
+         if (ss->ssl3.hs.ws == idle_handshake) {
+             /* We are done with the current handshake so stop trying to
+              * handshake. Note that it would be safe to test ss->firstHsDone
+diff --git a/security/nss/lib/ssl/ssl3prot.h b/security/nss/lib/ssl/ssl3prot.h
+--- a/security/nss/lib/ssl/ssl3prot.h
++++ b/security/nss/lib/ssl/ssl3prot.h
+@@ -11,17 +11,17 @@
+ #define __ssl3proto_h_
+ 
+ typedef PRUint16 SSL3ProtocolVersion;
+ /* version numbers are defined in sslproto.h */
+ 
+ /* The TLS 1.3 draft version. Used to avoid negotiating
+  * between incompatible pre-standard TLS 1.3 drafts.
+  * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */
+-#define TLS_1_3_DRAFT_VERSION 23
++#define TLS_1_3_DRAFT_VERSION 26
+ 
+ typedef PRUint16 ssl3CipherSuite;
+ /* The cipher suites are defined in sslproto.h */
+ 
+ #define MAX_CERT_TYPES 10
+ #define MAX_MAC_LENGTH 64
+ #define MAX_PADDING_LENGTH 64
+ #define MAX_KEY_LENGTH 64
+diff --git a/security/nss/lib/ssl/sslimpl.h b/security/nss/lib/ssl/sslimpl.h
+--- a/security/nss/lib/ssl/sslimpl.h
++++ b/security/nss/lib/ssl/sslimpl.h
+@@ -256,16 +256,17 @@ typedef struct sslOptionsStr {
+     unsigned int reuseServerECDHEKey : 1;
+     unsigned int enableFallbackSCSV : 1;
+     unsigned int enableServerDhe : 1;
+     unsigned int enableExtendedMS : 1;
+     unsigned int enableSignedCertTimestamps : 1;
+     unsigned int requireDHENamedGroups : 1;
+     unsigned int enable0RttData : 1;
+     unsigned int enableTls13CompatMode : 1;
++    unsigned int enableDtlsShortHeader : 1;
+ } sslOptions;
+ 
+ typedef enum { sslHandshakingUndetermined = 0,
+                sslHandshakingAsClient,
+                sslHandshakingAsServer
+ } sslHandshakingType;
+ 
+ #define SSL_LOCK_RANK_SPEC 255
+@@ -320,19 +321,21 @@ struct sslGatherStr {
+ 
+     /* Buffer for ssl3 to read (encrypted) data from the socket */
+     sslBuffer inbuf; /*recvBufLock*/
+ 
+     /* The ssl[23]_GatherData functions read data into this buffer, rather
+     ** than into buf or inbuf, while in the GS_HEADER state.
+     ** The portion of the SSL record header put here always comes off the wire
+     ** as plaintext, never ciphertext.
+-    ** For SSL3/TLS, the plaintext portion is 5 bytes long. For DTLS it is 13.
++    ** For SSL3/TLS, the plaintext portion is 5 bytes long. For DTLS it
++    ** varies based on version and header type.
+     */
+     unsigned char hdr[13];
++    unsigned int hdrLen;
+ 
+     /* Buffer for DTLS data read off the wire as a single datagram */
+     sslBuffer dtlsPacket;
+ 
+     /* the start of the buffered DTLS record in dtlsPacket */
+     unsigned int dtlsPacketOffset;
+ 
+     /* tracks whether we've seen a v3-type record before and must reject
+@@ -775,19 +778,23 @@ struct ssl3StateStr {
+ };
+ 
+ /* Ethernet MTU but without subtracting the headers,
+  * so slightly larger than expected */
+ #define DTLS_MAX_MTU 1500U
+ #define IS_DTLS(ss) (ss->protocolVariant == ssl_variant_datagram)
+ 
+ typedef struct {
+-    SSL3ContentType type;
+-    SSL3ProtocolVersion version;
+-    sslSequenceNumber seq_num; /* DTLS only */
++    /* |seqNum| eventually contains the reconstructed sequence number. */
++    sslSequenceNumber seqNum;
++    /* The header of the cipherText. */
++    const PRUint8 *hdr;
++    unsigned int hdrLen;
++
++    /* |buf| is the payload of the ciphertext. */
+     sslBuffer *buf;
+ } SSL3Ciphertext;
+ 
+ struct sslKeyPairStr {
+     SECKEYPrivateKey *privKey;
+     SECKEYPublicKey *pubKey;
+     PRInt32 refCount; /* use PR_Atomic calls for this. */
+ };
+@@ -1370,18 +1377,21 @@ extern SECStatus ssl3_AuthCertificateCom
+ extern SECStatus ssl3_HandleV2ClientHello(
+     sslSocket *ss, unsigned char *buffer, unsigned int length, PRUint8 padding);
+ 
+ SECStatus ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type);
+ 
+ /*
+  * input into the SSL3 machinery from the actualy network reading code
+  */
+-SECStatus ssl3_HandleRecord(
+-    sslSocket *ss, SSL3Ciphertext *cipher, sslBuffer *out);
++SECStatus ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cipher);
++SECStatus ssl3_HandleNonApplicationData(sslSocket *ss, SSL3ContentType rType,
++                                        DTLSEpoch epoch,
++                                        sslSequenceNumber seqNum,
++                                        sslBuffer *databuf);
+ SECStatus ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize);
+ 
+ int ssl3_GatherAppDataRecord(sslSocket *ss, int flags);
+ int ssl3_GatherCompleteHandshake(sslSocket *ss, int flags);
+ 
+ /* Create a new ref counted key pair object from two keys. */
+ extern sslKeyPair *ssl_NewKeyPair(SECKEYPrivateKey *privKey,
+                                   SECKEYPublicKey *pubKey);
+@@ -1631,16 +1641,19 @@ SECStatus ssl_PickSignatureScheme(sslSoc
+                                   const SSLSignatureScheme *peerSchemes,
+                                   unsigned int peerSchemeCount,
+                                   PRBool requireSha1);
+ SECOidTag ssl3_HashTypeToOID(SSLHashType hashType);
+ SSLHashType ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme);
+ KeyType ssl_SignatureSchemeToKeyType(SSLSignatureScheme scheme);
+ 
+ SECStatus ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes);
++SECStatus ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
++                                 SSL3ContentType contentType, sslBuffer *wrBuf,
++                                 PRBool *needsLength);
+ 
+ /* Pull in DTLS functions */
+ #include "dtlscon.h"
+ 
+ /* Pull in TLS 1.3 functions */
+ #include "tls13con.h"
+ #include "dtls13con.h"
+ 
+diff --git a/security/nss/lib/ssl/sslsecur.c b/security/nss/lib/ssl/sslsecur.c
+--- a/security/nss/lib/ssl/sslsecur.c
++++ b/security/nss/lib/ssl/sslsecur.c
+@@ -786,17 +786,17 @@ tls13_CheckKeyUpdate(sslSocket *ss, Ciph
+     ssl_GetSpecReadLock(ss);
+     if (dir == CipherSpecRead) {
+         spec = ss->ssl3.crSpec;
+         margin = spec->cipherDef->max_records / 8;
+     } else {
+         spec = ss->ssl3.cwSpec;
+         margin = spec->cipherDef->max_records / 4;
+     }
+-    seqNum = spec->seqNum;
++    seqNum = spec->nextSeqNum;
+     keyUpdate = seqNum > spec->cipherDef->max_records - margin;
+     ssl_ReleaseSpecReadLock(ss);
+     if (!keyUpdate) {
+         return SECSuccess;
+     }
+ 
+     SSL_TRC(5, ("%d: SSL[%d]: automatic key update at %llx for %s cipher spec",
+                 SSL_GETPID(), ss->fd, seqNum,
+diff --git a/security/nss/lib/ssl/sslsock.c b/security/nss/lib/ssl/sslsock.c
+--- a/security/nss/lib/ssl/sslsock.c
++++ b/security/nss/lib/ssl/sslsock.c
+@@ -76,17 +76,18 @@ static sslOptions ssl_defaults = {
+     .enableALPN = PR_TRUE,
+     .reuseServerECDHEKey = PR_TRUE,
+     .enableFallbackSCSV = PR_FALSE,
+     .enableServerDhe = PR_TRUE,
+     .enableExtendedMS = PR_FALSE,
+     .enableSignedCertTimestamps = PR_FALSE,
+     .requireDHENamedGroups = PR_FALSE,
+     .enable0RttData = PR_FALSE,
+-    .enableTls13CompatMode = PR_FALSE
++    .enableTls13CompatMode = PR_FALSE,
++    .enableDtlsShortHeader = PR_FALSE
+ };
+ 
+ /*
+  * default range of enabled SSL/TLS protocols
+  */
+ static SSLVersionRange versions_defaults_stream = {
+     SSL_LIBRARY_VERSION_TLS_1_0,
+     SSL_LIBRARY_VERSION_TLS_1_2
+@@ -802,16 +803,20 @@ SSL_OptionSet(PRFileDesc *fd, PRInt32 wh
+         case SSL_ENABLE_0RTT_DATA:
+             ss->opt.enable0RttData = val;
+             break;
+ 
+         case SSL_ENABLE_TLS13_COMPAT_MODE:
+             ss->opt.enableTls13CompatMode = val;
+             break;
+ 
++        case SSL_ENABLE_DTLS_SHORT_HEADER:
++            ss->opt.enableDtlsShortHeader = val;
++            break;
++
+         default:
+             PORT_SetError(SEC_ERROR_INVALID_ARGS);
+             rv = SECFailure;
+     }
+ 
+     /* We can't use the macros for releasing the locks here,
+      * because ss->opt.noLocks might have changed just above.
+      * We must release these locks (monitors) here, if we aquired them above,
+@@ -938,16 +943,19 @@ SSL_OptionGet(PRFileDesc *fd, PRInt32 wh
+             val = ss->opt.requireDHENamedGroups;
+             break;
+         case SSL_ENABLE_0RTT_DATA:
+             val = ss->opt.enable0RttData;
+             break;
+         case SSL_ENABLE_TLS13_COMPAT_MODE:
+             val = ss->opt.enableTls13CompatMode;
+             break;
++        case SSL_ENABLE_DTLS_SHORT_HEADER:
++            val = ss->opt.enableDtlsShortHeader;
++            break;
+         default:
+             PORT_SetError(SEC_ERROR_INVALID_ARGS);
+             rv = SECFailure;
+     }
+ 
+     ssl_ReleaseSSL3HandshakeLock(ss);
+     ssl_Release1stHandshakeLock(ss);
+ 
+@@ -1058,16 +1066,19 @@ SSL_OptionGetDefault(PRInt32 which, PRIn
+             val = ssl_defaults.enableSignedCertTimestamps;
+             break;
+         case SSL_ENABLE_0RTT_DATA:
+             val = ssl_defaults.enable0RttData;
+             break;
+         case SSL_ENABLE_TLS13_COMPAT_MODE:
+             val = ssl_defaults.enableTls13CompatMode;
+             break;
++        case SSL_ENABLE_DTLS_SHORT_HEADER:
++            val = ssl_defaults.enableDtlsShortHeader;
++            break;
+         default:
+             PORT_SetError(SEC_ERROR_INVALID_ARGS);
+             rv = SECFailure;
+     }
+ 
+     *pVal = val;
+     return rv;
+ }
+@@ -1241,16 +1252,20 @@ SSL_OptionSetDefault(PRInt32 which, PRIn
+         case SSL_ENABLE_0RTT_DATA:
+             ssl_defaults.enable0RttData = val;
+             break;
+ 
+         case SSL_ENABLE_TLS13_COMPAT_MODE:
+             ssl_defaults.enableTls13CompatMode = val;
+             break;
+ 
++        case SSL_ENABLE_DTLS_SHORT_HEADER:
++            ssl_defaults.enableDtlsShortHeader = val;
++            break;
++
+         default:
+             PORT_SetError(SEC_ERROR_INVALID_ARGS);
+             return SECFailure;
+     }
+     return SECSuccess;
+ }
+ 
+ SECStatus
+diff --git a/security/nss/lib/ssl/sslspec.h b/security/nss/lib/ssl/sslspec.h
+--- a/security/nss/lib/ssl/sslspec.h
++++ b/security/nss/lib/ssl/sslspec.h
+@@ -157,17 +157,19 @@ struct ssl3CipherSpecStr {
+     SSLAEADCipher aead;
+     void *cipherContext;
+ 
+     PK11SymKey *masterSecret;
+     ssl3KeyMaterial keyMaterial;
+ 
+     DTLSEpoch epoch;
+     const char *phase;
+-    sslSequenceNumber seqNum;
++
++    /* The next sequence number to be sent or received. */
++    sslSequenceNumber nextSeqNum;
+     DTLSRecvdRecords recvdRecords;
+ 
+     /* The number of 0-RTT bytes that can be sent or received in TLS 1.3. This
+      * will be zero for everything but 0-RTT. */
+     PRUint32 earlyDataRemaining;
+ };
+ 
+ typedef void (*sslCipherSpecChangedFunc)(void *arg,
+diff --git a/security/nss/lib/ssl/tls13con.c b/security/nss/lib/ssl/tls13con.c
+--- a/security/nss/lib/ssl/tls13con.c
++++ b/security/nss/lib/ssl/tls13con.c
+@@ -787,17 +787,17 @@ tls13_HandleKeyUpdate(sslSocket *ss, PRU
+     }
+ 
+     if (update == update_requested) {
+         PRBool sendUpdate;
+         if (ss->ssl3.peerRequestedKeyUpdate) {
+             /* Only send an update if we have sent with the current spec.  This
+              * prevents us from being forced to crank forward pointlessly. */
+             ssl_GetSpecReadLock(ss);
+-            sendUpdate = ss->ssl3.cwSpec->seqNum > 0;
++            sendUpdate = ss->ssl3.cwSpec->nextSeqNum > 0;
+             ssl_ReleaseSpecReadLock(ss);
+         } else {
+             sendUpdate = PR_TRUE;
+         }
+         if (sendUpdate) {
+             /* Respond immediately (don't buffer). */
+             rv = tls13_SendKeyUpdate(ss, update_not_requested, PR_FALSE);
+             if (rv != SECSuccess) {
+@@ -1615,17 +1615,17 @@ tls13_HandleClientHelloPart2(sslSocket *
+          * we generate are sent with the right sequence numbers. */
+         if (IS_DTLS(ss)) {
+             /* Count the first ClientHello and the HelloRetryRequest. */
+             ss->ssl3.hs.sendMessageSeq = 1;
+             ss->ssl3.hs.recvMessageSeq = 1;
+             ssl_GetSpecWriteLock(ss);
+             /* Increase the write sequence number.  The read sequence number
+              * will be reset after this to early data or handshake. */
+-            ss->ssl3.cwSpec->seqNum = 1;
++            ss->ssl3.cwSpec->nextSeqNum = 1;
+             ssl_ReleaseSpecWriteLock(ss);
+         }
+ 
+         if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_cookie_xtn) ||
+             !ss->xtnData.cookie.len) {
+             FATAL_ERROR(ss, SSL_ERROR_MISSING_COOKIE_EXTENSION,
+                         missing_extension);
+             goto loser;
+@@ -2002,17 +2002,17 @@ tls13_SendHelloRetryRequest(sslSocket *s
+         rv = ssl3_FlushHandshake(ss, 0);
+         if (rv != SECSuccess) {
+             goto loser; /* error code set by ssl3_FlushHandshake */
+         }
+     }
+ 
+     /* We depend on this being exactly one record and one message. */
+     PORT_Assert(!IS_DTLS(ss) || (ss->ssl3.hs.sendMessageSeq == 1 &&
+-                                 ss->ssl3.cwSpec->seqNum == 1));
++                                 ss->ssl3.cwSpec->nextSeqNum == 1));
+     ssl_ReleaseXmitBufLock(ss);
+ 
+     ss->ssl3.hs.helloRetry = PR_TRUE;
+ 
+     /* We received early data but have to ignore it because we sent a retry. */
+     if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
+         ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
+         ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_hrr;
+@@ -2204,16 +2204,18 @@ tls13_HandleHelloRetryRequest(sslSocket 
+         ssl_CipherSpecRelease(ss->ssl3.cwSpec);
+         ss->ssl3.cwSpec = ssl_FindCipherSpecByEpoch(ss, CipherSpecWrite,
+                                                     TrafficKeyClearText);
+         PORT_Assert(ss->ssl3.cwSpec);
+         ssl_ReleaseSpecWriteLock(ss);
+     } else {
+         PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none);
+     }
++    /* Set the spec version, because we want to send CH now with 0303 */
++    tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
+ 
+     /* Extensions must contain more than just supported_versions.  This will
+      * ensure that a HelloRetryRequest isn't a no-op: we must have at least two
+      * extensions, supported_versions plus one other.  That other must be one
+      * that we understand and recognize as being valid for HelloRetryRequest,
+      * and all the extensions we permit cause us to modify our second
+      * ClientHello in some meaningful way. */
+     if (ssl_ListCount(&ss->ssl3.hs.remoteExtensions) <= 1) {
+@@ -2243,16 +2245,17 @@ tls13_HandleHelloRetryRequest(sslSocket 
+     ssl_GetXmitBufLock(ss);
+     if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss) &&
+         ss->ssl3.hs.zeroRttState == ssl_0rtt_none) {
+         rv = ssl3_SendChangeCipherSpecsInt(ss);
+         if (rv != SECSuccess) {
+             goto loser;
+         }
+     }
++
+     rv = ssl3_SendClientHello(ss, client_hello_retry);
+     if (rv != SECSuccess) {
+         goto loser;
+     }
+ 
+     ssl_ReleaseXmitBufLock(ss);
+     return SECSuccess;
+ 
+@@ -3311,17 +3314,17 @@ tls13_SetCipherSpec(sslSocket *ss, PRUin
+     }
+ 
+     /* Create the new spec. */
+     spec = ssl_CreateCipherSpec(ss, direction);
+     if (!spec) {
+         return SECFailure;
+     }
+     spec->epoch = epoch;
+-    spec->seqNum = 0;
++    spec->nextSeqNum = 0;
+     if (IS_DTLS(ss)) {
+         dtls_InitRecvdRecords(&spec->recvdRecords);
+     }
+ 
+     /* This depends on spec having a valid direction and epoch. */
+     rv = tls13_SetupPendingCipherSpec(ss, spec);
+     if (rv != SECSuccess) {
+         goto loser;
+@@ -3531,48 +3534,50 @@ tls13_AESGCM(ssl3KeyMaterial *keys,
+              const unsigned char *in,
+              int inlen,
+              const unsigned char *additionalData,
+              int additionalDataLen)
+ {
+     CK_GCM_PARAMS gcmParams;
+     unsigned char nonce[12];
+ 
++    PORT_Assert(additionalDataLen > 8);
+     memset(&gcmParams, 0, sizeof(gcmParams));
+     gcmParams.pIv = nonce;
+     gcmParams.ulIvLen = sizeof(nonce);
+-    gcmParams.pAAD = NULL;
+-    gcmParams.ulAADLen = 0;
++    gcmParams.pAAD = (PRUint8 *)(additionalData + 8);
++    gcmParams.ulAADLen = additionalDataLen - 8;
+     gcmParams.ulTagBits = 128; /* GCM measures tag length in bits. */
+ 
+-    tls13_WriteNonce(keys, additionalData, additionalDataLen,
++    tls13_WriteNonce(keys, additionalData, 8,
+                      nonce, sizeof(nonce));
+     return tls13_AEAD(keys, doDecrypt, out, outlen, maxout, in, inlen,
+                       CKM_AES_GCM,
+                       (unsigned char *)&gcmParams, sizeof(gcmParams));
+ }
+ 
+ static SECStatus
+ tls13_ChaCha20Poly1305(ssl3KeyMaterial *keys, PRBool doDecrypt,
+                        unsigned char *out, int *outlen, int maxout,
+                        const unsigned char *in, int inlen,
+                        const unsigned char *additionalData,
+                        int additionalDataLen)
+ {
+     CK_NSS_AEAD_PARAMS aeadParams;
+     unsigned char nonce[12];
+ 
++    PORT_Assert(additionalDataLen > 8);
+     memset(&aeadParams, 0, sizeof(aeadParams));
+     aeadParams.pNonce = nonce;
+     aeadParams.ulNonceLen = sizeof(nonce);
+-    aeadParams.pAAD = NULL; /* No AAD in TLS 1.3. */
+-    aeadParams.ulAADLen = 0;
++    aeadParams.pAAD = (PRUint8 *)(additionalData + 8);
++    aeadParams.ulAADLen = additionalDataLen - 8;
+     aeadParams.ulTagLen = 16; /* The Poly1305 tag is 16 octets. */
+ 
+-    tls13_WriteNonce(keys, additionalData, additionalDataLen,
++    tls13_WriteNonce(keys, additionalData, 8,
+                      nonce, sizeof(nonce));
+     return tls13_AEAD(keys, doDecrypt, out, outlen, maxout, in, inlen,
+                       CKM_NSS_CHACHA20_POLY1305,
+                       (unsigned char *)&aeadParams, sizeof(aeadParams));
+ }
+ 
+ static SECStatus
+ tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b, PRUint32 length)
+@@ -4775,39 +4780,48 @@ tls13_ExtensionStatus(PRUint16 extension
+     return tls13_extension_allowed;
+ }
+ 
+ #undef _M
+ #undef _M1
+ #undef _M2
+ #undef _M3
+ 
+-/* TLS 1.3 doesn't actually have additional data but the aead function
+- * signature overloads additional data to carry the record sequence
+- * number and that's what we put here. The TLS 1.3 AEAD functions
+- * just use this input as the sequence number and not as additional
+- * data. */
++/* We cheat a bit on additional data because the AEAD interface
++ * which doesn't have room for the record number. The AAD we
++ * format is serialized record number followed by the true AD
++ * (i.e., the record header) plus the serialized record number. */
+ static SECStatus
+-tls13_FormatAdditionalData(sslSocket *ss, PRUint8 *aad, unsigned int length,
+-                           DTLSEpoch epoch, sslSequenceNumber seqNum)
++tls13_FormatAdditionalData(
++    sslSocket *ss,
++    const PRUint8 *header, unsigned int headerLen,
++    DTLSEpoch epoch, sslSequenceNumber seqNum,
++    PRUint8 *aad, unsigned int *aadLength, unsigned int maxLength)
+ {
+     SECStatus rv;
+-    sslBuffer buf = SSL_BUFFER_FIXED(aad, length);
+-
+-    PORT_Assert(length == 8);
++    sslBuffer buf = SSL_BUFFER_FIXED(aad, maxLength);
++
+     if (IS_DTLS(ss)) {
+         rv = sslBuffer_AppendNumber(&buf, epoch, 2);
+         if (rv != SECSuccess) {
+             return SECFailure;
+         }
+     }
+     rv = sslBuffer_AppendNumber(&buf, seqNum, IS_DTLS(ss) ? 6 : 8);
+     if (rv != SECSuccess) {
+         return SECFailure;
+     }
++
++    rv = sslBuffer_Append(&buf, header, headerLen);
++    if (rv != SECSuccess) {
++        return SECFailure;
++    }
++
++    *aadLength = buf.len;
++
+     return SECSuccess;
+ }
+ 
+ PRInt32
+ tls13_LimitEarlyData(sslSocket *ss, SSL3ContentType type, PRInt32 toSend)
+ {
+     PRInt32 reduced;
+ 
+@@ -4838,53 +4852,78 @@ tls13_ProtectRecord(sslSocket *ss,
+ {
+     const ssl3BulkCipherDef *cipher_def = cwSpec->cipherDef;
+     const int tagLen = cipher_def->tag_size;
+     SECStatus rv;
+ 
+     PORT_Assert(cwSpec->direction == CipherSpecWrite);
+     SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) protect 0x%0llx len=%u",
+                 SSL_GETPID(), ss->fd, cwSpec, cwSpec->epoch, cwSpec->phase,
+-                cwSpec->seqNum, contentLen));
+-
+-    if (contentLen + 1 + tagLen > wrBuf->space) {
++                cwSpec->nextSeqNum, contentLen));
++
++    if (contentLen + 1 + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
+         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+         return SECFailure;
+     }
+ 
+     /* Copy the data into the wrBuf. We're going to encrypt in-place
+      * in the AEAD branch anyway */
+-    PORT_Memcpy(wrBuf->buf, pIn, contentLen);
++    PORT_Memcpy(SSL_BUFFER_NEXT(wrBuf), pIn, contentLen);
+ 
+     if (cipher_def->calg == ssl_calg_null) {
+         /* Shortcut for plaintext */
+-        wrBuf->len = contentLen;
++        rv = sslBuffer_Skip(wrBuf, contentLen, NULL);
++        PORT_Assert(rv == SECSuccess);
+     } else {
+-        PRUint8 aad[8];
++        PRUint8 hdr[13];
++        sslBuffer buf = SSL_BUFFER_FIXED(hdr, sizeof(hdr));
++        PRBool needsLength;
++        PRUint8 aad[21];
++        unsigned int aadLen;
++        int len;
++
+         PORT_Assert(cipher_def->type == type_aead);
+ 
+         /* Add the content type at the end. */
+-        wrBuf->buf[contentLen] = type;
+-
+-        rv = tls13_FormatAdditionalData(ss, aad, sizeof(aad), cwSpec->epoch,
+-                                        cwSpec->seqNum);
++        *(SSL_BUFFER_NEXT(wrBuf) + contentLen) = type;
++
++        /* Create the header (ugly that we have to do it twice). */
++        rv = ssl_InsertRecordHeader(ss, cwSpec, content_application_data,
++                                    &buf, &needsLength);
++        if (rv != SECSuccess) {
++            return SECFailure;
++        }
++        if (needsLength) {
++            rv = sslBuffer_AppendNumber(&buf, contentLen + 1 +
++                                                  cwSpec->cipherDef->tag_size,
++                                        2);
++            if (rv != SECSuccess) {
++                return SECFailure;
++            }
++        }
++        rv = tls13_FormatAdditionalData(ss, SSL_BUFFER_BASE(&buf), SSL_BUFFER_LEN(&buf),
++                                        cwSpec->epoch, cwSpec->nextSeqNum,
++                                        aad, &aadLen, sizeof(aad));
+         if (rv != SECSuccess) {
+             return SECFailure;
+         }
+         rv = cwSpec->aead(&cwSpec->keyMaterial,
+-                          PR_FALSE,                   /* do encrypt */
+-                          wrBuf->buf,                 /* output  */
+-                          (int *)&wrBuf->len,         /* out len */
+-                          wrBuf->space,               /* max out */
+-                          wrBuf->buf, contentLen + 1, /* input   */
+-                          aad, sizeof(aad));
++                          PR_FALSE,                /* do encrypt */
++                          SSL_BUFFER_NEXT(wrBuf),  /* output  */
++                          &len,                    /* out len */
++                          SSL_BUFFER_SPACE(wrBuf), /* max out */
++                          SSL_BUFFER_NEXT(wrBuf),  /* input */
++                          contentLen + 1,          /* input len */
++                          aad, aadLen);
+         if (rv != SECSuccess) {
+             PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
+             return SECFailure;
+         }
++        rv = sslBuffer_Skip(wrBuf, len, NULL);
++        PORT_Assert(rv == SECSuccess);
+     }
+ 
+     return SECSuccess;
+ }
+ 
+ /* Unprotect a TLS 1.3 record and leave the result in plaintext.
+  *
+  * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
+@@ -4892,79 +4931,86 @@ tls13_ProtectRecord(sslSocket *ss,
+  *
+  * If SECFailure is returned, we:
+  * 1. Set |*alert| to the alert to be sent.
+  * 2. Call PORT_SetError() witn an appropriate code.
+  */
+ SECStatus
+ tls13_UnprotectRecord(sslSocket *ss,
+                       ssl3CipherSpec *spec,
+-                      SSL3Ciphertext *cText, sslBuffer *plaintext,
++                      SSL3Ciphertext *cText,
++                      sslBuffer *plaintext,
++                      SSL3ContentType *innerType,
+                       SSL3AlertDescription *alert)
+ {
+     const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
+-    sslSequenceNumber seqNum;
+-    PRUint8 aad[8];
++    PRUint8 aad[21];
++    unsigned int aadLen;
+     SECStatus rv;
+ 
+     *alert = bad_record_mac; /* Default alert for most issues. */
+ 
+     PORT_Assert(spec->direction == CipherSpecRead);
+-    if (IS_DTLS(ss)) {
+-        seqNum = cText->seq_num & RECORD_SEQ_MASK;
+-    } else {
+-        seqNum = spec->seqNum;
+-    }
+     SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) unprotect 0x%0llx len=%u",
+-                SSL_GETPID(), ss->fd, spec, spec->epoch, spec->phase, seqNum,
+-                cText->buf->len));
++                SSL_GETPID(), ss->fd, spec, spec->epoch, spec->phase,
++                cText->seqNum, cText->buf->len));
+ 
+     /* We can perform this test in variable time because the record's total
+      * length and the ciphersuite are both public knowledge. */
+     if (cText->buf->len < cipher_def->tag_size) {
+         SSL_TRC(3,
+                 ("%d: TLS13[%d]: record too short to contain valid AEAD data",
+                  SSL_GETPID(), ss->fd));
+         PORT_SetError(SSL_ERROR_BAD_MAC_READ);
+         return SECFailure;
+     }
+ 
+-    /* Verify that the content type is right, even though we overwrite it. */
+-    if (cText->type != content_application_data) {
++    /* Verify that the content type is right, even though we overwrite it.
++     * Also allow the DTLS short header in TLS 1.3. */
++    if (!(cText->hdr[0] == content_application_data ||
++          (IS_DTLS(ss) &&
++           ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
++           (cText->hdr[0] & 0xe0) == 0x20))) {
+         SSL_TRC(3,
+-                ("%d: TLS13[%d]: record has invalid exterior content type=%d",
+-                 SSL_GETPID(), ss->fd, cText->type));
++                ("%d: TLS13[%d]: record has invalid exterior type=%2.2x",
++                 SSL_GETPID(), ss->fd, cText->hdr[0]));
+         /* Do we need a better error here? */
+         PORT_SetError(SSL_ERROR_BAD_MAC_READ);
+         return SECFailure;
+     }
+ 
+-    /* Check the version number in the record. */
+-    if (cText->version != spec->recordVersion) {
+-        /* Do we need a better error here? */
+-        SSL_TRC(3,
+-                ("%d: TLS13[%d]: record has bogus version",
+-                 SSL_GETPID(), ss->fd));
+-        return SECFailure;
++    /* Check the version number in the record. Stream only. */
++    if (!IS_DTLS(ss)) {
++        SSL3ProtocolVersion version =
++            ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
++            (SSL3ProtocolVersion)cText->hdr[2];
++        if (version != spec->recordVersion) {
++            /* Do we need a better error here? */
++            SSL_TRC(3, ("%d: TLS13[%d]: record has bogus version",
++                        SSL_GETPID(), ss->fd));
++            return SECFailure;
++        }
+     }
+ 
+     /* Decrypt */
+     PORT_Assert(cipher_def->type == type_aead);
+-    rv = tls13_FormatAdditionalData(ss, aad, sizeof(aad), spec->epoch, seqNum);
++    rv = tls13_FormatAdditionalData(ss, cText->hdr, cText->hdrLen,
++                                    spec->epoch, cText->seqNum,
++                                    aad, &aadLen, sizeof(aad));
+     if (rv != SECSuccess) {
+         return SECFailure;
+     }
+     rv = spec->aead(&spec->keyMaterial,
+                     PR_TRUE,                /* do decrypt */
+                     plaintext->buf,         /* out */
+                     (int *)&plaintext->len, /* outlen */
+                     plaintext->space,       /* maxout */
+                     cText->buf->buf,        /* in */
+                     cText->buf->len,        /* inlen */
+-                    aad, sizeof(aad));
++                    aad, aadLen);
+     if (rv != SECSuccess) {
+         SSL_TRC(3,
+                 ("%d: TLS13[%d]: record has bogus MAC",
+                  SSL_GETPID(), ss->fd));
+         PORT_SetError(SSL_ERROR_BAD_MAC_READ);
+         return SECFailure;
+     }
+ 
+@@ -4972,44 +5018,41 @@ tls13_UnprotectRecord(sslSocket *ss,
+      * content type, so read from the right until we receive a
+      * nonzero byte. */
+     while (plaintext->len > 0 && !(plaintext->buf[plaintext->len - 1])) {
+         --plaintext->len;
+     }
+ 
+     /* Bogus padding. */
+     if (plaintext->len < 1) {
+-        SSL_TRC(3,
+-                ("%d: TLS13[%d]: empty record",
+-                 SSL_GETPID(), ss->fd, cText->type));
++        SSL_TRC(3, ("%d: TLS13[%d]: empty record", SSL_GETPID(), ss->fd));
+         /* It's safe to report this specifically because it happened
+          * after the MAC has been verified. */
+         PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING);
+         return SECFailure;
+     }
+ 
+     /* Record the type. */
+-    cText->type = plaintext->buf[plaintext->len - 1];
++    *innerType = (SSL3ContentType)plaintext->buf[plaintext->len - 1];
+     --plaintext->len;
+ 
+     /* Check that we haven't received too much 0-RTT data. */
+     if (spec->epoch == TrafficKeyEarlyApplicationData &&
+-        cText->type == content_application_data) {
++        *innerType == content_application_data) {
+         if (plaintext->len > spec->earlyDataRemaining) {
+             *alert = unexpected_message;
+             PORT_SetError(SSL_ERROR_TOO_MUCH_EARLY_DATA);
+             return SECFailure;
+         }
+         spec->earlyDataRemaining -= plaintext->len;
+     }
+ 
+     SSL_TRC(10,
+-            ("%d: TLS13[%d]: %s received record of length=%d type=%d",
+-             SSL_GETPID(), ss->fd, SSL_ROLE(ss),
+-             plaintext->len, cText->type));
++            ("%d: TLS13[%d]: %s received record of length=%d, type=%d",
++             SSL_GETPID(), ss->fd, SSL_ROLE(ss), plaintext->len, *innerType));
+ 
+     return SECSuccess;
+ }
+ 
+ /* 0-RTT is only permitted if:
+  *
+  * 1. We are doing TLS 1.3
+  * 2. This isn't a second ClientHello (in response to HelloRetryRequest)
+@@ -5222,16 +5265,68 @@ tls13_EncodeDraftVersion(SSL3ProtocolVer
+ #ifdef TLS_1_3_DRAFT_VERSION
+     if (version == SSL_LIBRARY_VERSION_TLS_1_3) {
+         return 0x7f00 | TLS_1_3_DRAFT_VERSION;
+     }
+ #endif
+     return (PRUint16)version;
+ }
+ 
++SECStatus
++tls13_ClientReadSupportedVersion(sslSocket *ss)
++{
++    PRUint32 temp;
++    SSL3ProtocolVersion v;
++    TLSExtension *versionExtension;
++    SECItem it;
++    SECStatus rv;
++
++    /* Update the version based on the extension, as necessary. */
++    versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
++    if (!versionExtension) {
++        return SECSuccess;
++    }
++
++    /* Struct copy so we don't damage the extension. */
++    it = versionExtension->data;
++
++    rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, &it.data, &it.len);
++    if (rv != SECSuccess) {
++        return SECFailure;
++    }
++    if (it.len) {
++        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
++        return SECFailure;
++    }
++    v = (SSL3ProtocolVersion)temp;
++
++    /* You cannot negotiate < TLS 1.3 with supported_versions. */
++    if (v < SSL_LIBRARY_VERSION_TLS_1_3) {
++        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
++        return SECFailure;
++    }
++
++#ifdef TLS_1_3_DRAFT_VERSION
++    if (temp == SSL_LIBRARY_VERSION_TLS_1_3) {
++        FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version);
++        return SECFailure;
++    }
++    if (temp == tls13_EncodeDraftVersion(SSL_LIBRARY_VERSION_TLS_1_3)) {
++        v = SSL_LIBRARY_VERSION_TLS_1_3;
++    } else {
++        v = (SSL3ProtocolVersion)temp;
++    }
++#else
++    v = (SSL3ProtocolVersion)temp;
++#endif
++
++    ss->version = v;
++    return SECSuccess;
++}
++
+ /* Pick the highest version we support that is also advertised. */
+ SECStatus
+ tls13_NegotiateVersion(sslSocket *ss, const TLSExtension *supportedVersions)
+ {
+     PRUint16 version;
+     /* Make a copy so we're nondestructive. */
+     SECItem data = supportedVersions->data;
+     SECItem versions;
+diff --git a/security/nss/lib/ssl/tls13con.h b/security/nss/lib/ssl/tls13con.h
+--- a/security/nss/lib/ssl/tls13con.h
++++ b/security/nss/lib/ssl/tls13con.h
+@@ -23,16 +23,17 @@ typedef enum {
+     update_requested = 1
+ } tls13KeyUpdateRequest;
+ 
+ #define TLS13_MAX_FINISHED_SIZE 64
+ 
+ SECStatus tls13_UnprotectRecord(
+     sslSocket *ss, ssl3CipherSpec *spec,
+     SSL3Ciphertext *cText, sslBuffer *plaintext,
++    SSL3ContentType *innerType,
+     SSL3AlertDescription *alert);
+ 
+ #if defined(WIN32)
+ #define __func__ __FUNCTION__
+ #endif
+ 
+ void tls13_SetHsState(sslSocket *ss, SSL3WaitState ws,
+                       const char *func, const char *file, int line);
+@@ -96,16 +97,17 @@ SECStatus tls13_ProtectRecord(sslSocket 
+                               SSL3ContentType type,
+                               const PRUint8 *pIn,
+                               PRUint32 contentLen,
+                               sslBuffer *wrBuf);
+ PRInt32 tls13_Read0RttData(sslSocket *ss, void *buf, PRInt32 len);
+ SECStatus tls13_HandleEarlyApplicationData(sslSocket *ss, sslBuffer *origBuf);
+ PRBool tls13_ClientAllow0Rtt(const sslSocket *ss, const sslSessionID *sid);
+ PRUint16 tls13_EncodeDraftVersion(SSL3ProtocolVersion version);
++SECStatus tls13_ClientReadSupportedVersion(sslSocket *ss);
+ SECStatus tls13_NegotiateVersion(sslSocket *ss,
+                                  const TLSExtension *supported_versions);
+ 
+ PRBool tls13_IsReplay(const sslSocket *ss, const sslSessionID *sid);
+ void tls13_AntiReplayRollover(PRTime now);
+ 
+ SECStatus SSLExp_SetupAntiReplay(PRTime window, unsigned int k,
+                                  unsigned int bits);
+diff --git a/security/nss/tests/ssl/ssl.sh b/security/nss/tests/ssl/ssl.sh
+--- a/security/nss/tests/ssl/ssl.sh
++++ b/security/nss/tests/ssl/ssl.sh
+@@ -278,44 +278,40 @@ ssl_cov()
+   VMAX="tls1.1"
+ 
+   ignore_blank_lines ${SSLCOV} | \
+   while read ectype testmax param testname
+   do
+       echo "${testname}" | grep "EXPORT" > /dev/null
+       EXP=$?
+ 
+-      if [ "$ectype" = "ECC" ] ; then
+-          echo "$SCRIPTNAME: skipping  $testname (ECC only)"
+-      else
+-          echo "$SCRIPTNAME: running $testname ----------------------------"
+-          VMAX="ssl3"
+-          if [ "$testmax" = "TLS10" ]; then
+-              VMAX="tls1.0"
+-          fi
+-          if [ "$testmax" = "TLS11" ]; then
+-              VMAX="tls1.1"
+-          fi
+-          if [ "$testmax" = "TLS12" ]; then
+-              VMAX="tls1.2"
+-          fi
++      echo "$SCRIPTNAME: running $testname ----------------------------"
++      VMAX="ssl3"
++      if [ "$testmax" = "TLS10" ]; then
++          VMAX="tls1.0"
++      fi
++      if [ "$testmax" = "TLS11" ]; then
++          VMAX="tls1.1"
++      fi
++      if [ "$testmax" = "TLS12" ]; then
++          VMAX="tls1.2"
++      fi
+ 
+-          echo "tstclnt -4 -p ${PORT} -h ${HOSTADDR} -c ${param} -V ${VMIN}:${VMAX} ${CLIENT_OPTIONS} \\"
+-          echo "        -f -d ${P_R_CLIENTDIR} $verbose -w nss < ${REQUEST_FILE}"
++      echo "tstclnt -4 -p ${PORT} -h ${HOSTADDR} -c ${param} -V ${VMIN}:${VMAX} ${CLIENT_OPTIONS} \\"
++      echo "        -f -d ${P_R_CLIENTDIR} $verbose -w nss < ${REQUEST_FILE}"
+ 
+-          rm ${TMP}/$HOST.tmp.$$ 2>/dev/null
+-          ${PROFTOOL} ${BINDIR}/tstclnt -4 -p ${PORT} -h ${HOSTADDR} -c ${param} -V ${VMIN}:${VMAX} ${CLIENT_OPTIONS} -f \
+-                  -d ${P_R_CLIENTDIR} $verbose -w nss < ${REQUEST_FILE} \
+-                  >${TMP}/$HOST.tmp.$$  2>&1
+-          ret=$?
+-          cat ${TMP}/$HOST.tmp.$$
+-          rm ${TMP}/$HOST.tmp.$$ 2>/dev/null
+-          html_msg $ret 0 "${testname}" \
+-                   "produced a returncode of $ret, expected is 0"
+-      fi
++      rm ${TMP}/$HOST.tmp.$$ 2>/dev/null
++      ${PROFTOOL} ${BINDIR}/tstclnt -4 -p ${PORT} -h ${HOSTADDR} -c ${param} -V ${VMIN}:${VMAX} ${CLIENT_OPTIONS} -f \
++              -d ${P_R_CLIENTDIR} $verbose -w nss < ${REQUEST_FILE} \
++              >${TMP}/$HOST.tmp.$$  2>&1
++      ret=$?
++      cat ${TMP}/$HOST.tmp.$$
++      rm ${TMP}/$HOST.tmp.$$ 2>/dev/null
++      html_msg $ret 0 "${testname}" \
++               "produced a returncode of $ret, expected is 0"
+   done
+ 
+   kill_selfserv
+   html "</TABLE><BR>"
+ }
+ 
+ ############################## ssl_auth ################################
+ # local shell function to perform SSL  Client Authentication tests
+@@ -330,18 +326,16 @@ ssl_auth()
+   do
+       echo "${testname}" | grep "don't require client auth" > /dev/null
+       CAUTH=$?
+ 
+       if [ "${CLIENT_MODE}" = "fips" -a "${CAUTH}" -eq 0 ] ; then
+           echo "$SCRIPTNAME: skipping  $testname (non-FIPS only)"
+       elif [ "$ectype" = "SNI" -a "$NORM_EXT" = "Extended Test" ] ; then
+           echo "$SCRIPTNAME: skipping  $testname for $NORM_EXT"
+-      elif [ "$ectype" = "ECC" ] ; then
+-          echo "$SCRIPTNAME: skipping  $testname (ECC only)"
+       else
+           cparam=`echo $cparam | sed -e 's;_; ;g' -e "s/TestUser/$USER_NICKNAME/g" `
+           if [ "$ectype" = "SNI" ]; then
+               cparam=`echo $cparam | sed -e "s/Host/$HOST/g" -e "s/Dom/$DOMSUF/g" `
+               sparam=`echo $sparam | sed -e "s/Host/$HOST/g" -e "s/Dom/$DOMSUF/g" `
+           fi
+           start_selfserv
+ 
+@@ -545,18 +539,16 @@ ssl_stress()
+   do
+       echo "${testname}" | grep "client auth" > /dev/null
+       CAUTH=$?
+       echo "${testname}" | grep "no login" > /dev/null
+       NOLOGIN=$?
+ 
+       if [ "$ectype" = "SNI" -a "$NORM_EXT" = "Extended Test" ] ; then
+           echo "$SCRIPTNAME: skipping  $testname for $NORM_EXT"
+-      elif [ "$ectype" = "ECC" ] ; then
+-          echo "$SCRIPTNAME: skipping  $testname (ECC only)"
+       elif [ "${CLIENT_MODE}" = "fips" -a "${CAUTH}" -ne 0 ] ; then
+           echo "$SCRIPTNAME: skipping  $testname (non-FIPS only)"
+       elif [ "${NOLOGIN}" -eq 0 ] && \
+            [ "${CLIENT_MODE}" = "fips" -o "$NORM_EXT" = "Extended Test" ] ; then
+           echo "$SCRIPTNAME: skipping  $testname for $NORM_EXT"
+       else
+           cparam=`echo $cparam | sed -e 's;_; ;g' -e "s/TestUser/$USER_NICKNAME/g" `
+           if [ "$ectype" = "SNI" ]; then
+@@ -610,19 +602,17 @@ ssl_crl_ssl()
+   # Cert number $UNREVOKED_CERT_GRP_1 was not revoked
+   CRL_GROUP_BEGIN=$CRL_GRP_1_BEGIN
+   CRL_GROUP_RANGE=$CRL_GRP_1_RANGE
+   UNREVOKED_CERT=$UNREVOKED_CERT_GRP_1
+ 
+   ignore_blank_lines ${SSLAUTH} | \
+   while read ectype value sparam cparam testname
+   do
+-    if [ "$ectype" = "ECC" ] ; then
+-        echo "$SCRIPTNAME: skipping $testname (ECC only)"
+-    elif [ "$ectype" = "SNI" ]; then
++    if [ "$ectype" = "SNI" ]; then
+         continue
+     else
+ 	servarg=`echo $sparam | awk '{r=split($0,a,"-r") - 1;print r;}'`
+ 	pwd=`echo $cparam | grep nss`
+ 	user=`echo $cparam | grep TestUser`
+ 	_cparam=$cparam
+ 	case $servarg in
+ 	    1) if [ -z "$pwd" -o -z "$user" ]; then
+@@ -724,53 +714,49 @@ ssl_policy()
+ 
+   start_selfserv # Launch the server
+ 
+   ignore_blank_lines ${SSLPOLICY} | \
+   while read value ectype testmax param policy testname
+   do
+       VMIN="ssl3"
+ 
+-      if [ "$ectype" = "ECC" ] ; then
+-          echo "$SCRIPTNAME: skipping  $testname (ECC only)"
+-      else
+-          echo "$SCRIPTNAME: running $testname ----------------------------"
+-          VMAX="ssl3"
+-          if [ "$testmax" = "TLS10" ]; then
+-              VMAX="tls1.0"
+-          fi
+-          if [ "$testmax" = "TLS11" ]; then
+-              VMAX="tls1.1"
+-          fi
+-          if [ "$testmax" = "TLS12" ]; then
+-              VMAX="tls1.2"
+-          fi
++      echo "$SCRIPTNAME: running $testname ----------------------------"
++      VMAX="ssl3"
++      if [ "$testmax" = "TLS10" ]; then
++          VMAX="tls1.0"
++      fi
++      if [ "$testmax" = "TLS11" ]; then
++          VMAX="tls1.1"
++      fi
++      if [ "$testmax" = "TLS12" ]; then
++          VMAX="tls1.2"
++      fi
+ 
+-          # load the policy
+-          policy=`echo ${policy} | sed -e 's;_; ;g'`
+-          setup_policy "$policy" ${P_R_CLIENTDIR}
++      # load the policy
++      policy=`echo ${policy} | sed -e 's;_; ;g'`
++      setup_policy "$policy" ${P_R_CLIENTDIR}
+ 
+-          echo "tstclnt -4 -p ${PORT} -h ${HOSTADDR} -c ${param} -V ${VMIN}:${VMAX} ${CLIENT_OPTIONS} \\"
+-          echo "        -f -d ${P_R_CLIENTDIR} $verbose -w nss < ${REQUEST_FILE}"
++      echo "tstclnt -4 -p ${PORT} -h ${HOSTADDR} -c ${param} -V ${VMIN}:${VMAX} ${CLIENT_OPTIONS} \\"
++      echo "        -f -d ${P_R_CLIENTDIR} $verbose -w nss < ${REQUEST_FILE}"
+ 
+-          rm ${TMP}/$HOST.tmp.$$ 2>/dev/null
+-          ${PROFTOOL} ${BINDIR}/tstclnt -4 -p ${PORT} -h ${HOSTADDR} -c ${param} -V ${VMIN}:${VMAX} ${CLIENT_OPTIONS} -f \
+-                  -d ${P_R_CLIENTDIR} $verbose -w nss < ${REQUEST_FILE} \
+-                  >${TMP}/$HOST.tmp.$$  2>&1
+-          ret=$?
+-          cat ${TMP}/$HOST.tmp.$$
+-          rm ${TMP}/$HOST.tmp.$$ 2>/dev/null
++      rm ${TMP}/$HOST.tmp.$$ 2>/dev/null
++      ${PROFTOOL} ${BINDIR}/tstclnt -4 -p ${PORT} -h ${HOSTADDR} -c ${param} -V ${VMIN}:${VMAX} ${CLIENT_OPTIONS} -f \
++              -d ${P_R_CLIENTDIR} $verbose -w nss < ${REQUEST_FILE} \
++              >${TMP}/$HOST.tmp.$$  2>&1
++      ret=$?
++      cat ${TMP}/$HOST.tmp.$$
++      rm ${TMP}/$HOST.tmp.$$ 2>/dev/null
+ 
+-          #workaround for bug #402058
+-          [ $ret -ne 0 ] && ret=1
+-          [ ${value} -ne 0 ] && value=1
++      #workaround for bug #402058
++      [ $ret -ne 0 ] && ret=1
++      [ ${value} -ne 0 ] && value=1
+ 
+-          html_msg $ret ${value} "${testname}" \
+-                   "produced a returncode of $ret, expected is ${value}"
+-      fi
++      html_msg $ret ${value} "${testname}" \
++               "produced a returncode of $ret, expected is ${value}"
+   done
+   cp ${P_R_CLIENTDIR}/pkcs11.txt.sav ${P_R_CLIENTDIR}/pkcs11.txt
+ 
+   kill_selfserv
+   html "</TABLE><BR>"
+ }
+ 
+ list_enabled_suites()
+@@ -999,19 +985,17 @@ ssl_crl_cache()
+   while [ $? -eq 0 -a -f ${SSLAUTH_TMP} ]
+     do
+     sparam=$SERV_ARG
+     start_selfserv
+     exec < ${SSLAUTH_TMP}
+     while read ectype value sparam cparam testname
+       do
+       [ "$ectype" = "" ] && continue
+-      if [ "$ectype" = "ECC" ] ; then
+-        echo "$SCRIPTNAME: skipping  $testname (ECC only)"
+-      elif [ "$ectype" = "SNI" ]; then
++      if [ "$ectype" = "SNI" ]; then
+           continue
+       else
+         servarg=`echo $sparam | awk '{r=split($0,a,"-r") - 1;print r;}'`
+         pwd=`echo $cparam | grep nss`
+         user=`echo $cparam | grep TestUser`
+         _cparam=$cparam
+         case $servarg in
+             1) if [ -z "$pwd" -o -z "$user" ]; then

+ 75 - 0
rel-257/ian/patches/1445731-3-NSS337-61a1.patch

@@ -0,0 +1,75 @@
+# HG changeset patch
+# User J.C. Jones <jjones@mozilla.com>
+# Date 1521754830 25200
+#      Thu Mar 22 14:40:30 2018 -0700
+# Node ID 2fdd9bac3094fbaa41b94c7685968d0d2cbee036
+# Parent  7196c7b63af51b678344c5127b220bd4b12cf81d
+Bug 1445731 - land NSS 1bde21f90bd1 UPGRADE_NSS_RELEASE, r=me
+
+diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO
+--- a/security/nss/TAG-INFO
++++ b/security/nss/TAG-INFO
+@@ -1,1 +1,1 @@
+-c5dffd6269ea
++1bde21f90bd1
+diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep
+--- a/security/nss/coreconf/coreconf.dep
++++ b/security/nss/coreconf/coreconf.dep
+@@ -5,9 +5,8 @@
+ 
+ /*
+  * A dummy header file that is a dependency for all the object files.
+  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
+  * depend builds.  See comments in rules.mk.
+  */
+ 
+ #error "Do not include this header file."
+-
+diff --git a/security/nss/lib/ssl/ssl3ext.c b/security/nss/lib/ssl/ssl3ext.c
+--- a/security/nss/lib/ssl/ssl3ext.c
++++ b/security/nss/lib/ssl/ssl3ext.c
+@@ -676,17 +676,21 @@ ssl_CallCustomExtensionSenders(sslSocket
+         buf->len += len;
+ 
+         if (message == ssl_hs_client_hello ||
+             message == ssl_hs_certificate_request) {
+             ss->xtnData.advertised[ss->xtnData.numAdvertised++] = hook->type;
+         }
+     }
+ 
+-    sslBuffer_Append(buf, tail.buf, tail.len);
++    rv = sslBuffer_Append(buf, tail.buf, tail.len);
++    if (rv != SECSuccess) {
++        goto loser; /* Code already set. */
++    }
++
+     sslBuffer_Clear(&tail);
+     return SECSuccess;
+ 
+ loser:
+     sslBuffer_Clear(&tail);
+     return SECFailure;
+ }
+ 
+diff --git a/security/nss/lib/ssl/ssl3gthr.c b/security/nss/lib/ssl/ssl3gthr.c
+--- a/security/nss/lib/ssl/ssl3gthr.c
++++ b/security/nss/lib/ssl/ssl3gthr.c
+@@ -345,17 +345,17 @@ dtls_GatherData(sslSocket *ss, sslGather
+     gs->dtlsPacketOffset += headerLen;
+ 
+     /* Have received SSL3 record header in gs->hdr. */
+     if (headerLen == 13) {
+         gs->remainder = (gs->hdr[11] << 8) | gs->hdr[12];
+     } else if (headerLen == 7) {
+         gs->remainder = (gs->hdr[5] << 8) | gs->hdr[6];
+     } else {
+-        PORT_Assert(headerLen = 2);
++        PORT_Assert(headerLen == 2);
+         gs->remainder = gs->dtlsPacket.len - gs->dtlsPacketOffset;
+     }
+ 
+     if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < gs->remainder) {
+         SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet too short "
+                  "to contain rest of body",
+                  SSL_GETPID(), ss->fd));
+         PORT_SetError(PR_WOULD_BLOCK_ERROR);

+ 49 - 0
rel-257/ian/patches/1445731-4-NSS337-61a1.patch

@@ -0,0 +1,49 @@
+# HG changeset patch
+# User J.C. Jones <jjones@mozilla.com>
+# Date 1522076697 25200
+#      Mon Mar 26 08:04:57 2018 -0700
+# Node ID f4f472ea0a555eb300ee89750e53694304c630ab
+# Parent  38fd94fbfdafb39bca208bd89e3af3d86056c00d
+Bug 1445731 - land NSS dedf5290c679 UPGRADE_NSS_RELEASE, r=me
+
+diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO
+--- a/security/nss/TAG-INFO
++++ b/security/nss/TAG-INFO
+@@ -1,1 +1,1 @@
+-1bde21f90bd1
++dedf5290c679
+diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep
+--- a/security/nss/coreconf/coreconf.dep
++++ b/security/nss/coreconf/coreconf.dep
+@@ -5,8 +5,9 @@
+ 
+ /*
+  * A dummy header file that is a dependency for all the object files.
+  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
+  * depend builds.  See comments in rules.mk.
+  */
+ 
+ #error "Do not include this header file."
++
+diff --git a/security/nss/lib/pkcs7/p7create.c b/security/nss/lib/pkcs7/p7create.c
+--- a/security/nss/lib/pkcs7/p7create.c
++++ b/security/nss/lib/pkcs7/p7create.c
+@@ -17,17 +17,17 @@
+ #include "secerr.h"
+ #include "secder.h"
+ #include "secpkcs5.h"
+ 
+ const int NSS_PBE_DEFAULT_ITERATION_COUNT = /* used in p12e.c too */
+ #ifdef DEBUG
+     10000
+ #else
+-    1000000
++    600000
+ #endif
+     ;
+ 
+ static SECStatus
+ sec_pkcs7_init_content_info(SEC_PKCS7ContentInfo *cinfo, PLArenaPool *poolp,
+                             SECOidTag kind, PRBool detached)
+ {
+     void *thing;

+ 172 - 0
rel-257/ian/patches/1445731-5-NSS337-61a1.patch

@@ -0,0 +1,172 @@
+# HG changeset patch
+# User J.C. Jones <jjones@mozilla.com>
+# Date 1522425176 25200
+#      Fri Mar 30 08:52:56 2018 -0700
+# Node ID 280491d65d24816f1d8beb1e38b738e000ca3df8
+# Parent  37c026e3a6a58e1110bc19c5d4588460cc83fe25
+Bug 1445731 - land NSS 6ae3ab8a1e7b UPGRADE_NSS_RELEASE, r=me
+
+diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO
+--- a/security/nss/TAG-INFO
++++ b/security/nss/TAG-INFO
+@@ -1,1 +1,1 @@
+-dedf5290c679
++6ae3ab8a1e7b
+diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep
+--- a/security/nss/coreconf/coreconf.dep
++++ b/security/nss/coreconf/coreconf.dep
+@@ -5,9 +5,8 @@
+ 
+ /*
+  * A dummy header file that is a dependency for all the object files.
+  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
+  * depend builds.  See comments in rules.mk.
+  */
+ 
+ #error "Do not include this header file."
+-
+diff --git a/security/nss/lib/dev/devslot.c b/security/nss/lib/dev/devslot.c
+--- a/security/nss/lib/dev/devslot.c
++++ b/security/nss/lib/dev/devslot.c
+@@ -91,20 +91,26 @@ nssSlot_ResetDelay(
+     NSSSlot *slot)
+ {
+     PZ_Lock(slot->isPresentLock);
+     slot->lastTokenPingState = nssSlotLastPingState_Reset;
+     PZ_Unlock(slot->isPresentLock);
+ }
+ 
+ static PRBool
+-within_token_delay_period(const NSSSlot *slot)
++token_status_checked(const NSSSlot *slot)
+ {
+     PRIntervalTime time;
+     int lastPingState = slot->lastTokenPingState;
++    /* When called from the same thread, that means
++     * nssSlot_IsTokenPresent() is called recursively through
++     * nssSlot_Refresh(). Return immediately in that case. */
++    if (slot->isPresentThread == PR_GetCurrentThread()) {
++        return PR_TRUE;
++    }
+     /* Set the delay time for checking the token presence */
+     if (s_token_delay_time == 0) {
+         s_token_delay_time = PR_SecondsToInterval(NSSSLOT_TOKEN_DELAY_TIME);
+     }
+     time = PR_IntervalNow();
+     if ((lastPingState == nssSlotLastPingState_Valid) && ((time - slot->lastTokenPingTime) < s_token_delay_time)) {
+         return PR_TRUE;
+     }
+@@ -125,46 +131,46 @@ nssSlot_IsTokenPresent(
+ 
+     /* permanent slots are always present unless they're disabled */
+     if (nssSlot_IsPermanent(slot)) {
+         return !PK11_IsDisabled(slot->pk11slot);
+     }
+ 
+     /* avoid repeated calls to check token status within set interval */
+     PZ_Lock(slot->isPresentLock);
+-    if (within_token_delay_period(slot)) {
++    if (token_status_checked(slot)) {
+         CK_FLAGS ckFlags = slot->ckFlags;
+         PZ_Unlock(slot->isPresentLock);
+         return ((ckFlags & CKF_TOKEN_PRESENT) != 0);
+     }
+     PZ_Unlock(slot->isPresentLock);
+ 
+     /* First obtain the slot epv before we set up the condition
+      * variable, so we can just return if we couldn't get it. */
+     epv = slot->epv;
+     if (!epv) {
+         return PR_FALSE;
+     }
+ 
+     /* set up condition so only one thread is active in this part of the code at a time */
+     PZ_Lock(slot->isPresentLock);
+-    while (slot->inIsPresent) {
++    while (slot->isPresentThread) {
+         PR_WaitCondVar(slot->isPresentCondition, 0);
+     }
+     /* if we were one of multiple threads here, the first thread will have
+      * given us the answer, no need to make more queries of the token. */
+-    if (within_token_delay_period(slot)) {
++    if (token_status_checked(slot)) {
+         CK_FLAGS ckFlags = slot->ckFlags;
+         PZ_Unlock(slot->isPresentLock);
+         return ((ckFlags & CKF_TOKEN_PRESENT) != 0);
+     }
+     /* this is the winning thread, block all others until we've determined
+      * if the token is present and that it needs initialization. */
+     slot->lastTokenPingState = nssSlotLastPingState_Update;
+-    slot->inIsPresent = PR_TRUE;
++    slot->isPresentThread = PR_GetCurrentThread();
+ 
+     PZ_Unlock(slot->isPresentLock);
+ 
+     nssSlot_EnterMonitor(slot);
+     ckrv = CKAPI(epv)->C_GetSlotInfo(slot->slotID, &slotInfo);
+     nssSlot_ExitMonitor(slot);
+     if (ckrv != CKR_OK) {
+         slot->token->base.name[0] = 0; /* XXX */
+@@ -252,17 +258,17 @@ done:
+      */
+     PZ_Lock(slot->isPresentLock);
+     /* don't update the time if we were reset while we were
+      * getting the token state */
+     if (slot->lastTokenPingState == nssSlotLastPingState_Update) {
+         slot->lastTokenPingTime = PR_IntervalNow();
+         slot->lastTokenPingState = nssSlotLastPingState_Valid;
+     }
+-    slot->inIsPresent = PR_FALSE;
++    slot->isPresentThread = NULL;
+     PR_NotifyAllCondVar(slot->isPresentCondition);
+     PZ_Unlock(slot->isPresentLock);
+     return isPresent;
+ }
+ 
+ NSS_IMPLEMENT void *
+ nssSlot_GetCryptokiEPV(
+     NSSSlot *slot)
+diff --git a/security/nss/lib/dev/devt.h b/security/nss/lib/dev/devt.h
+--- a/security/nss/lib/dev/devt.h
++++ b/security/nss/lib/dev/devt.h
+@@ -87,17 +87,17 @@ struct NSSSlotStr {
+     struct nssSlotAuthInfoStr authInfo;
+     PRIntervalTime lastTokenPingTime;
+     nssSlotLastPingState lastTokenPingState;
+     PZLock *lock;
+     void *epv;
+     PK11SlotInfo *pk11slot;
+     PZLock *isPresentLock;
+     PRCondVar *isPresentCondition;
+-    PRBool inIsPresent;
++    PRThread *isPresentThread;
+ };
+ 
+ struct nssSessionStr {
+     PZLock *lock;
+     CK_SESSION_HANDLE handle;
+     NSSSlot *slot;
+     PRBool isRW;
+     PRBool ownLock;
+diff --git a/security/nss/lib/pk11wrap/dev3hack.c b/security/nss/lib/pk11wrap/dev3hack.c
+--- a/security/nss/lib/pk11wrap/dev3hack.c
++++ b/security/nss/lib/pk11wrap/dev3hack.c
+@@ -117,17 +117,17 @@ nssSlot_CreateFromPK11SlotInfo(NSSTrustD
+     rvSlot->pk11slot = PK11_ReferenceSlot(nss3slot);
+     rvSlot->epv = nss3slot->functionList;
+     rvSlot->slotID = nss3slot->slotID;
+     /* Grab the slot name from the PKCS#11 fixed-length buffer */
+     rvSlot->base.name = nssUTF8_Duplicate(nss3slot->slot_name, td->arena);
+     rvSlot->lock = (nss3slot->isThreadSafe) ? NULL : nss3slot->sessionLock;
+     rvSlot->isPresentLock = PZ_NewLock(nssiLockOther);
+     rvSlot->isPresentCondition = PR_NewCondVar(rvSlot->isPresentLock);
+-    rvSlot->inIsPresent = PR_FALSE;
++    rvSlot->isPresentThread = NULL;
+     rvSlot->lastTokenPingState = nssSlotLastPingState_Reset;
+     return rvSlot;
+ }
+ 
+ NSSToken *
+ nssToken_CreateFromPK11SlotInfo(NSSTrustDomain *td, PK11SlotInfo *nss3slot)
+ {
+     NSSToken *rvToken;

+ 156 - 0
rel-257/ian/patches/1445731-6-NSS337-61a1.patch

@@ -0,0 +1,156 @@
+# HG changeset patch
+# User Franziskus Kiefer <franziskuskiefer@gmail.com>
+# Date 1522831513 -7200
+#      Wed Apr 04 10:45:13 2018 +0200
+# Node ID f51236743c91517cf40b98b91a620f12c8bf1381
+# Parent  b878c7217f8626bbd211d6be1eaf03a49c0f4b3b
+Bug 1445731 - land NSS 954032211d2d UPGRADE_NSS_RELEASE, r=me
+
+diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO
+--- a/security/nss/TAG-INFO
++++ b/security/nss/TAG-INFO
+@@ -1,1 +1,1 @@
+-6ae3ab8a1e7b
++954032211d2d
+diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep
+--- a/security/nss/coreconf/coreconf.dep
++++ b/security/nss/coreconf/coreconf.dep
+@@ -5,8 +5,9 @@
+ 
+ /*
+  * A dummy header file that is a dependency for all the object files.
+  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
+  * depend builds.  See comments in rules.mk.
+  */
+ 
+ #error "Do not include this header file."
++
+diff --git a/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_hrr_unittest.cc
+@@ -995,16 +995,49 @@ TEST_P(HelloRetryRequestAgentTest, Handl
+ TEST_P(HelloRetryRequestAgentTest, HandleNoopHelloRetryRequest) {
+   DataBuffer hrr;
+   MakeCannedHrr(nullptr, 0U, &hrr);
+   ExpectAlert(kTlsAlertDecodeError);
+   ProcessMessage(hrr, TlsAgent::STATE_ERROR,
+                  SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST);
+ }
+ 
++class ReplaceRandom : public TlsHandshakeFilter {
++ public:
++  ReplaceRandom(const std::shared_ptr<TlsAgent>& a, const DataBuffer& r)
++      : TlsHandshakeFilter(a, {kTlsHandshakeServerHello}), random_(r) {}
++
++  PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
++                                       const DataBuffer& input,
++                                       DataBuffer* output) override {
++    output->Assign(input);
++    output->Write(2, random_);
++    return CHANGE;
++  }
++
++ private:
++  DataBuffer random_;
++};
++
++// Make sure that the TLS 1.3 special value for the ServerHello.random
++// is rejected by earlier versions.
++TEST_P(TlsConnectStreamPre13, HrrRandomOnTls10) {
++  static const uint8_t hrr_random[] = {
++      0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C,
++      0x02, 0x1E, 0x65, 0xB8, 0x91, 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB,
++      0x8C, 0x5E, 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C};
++
++  EnsureTlsSetup();
++  MakeTlsFilter<ReplaceRandom>(server_,
++                               DataBuffer(hrr_random, sizeof(hrr_random)));
++  ConnectExpectAlert(client_, kTlsAlertIllegalParameter);
++  client_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
++  server_->CheckErrorCode(SSL_ERROR_ILLEGAL_PARAMETER_ALERT);
++}
++
+ INSTANTIATE_TEST_CASE_P(HelloRetryRequestAgentTests, HelloRetryRequestAgentTest,
+                         ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll,
+                                            TlsConnectTestBase::kTlsV13));
+ #ifndef NSS_DISABLE_TLS_1_3
+ INSTANTIATE_TEST_CASE_P(HelloRetryRequestKeyExchangeTests, TlsKeyExchange13,
+                         ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll,
+                                            TlsConnectTestBase::kTlsV13));
+ #endif
+diff --git a/security/nss/lib/freebl/freebl.gyp b/security/nss/lib/freebl/freebl.gyp
+--- a/security/nss/lib/freebl/freebl.gyp
++++ b/security/nss/lib/freebl/freebl.gyp
+@@ -267,24 +267,19 @@
+               'NSS_USE_COMBA',
+               'USE_HW_AES',
+               'INTEL_GCM',
+             ],
+           },
+         },
+       }],
+       [ 'cc_use_gnu_ld==1 and OS=="win" and target_arch=="x64"', {
++        # mingw x64
+         'defines': [
+           'MP_IS_LITTLE_ENDIAN',
+-          'NSS_BEVAND_ARCFOUR',
+-          'MPI_AMD64',
+-          'MP_ASSEMBLY_MULTIPLY',
+-          'NSS_USE_COMBA',
+-          'USE_HW_AES',
+-          'INTEL_GCM',
+          ],
+       }],
+       [ 'OS!="win"', {
+         'conditions': [
+           [ 'target_arch=="x64" or target_arch=="arm64" or target_arch=="aarch64"', {
+             'defines': [
+               # The Makefile does version-tests on GCC, but we're not doing that here.
+               'HAVE_INT128_SUPPORT',
+diff --git a/security/nss/lib/freebl/freebl_base.gypi b/security/nss/lib/freebl/freebl_base.gypi
+--- a/security/nss/lib/freebl/freebl_base.gypi
++++ b/security/nss/lib/freebl/freebl_base.gypi
+@@ -118,16 +118,21 @@
+ 	      [ 'cc_use_gnu_ld!=1 and target_arch!="x64"', {
+           # not x64
+           'sources': [
+             'mpi/mpi_x86_asm.c',
+             'intel-aes-x86-masm.asm',
+             'intel-gcm-x86-masm.asm',
+           ],
+         }],
++        [ 'cc_use_gnu_ld==1', {
++          # mingw
++          'sources': [
++          ],
++        }],
+         [ 'cc_is_clang!=1', {
+           # MSVC
+           'sources': [
+             'intel-gcm-wrap.c',
+           ],
+         }],
+       ],
+     }],
+diff --git a/security/nss/lib/ssl/ssl3con.c b/security/nss/lib/ssl/ssl3con.c
+--- a/security/nss/lib/ssl/ssl3con.c
++++ b/security/nss/lib/ssl/ssl3con.c
+@@ -6283,17 +6283,17 @@ ssl3_HandleServerHello(sslSocket *ss, PR
+         desc = unexpected_message;
+         errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST;
+         goto alert_loser;
+     }
+ 
+     /* The server didn't pick 1.3 although we either received a
+      * HelloRetryRequest, or we prepared to send early app data. */
+     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+-        if (ss->ssl3.hs.helloRetry) {
++        if (isHelloRetry || ss->ssl3.hs.helloRetry) {
+             /* SSL3_SendAlert() will uncache the SID. */
+             desc = illegal_parameter;
+             errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+             goto alert_loser;
+         }
+         if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
+             /* SSL3_SendAlert() will uncache the SID. */
+             desc = illegal_parameter;

+ 1278 - 0
rel-257/ian/patches/1445731-7-NSS337-61a1.patch

@@ -0,0 +1,1278 @@
+# HG changeset patch
+# User Kai Engert <kaie@kuix.de>
+# Date 1523444048 -7200
+#      Wed Apr 11 12:54:08 2018 +0200
+# Node ID 0037f2516d1015029e8a3d0901d6e6d12a6aa140
+# Parent  1b0a61c9da091a06c125e8bb4fb7d7709df4f52a
+Bug 1445731, land NSS 2eefd697d661 UPGRADE_NSS_RELEASE, r=me
+
+diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO
+--- a/security/nss/TAG-INFO
++++ b/security/nss/TAG-INFO
+@@ -1,1 +1,1 @@
+-954032211d2d
++2eefd697d661
+diff --git a/security/nss/automation/taskcluster/docker-hacl/Dockerfile b/security/nss/automation/taskcluster/docker-hacl/Dockerfile
+--- a/security/nss/automation/taskcluster/docker-hacl/Dockerfile
++++ b/security/nss/automation/taskcluster/docker-hacl/Dockerfile
+@@ -4,17 +4,17 @@ MAINTAINER Franziskus Kiefer <franziskus
+ # Based on the HACL* image from Benjamin Beurdouche and
+ # the original F* formula with Daniel Fabian
+ 
+ # Pinned versions of HACL* (F* and KreMLin are pinned as submodules)
+ ENV haclrepo https://github.com/mitls/hacl-star.git
+ 
+ # Define versions of dependencies
+ ENV opamv 4.04.2
+-ENV haclversion 426abe1c4e55f3e569bd9815d52bffc4daac44e5
++ENV haclversion e13326efee1a9910004dccbb56f3d7be6639e0b8
+ 
+ # Install required packages and set versions
+ ADD setup.sh /tmp/setup.sh
+ RUN bash /tmp/setup.sh
+ 
+ # Create user, add scripts.
+ RUN useradd -ms /bin/bash worker
+ WORKDIR /home/worker
+diff --git a/security/nss/automation/taskcluster/docker-hacl/setup-user.sh b/security/nss/automation/taskcluster/docker-hacl/setup-user.sh
+--- a/security/nss/automation/taskcluster/docker-hacl/setup-user.sh
++++ b/security/nss/automation/taskcluster/docker-hacl/setup-user.sh
+@@ -11,16 +11,15 @@ opam install ocamlfind batteries sqlite3
+ # Get the HACL* code
+ git clone ${haclrepo} hacl-star
+ git -C hacl-star checkout ${haclversion}
+ 
+ # Prepare submodules, and build, verify, test, and extract c code
+ # This caches the extracted c code (pins the HACL* version). All we need to do
+ # on CI now is comparing the code in this docker image with the one in NSS.
+ opam config exec -- make -C hacl-star prepare -j$(nproc)
+-make -C hacl-star verify-nss -j$(nproc)
+ make -C hacl-star -f Makefile.build snapshots/nss -j$(nproc)
+ KOPTS="-funroll-loops 5" make -C hacl-star/code/curve25519 test -j$(nproc)
+ make -C hacl-star/code/salsa-family test -j$(nproc)
+ make -C hacl-star/code/poly1305 test -j$(nproc)
+ 
+ # Cleanup.
+ rm -rf ~/.ccache ~/.cache
+diff --git a/security/nss/automation/taskcluster/docker/Dockerfile b/security/nss/automation/taskcluster/docker/Dockerfile
+--- a/security/nss/automation/taskcluster/docker/Dockerfile
++++ b/security/nss/automation/taskcluster/docker/Dockerfile
+@@ -7,19 +7,16 @@ WORKDIR /home/worker
+ # Add build and test scripts.
+ ADD bin /home/worker/bin
+ RUN chmod +x /home/worker/bin/*
+ 
+ # Install dependencies.
+ ADD setup.sh /tmp/setup.sh
+ RUN bash /tmp/setup.sh
+ 
+-# Change user.
+-USER worker
+-
+ # Env variables.
+ ENV HOME /home/worker
+ ENV SHELL /bin/bash
+ ENV USER worker
+ ENV LOGNAME worker
+ ENV HOSTNAME taskcluster-worker
+ ENV LANG en_US.UTF-8
+ ENV LC_ALL en_US.UTF-8
+diff --git a/security/nss/automation/taskcluster/scripts/run_hacl.sh b/security/nss/automation/taskcluster/scripts/run_hacl.sh
+--- a/security/nss/automation/taskcluster/scripts/run_hacl.sh
++++ b/security/nss/automation/taskcluster/scripts/run_hacl.sh
+@@ -7,16 +7,19 @@ if [[ $(id -u) -eq 0 ]]; then
+ fi
+ 
+ set -e -x -v
+ 
+ # The docker image this is running in has the HACL* and NSS sources.
+ # The extracted C code from HACL* is already generated and the HACL* tests were
+ # successfully executed.
+ 
++# Verify HACL*. Taskcluster fails when we do this in the image build.
++make -C hacl-star verify-nss -j$(nproc)
++
+ # Add license header to specs
+ spec_files=($(find ~/hacl-star/specs -type f -name '*.fst'))
+ for f in "${spec_files[@]}"; do
+     cat /tmp/license.txt "$f" > /tmp/tmpfile && mv /tmp/tmpfile "$f"
+ done
+ 
+ # Format the extracted C code.
+ cd ~/hacl-star/snapshots/nss
+diff --git a/security/nss/automation/taskcluster/scripts/tools.sh b/security/nss/automation/taskcluster/scripts/tools.sh
+--- a/security/nss/automation/taskcluster/scripts/tools.sh
++++ b/security/nss/automation/taskcluster/scripts/tools.sh
+@@ -1,18 +1,23 @@
+ #!/usr/bin/env bash
+ 
+ set -v -e -x
+ 
+ if [[ $(id -u) -eq 0 ]]; then
++    # Stupid Docker. It works without sometimes... But not always.
++    echo "127.0.0.1 localhost.localdomain" >> /etc/hosts
++
+     # Drop privileges by re-running this script.
+     # Note: this mangles arguments, better to avoid running scripts as root.
+     exec su worker -c "$0 $*"
+ fi
+ 
++export PATH="${PATH}:/home/worker/.cargo/bin/:/usr/lib/go-1.6/bin"
++
+ # Usage: hg_clone repo dir [revision=@]
+ hg_clone() {
+     repo=$1
+     dir=$2
+     rev=${3:-@}
+     if [ -d "$dir" ]; then
+         hg pull -R "$dir" -ur "$rev" "$repo" && return
+         rm -rf "$dir"
+diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep
+--- a/security/nss/coreconf/coreconf.dep
++++ b/security/nss/coreconf/coreconf.dep
+@@ -5,9 +5,8 @@
+ 
+ /*
+  * A dummy header file that is a dependency for all the object files.
+  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
+  * depend builds.  See comments in rules.mk.
+  */
+ 
+ #error "Do not include this header file."
+-
+diff --git a/security/nss/gtests/ssl_gtest/ssl_agent_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_agent_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_agent_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_agent_unittest.cc
+@@ -140,16 +140,45 @@ TEST_F(TlsAgentDgramTestClient, Encrypte
+   agent_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_3,
+                           SSL_LIBRARY_VERSION_TLS_1_3);
+   ProcessMessage(buffer, TlsAgent::STATE_CONNECTING);
+   ExpectAlert(kTlsAlertUnexpectedMessage);
+   ProcessMessage(buffer2, TlsAgent::STATE_ERROR,
+                  SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
+ }
+ 
++TEST_F(TlsAgentDgramTestClient, AckWithBogusLengthField) {
++  EnsureInit();
++  // Length doesn't match
++  const uint8_t ackBuf[] = {0x00, 0x08, 0x00};
++  DataBuffer record;
++  MakeRecord(variant_, kTlsAckType, SSL_LIBRARY_VERSION_TLS_1_2, ackBuf,
++             sizeof(ackBuf), &record, 0);
++  agent_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_3,
++                          SSL_LIBRARY_VERSION_TLS_1_3);
++  ExpectAlert(kTlsAlertDecodeError);
++  ProcessMessage(record, TlsAgent::STATE_ERROR,
++                 SSL_ERROR_RX_MALFORMED_DTLS_ACK);
++}
++
++TEST_F(TlsAgentDgramTestClient, AckWithNonEvenLength) {
++  EnsureInit();
++  // Length isn't a multiple of 8
++  const uint8_t ackBuf[] = {0x00, 0x01, 0x00};
++  DataBuffer record;
++  MakeRecord(variant_, kTlsAckType, SSL_LIBRARY_VERSION_TLS_1_2, ackBuf,
++             sizeof(ackBuf), &record, 0);
++  agent_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_3,
++                          SSL_LIBRARY_VERSION_TLS_1_3);
++  // Because we haven't negotiated the version,
++  // ssl3_DecodeError() sends an older (pre-TLS error).
++  ExpectAlert(kTlsAlertIllegalParameter);
++  ProcessMessage(record, TlsAgent::STATE_ERROR, SSL_ERROR_BAD_SERVER);
++}
++
+ TEST_F(TlsAgentStreamTestClient, Set0RttOptionThenWrite) {
+   EnsureInit();
+   agent_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_1,
+                           SSL_LIBRARY_VERSION_TLS_1_3);
+   agent_->StartConnect();
+   agent_->Set0RttEnabled(true);
+   auto filter =
+       MakeTlsFilter<TlsHandshakeRecorder>(agent_, kTlsHandshakeClientHello);
+diff --git a/security/nss/gtests/ssl_gtest/ssl_auth_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_auth_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_auth_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_auth_unittest.cc
+@@ -361,16 +361,60 @@ TEST_P(TlsConnectTls13, SignatureAlgorit
+ // only fails when the Finished is checked.
+ TEST_P(TlsConnectTls12, SignatureAlgorithmDrop) {
+   MakeTlsFilter<TlsExtensionDropper>(client_, ssl_signature_algorithms_xtn);
+   ConnectExpectAlert(server_, kTlsAlertDecryptError);
+   client_->CheckErrorCode(SSL_ERROR_DECRYPT_ERROR_ALERT);
+   server_->CheckErrorCode(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
+ }
+ 
++// Replaces the signature scheme in a TLS 1.3 CertificateVerify message.
++class TlsReplaceSignatureSchemeFilter : public TlsHandshakeFilter {
++ public:
++  TlsReplaceSignatureSchemeFilter(const std::shared_ptr<TlsAgent>& a,
++                                  SSLSignatureScheme scheme)
++      : TlsHandshakeFilter(a, {kTlsHandshakeCertificateVerify}),
++        scheme_(scheme) {
++    EnableDecryption();
++  }
++
++ protected:
++  virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
++                                               const DataBuffer& input,
++                                               DataBuffer* output) {
++    *output = input;
++    output->Write(0, scheme_, 2);
++    return CHANGE;
++  }
++
++ private:
++  SSLSignatureScheme scheme_;
++};
++
++TEST_P(TlsConnectTls13, UnsupportedSignatureSchemeAlert) {
++  EnsureTlsSetup();
++  MakeTlsFilter<TlsReplaceSignatureSchemeFilter>(server_, ssl_sig_none);
++
++  ConnectExpectAlert(client_, kTlsAlertIllegalParameter);
++  server_->CheckErrorCode(SSL_ERROR_ILLEGAL_PARAMETER_ALERT);
++  client_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_CERT_VERIFY);
++}
++
++TEST_P(TlsConnectTls13, InconsistentSignatureSchemeAlert) {
++  EnsureTlsSetup();
++
++  // This won't work because we use an RSA cert by default.
++  MakeTlsFilter<TlsReplaceSignatureSchemeFilter>(
++      server_, ssl_sig_ecdsa_secp256r1_sha256);
++
++  ConnectExpectAlert(client_, kTlsAlertIllegalParameter);
++  server_->CheckErrorCode(SSL_ERROR_ILLEGAL_PARAMETER_ALERT);
++  client_->CheckErrorCode(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
++}
++
+ TEST_P(TlsConnectTls12Plus, RequestClientAuthWithSha384) {
+   server_->SetSignatureSchemes(SignatureSchemeRsaSha384,
+                                PR_ARRAY_SIZE(SignatureSchemeRsaSha384));
+   server_->RequestClientAuth(false);
+   Connect();
+ }
+ 
+ class BeforeFinished : public TlsRecordFilter {
+diff --git a/security/nss/gtests/ssl_gtest/ssl_drop_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_drop_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_drop_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_drop_unittest.cc
+@@ -137,20 +137,23 @@ class TlsDropDatagram13 : public TlsConn
+     std::shared_ptr<TlsRecordRecorder> ack_;
+     std::shared_ptr<SelectiveRecordDropFilter> drop_;
+     std::shared_ptr<PacketFilter> chain_;
+   };
+ 
+   void CheckAcks(const DropAckChain& chain, size_t index,
+                  std::vector<uint64_t> acks) {
+     const DataBuffer& buf = chain.ack_->record(index).buffer;
+-    size_t offset = 0;
++    size_t offset = 2;
++    uint64_t len;
+ 
+-    EXPECT_EQ(acks.size() * 8, buf.len());
+-    if ((acks.size() * 8) != buf.len()) {
++    EXPECT_EQ(2 + acks.size() * 8, buf.len());
++    ASSERT_TRUE(buf.Read(0, 2, &len));
++    ASSERT_EQ(static_cast<size_t>(len + 2), buf.len());
++    if ((2 + acks.size() * 8) != buf.len()) {
+       while (offset < buf.len()) {
+         uint64_t ack;
+         ASSERT_TRUE(buf.Read(offset, 8, &ack));
+         offset += 8;
+         std::cerr << "Ack=0x" << std::hex << ack << std::dec << std::endl;
+       }
+       return;
+     }
+diff --git a/security/nss/gtests/ssl_gtest/ssl_tls13compat_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_tls13compat_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_tls13compat_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_tls13compat_unittest.cc
+@@ -209,16 +209,108 @@ TEST_F(Tls13CompatTest, EnabledHrrZeroRt
+   CheckForCCS(true, true);
+ 
+   Handshake();
+   ExpectEarlyDataAccepted(false);
+   CheckConnected();
+   CheckForCompatHandshake();
+ }
+ 
++class TlsSessionIDEchoFilter : public TlsHandshakeFilter {
++ public:
++  TlsSessionIDEchoFilter(const std::shared_ptr<TlsAgent>& a)
++      : TlsHandshakeFilter(
++            a, {kTlsHandshakeClientHello, kTlsHandshakeServerHello}) {}
++
++ protected:
++  virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
++                                               const DataBuffer& input,
++                                               DataBuffer* output) {
++    TlsParser parser(input);
++
++    // Skip version + random.
++    EXPECT_TRUE(parser.Skip(2 + 32));
++
++    // Capture CH.legacy_session_id.
++    if (header.handshake_type() == kTlsHandshakeClientHello) {
++      EXPECT_TRUE(parser.ReadVariable(&sid_, 1));
++      return KEEP;
++    }
++
++    // Check that server sends one too.
++    uint32_t sid_len = 0;
++    EXPECT_TRUE(parser.Read(&sid_len, 1));
++    EXPECT_EQ(sid_len, sid_.len());
++
++    // Echo the one we captured.
++    *output = input;
++    output->Write(parser.consumed(), sid_.data(), sid_.len());
++
++    return CHANGE;
++  }
++
++ private:
++  DataBuffer sid_;
++};
++
++TEST_F(TlsConnectTest, EchoTLS13CompatibilitySessionID) {
++  ConfigureSessionCache(RESUME_SESSIONID, RESUME_SESSIONID);
++
++  client_->SetOption(SSL_ENABLE_TLS13_COMPAT_MODE, PR_TRUE);
++
++  client_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_2,
++                           SSL_LIBRARY_VERSION_TLS_1_3);
++
++  server_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_2,
++                           SSL_LIBRARY_VERSION_TLS_1_2);
++
++  server_->SetFilter(MakeTlsFilter<TlsSessionIDEchoFilter>(client_));
++  ConnectExpectAlert(client_, kTlsAlertIllegalParameter);
++
++  client_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
++  server_->CheckErrorCode(SSL_ERROR_ILLEGAL_PARAMETER_ALERT);
++}
++
++class TlsSessionIDInjectFilter : public TlsHandshakeFilter {
++ public:
++  TlsSessionIDInjectFilter(const std::shared_ptr<TlsAgent>& a)
++      : TlsHandshakeFilter(a, {kTlsHandshakeServerHello}) {}
++
++ protected:
++  virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
++                                               const DataBuffer& input,
++                                               DataBuffer* output) {
++    TlsParser parser(input);
++
++    // Skip version + random.
++    EXPECT_TRUE(parser.Skip(2 + 32));
++
++    *output = input;
++
++    // Inject a Session ID.
++    const uint8_t fake_sid[SSL3_SESSIONID_BYTES] = {0xff};
++    output->Write(parser.consumed(), sizeof(fake_sid), 1);
++    output->Splice(fake_sid, sizeof(fake_sid), parser.consumed() + 1, 0);
++
++    return CHANGE;
++  }
++};
++
++TEST_F(TlsConnectTest, TLS13NonCompatModeSessionID) {
++  ConfigureVersion(SSL_LIBRARY_VERSION_TLS_1_3);
++
++  MakeTlsFilter<TlsSessionIDInjectFilter>(server_);
++  client_->ExpectSendAlert(kTlsAlertIllegalParameter);
++  server_->ExpectSendAlert(kTlsAlertBadRecordMac);
++  ConnectExpectFail();
++
++  client_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
++  server_->CheckErrorCode(SSL_ERROR_BAD_MAC_READ);
++}
++
+ static const uint8_t kCannedCcs[] = {
+     kTlsChangeCipherSpecType,
+     SSL_LIBRARY_VERSION_TLS_1_2 >> 8,
+     SSL_LIBRARY_VERSION_TLS_1_2 & 0xff,
+     0,
+     1,  // length
+     1   // change_cipher_spec_choice
+ };
+diff --git a/security/nss/lib/ckfw/builtins/certdata.txt b/security/nss/lib/ckfw/builtins/certdata.txt
+--- a/security/nss/lib/ckfw/builtins/certdata.txt
++++ b/security/nss/lib/ckfw/builtins/certdata.txt
+@@ -7236,173 +7236,16 @@ CKA_SERIAL_NUMBER MULTILINE_OCTAL
+ \014
+ END
+ CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NSS_MUST_VERIFY_TRUST
+ CKA_TRUST_EMAIL_PROTECTION CK_TRUST CKT_NSS_TRUSTED_DELEGATOR
+ CKA_TRUST_CODE_SIGNING CK_TRUST CKT_NSS_MUST_VERIFY_TRUST
+ CKA_TRUST_STEP_UP_APPROVED CK_BBOOL CK_FALSE
+ 
+ #
+-# Certificate "TC TrustCenter Class 3 CA II"
+-#
+-# Issuer: CN=TC TrustCenter Class 3 CA II,OU=TC TrustCenter Class 3 CA,O=TC TrustCenter GmbH,C=DE
+-# Serial Number:4a:47:00:01:00:02:e5:a0:5d:d6:3f:00:51:bf
+-# Subject: CN=TC TrustCenter Class 3 CA II,OU=TC TrustCenter Class 3 CA,O=TC TrustCenter GmbH,C=DE
+-# Not Valid Before: Thu Jan 12 14:41:57 2006
+-# Not Valid After : Wed Dec 31 22:59:59 2025
+-# Fingerprint (MD5): 56:5F:AA:80:61:12:17:F6:67:21:E6:2B:6D:61:56:8E
+-# Fingerprint (SHA1): 80:25:EF:F4:6E:70:C8:D4:72:24:65:84:FE:40:3B:8A:8D:6A:DB:F5
+-CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE
+-CKA_TOKEN CK_BBOOL CK_TRUE
+-CKA_PRIVATE CK_BBOOL CK_FALSE
+-CKA_MODIFIABLE CK_BBOOL CK_FALSE
+-CKA_LABEL UTF8 "TC TrustCenter Class 3 CA II"
+-CKA_CERTIFICATE_TYPE CK_CERTIFICATE_TYPE CKC_X_509
+-CKA_SUBJECT MULTILINE_OCTAL
+-\060\166\061\013\060\011\006\003\125\004\006\023\002\104\105\061
+-\034\060\032\006\003\125\004\012\023\023\124\103\040\124\162\165
+-\163\164\103\145\156\164\145\162\040\107\155\142\110\061\042\060
+-\040\006\003\125\004\013\023\031\124\103\040\124\162\165\163\164
+-\103\145\156\164\145\162\040\103\154\141\163\163\040\063\040\103
+-\101\061\045\060\043\006\003\125\004\003\023\034\124\103\040\124
+-\162\165\163\164\103\145\156\164\145\162\040\103\154\141\163\163
+-\040\063\040\103\101\040\111\111
+-END
+-CKA_ID UTF8 "0"
+-CKA_ISSUER MULTILINE_OCTAL
+-\060\166\061\013\060\011\006\003\125\004\006\023\002\104\105\061
+-\034\060\032\006\003\125\004\012\023\023\124\103\040\124\162\165
+-\163\164\103\145\156\164\145\162\040\107\155\142\110\061\042\060
+-\040\006\003\125\004\013\023\031\124\103\040\124\162\165\163\164
+-\103\145\156\164\145\162\040\103\154\141\163\163\040\063\040\103
+-\101\061\045\060\043\006\003\125\004\003\023\034\124\103\040\124
+-\162\165\163\164\103\145\156\164\145\162\040\103\154\141\163\163
+-\040\063\040\103\101\040\111\111
+-END
+-CKA_SERIAL_NUMBER MULTILINE_OCTAL
+-\002\016\112\107\000\001\000\002\345\240\135\326\077\000\121\277
+-END
+-CKA_VALUE MULTILINE_OCTAL
+-\060\202\004\252\060\202\003\222\240\003\002\001\002\002\016\112
+-\107\000\001\000\002\345\240\135\326\077\000\121\277\060\015\006
+-\011\052\206\110\206\367\015\001\001\005\005\000\060\166\061\013
+-\060\011\006\003\125\004\006\023\002\104\105\061\034\060\032\006
+-\003\125\004\012\023\023\124\103\040\124\162\165\163\164\103\145
+-\156\164\145\162\040\107\155\142\110\061\042\060\040\006\003\125
+-\004\013\023\031\124\103\040\124\162\165\163\164\103\145\156\164
+-\145\162\040\103\154\141\163\163\040\063\040\103\101\061\045\060
+-\043\006\003\125\004\003\023\034\124\103\040\124\162\165\163\164
+-\103\145\156\164\145\162\040\103\154\141\163\163\040\063\040\103
+-\101\040\111\111\060\036\027\015\060\066\060\061\061\062\061\064
+-\064\061\065\067\132\027\015\062\065\061\062\063\061\062\062\065
+-\071\065\071\132\060\166\061\013\060\011\006\003\125\004\006\023
+-\002\104\105\061\034\060\032\006\003\125\004\012\023\023\124\103
+-\040\124\162\165\163\164\103\145\156\164\145\162\040\107\155\142
+-\110\061\042\060\040\006\003\125\004\013\023\031\124\103\040\124
+-\162\165\163\164\103\145\156\164\145\162\040\103\154\141\163\163
+-\040\063\040\103\101\061\045\060\043\006\003\125\004\003\023\034
+-\124\103\040\124\162\165\163\164\103\145\156\164\145\162\040\103
+-\154\141\163\163\040\063\040\103\101\040\111\111\060\202\001\042
+-\060\015\006\011\052\206\110\206\367\015\001\001\001\005\000\003
+-\202\001\017\000\060\202\001\012\002\202\001\001\000\264\340\273
+-\121\273\071\134\213\004\305\114\171\034\043\206\061\020\143\103
+-\125\047\077\306\105\307\244\075\354\011\015\032\036\040\302\126
+-\036\336\033\067\007\060\042\057\157\361\006\361\253\255\326\310
+-\253\141\243\057\103\304\260\262\055\374\303\226\151\173\176\212
+-\344\314\300\071\022\220\102\140\311\314\065\150\356\332\137\220
+-\126\137\315\034\115\133\130\111\353\016\001\117\144\372\054\074
+-\211\130\330\057\056\342\260\150\351\042\073\165\211\326\104\032
+-\145\362\033\227\046\035\050\155\254\350\275\131\035\053\044\366
+-\326\204\003\146\210\044\000\170\140\361\370\253\376\002\262\153
+-\373\042\373\065\346\026\321\255\366\056\022\344\372\065\152\345
+-\031\271\135\333\073\036\032\373\323\377\025\024\010\330\011\152
+-\272\105\235\024\171\140\175\257\100\212\007\163\263\223\226\323
+-\164\064\215\072\067\051\336\134\354\365\356\056\061\302\040\334
+-\276\361\117\177\043\122\331\133\342\144\331\234\252\007\010\265
+-\105\275\321\320\061\301\253\124\237\251\322\303\142\140\003\361
+-\273\071\112\222\112\075\012\271\235\305\240\376\067\002\003\001
+-\000\001\243\202\001\064\060\202\001\060\060\017\006\003\125\035
+-\023\001\001\377\004\005\060\003\001\001\377\060\016\006\003\125
+-\035\017\001\001\377\004\004\003\002\001\006\060\035\006\003\125
+-\035\016\004\026\004\024\324\242\374\237\263\303\330\003\323\127
+-\134\007\244\320\044\247\300\362\000\324\060\201\355\006\003\125
+-\035\037\004\201\345\060\201\342\060\201\337\240\201\334\240\201
+-\331\206\065\150\164\164\160\072\057\057\167\167\167\056\164\162
+-\165\163\164\143\145\156\164\145\162\056\144\145\057\143\162\154
+-\057\166\062\057\164\143\137\143\154\141\163\163\137\063\137\143
+-\141\137\111\111\056\143\162\154\206\201\237\154\144\141\160\072
+-\057\057\167\167\167\056\164\162\165\163\164\143\145\156\164\145
+-\162\056\144\145\057\103\116\075\124\103\045\062\060\124\162\165
+-\163\164\103\145\156\164\145\162\045\062\060\103\154\141\163\163
+-\045\062\060\063\045\062\060\103\101\045\062\060\111\111\054\117
+-\075\124\103\045\062\060\124\162\165\163\164\103\145\156\164\145
+-\162\045\062\060\107\155\142\110\054\117\125\075\162\157\157\164
+-\143\145\162\164\163\054\104\103\075\164\162\165\163\164\143\145
+-\156\164\145\162\054\104\103\075\144\145\077\143\145\162\164\151
+-\146\151\143\141\164\145\122\145\166\157\143\141\164\151\157\156
+-\114\151\163\164\077\142\141\163\145\077\060\015\006\011\052\206
+-\110\206\367\015\001\001\005\005\000\003\202\001\001\000\066\140
+-\344\160\367\006\040\103\331\043\032\102\362\370\243\262\271\115
+-\212\264\363\302\232\125\061\174\304\073\147\232\264\337\115\016
+-\212\223\112\027\213\033\215\312\211\341\317\072\036\254\035\361
+-\234\062\264\216\131\166\242\101\205\045\067\240\023\320\365\174
+-\116\325\352\226\342\156\162\301\273\052\376\154\156\370\221\230
+-\106\374\311\033\127\133\352\310\032\073\077\260\121\230\074\007
+-\332\054\131\001\332\213\104\350\341\164\375\247\150\335\124\272
+-\203\106\354\310\106\265\370\257\227\300\073\011\034\217\316\162
+-\226\075\063\126\160\274\226\313\330\325\175\040\232\203\237\032
+-\334\071\361\305\162\243\021\003\375\073\102\122\051\333\350\001
+-\367\233\136\214\326\215\206\116\031\372\274\034\276\305\041\245
+-\207\236\170\056\066\333\011\161\243\162\064\370\154\343\006\011
+-\362\136\126\245\323\335\230\372\324\346\006\364\360\266\040\143
+-\113\352\051\275\252\202\146\036\373\201\252\247\067\255\023\030
+-\346\222\303\201\301\063\273\210\036\241\347\342\264\275\061\154
+-\016\121\075\157\373\226\126\200\342\066\027\321\334\344
+-END
+-CKA_NSS_MOZILLA_CA_POLICY CK_BBOOL CK_TRUE
+-
+-# Trust for Certificate "TC TrustCenter Class 3 CA II"
+-# Issuer: CN=TC TrustCenter Class 3 CA II,OU=TC TrustCenter Class 3 CA,O=TC TrustCenter GmbH,C=DE
+-# Serial Number:4a:47:00:01:00:02:e5:a0:5d:d6:3f:00:51:bf
+-# Subject: CN=TC TrustCenter Class 3 CA II,OU=TC TrustCenter Class 3 CA,O=TC TrustCenter GmbH,C=DE
+-# Not Valid Before: Thu Jan 12 14:41:57 2006
+-# Not Valid After : Wed Dec 31 22:59:59 2025
+-# Fingerprint (MD5): 56:5F:AA:80:61:12:17:F6:67:21:E6:2B:6D:61:56:8E
+-# Fingerprint (SHA1): 80:25:EF:F4:6E:70:C8:D4:72:24:65:84:FE:40:3B:8A:8D:6A:DB:F5
+-CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST
+-CKA_TOKEN CK_BBOOL CK_TRUE
+-CKA_PRIVATE CK_BBOOL CK_FALSE
+-CKA_MODIFIABLE CK_BBOOL CK_FALSE
+-CKA_LABEL UTF8 "TC TrustCenter Class 3 CA II"
+-CKA_CERT_SHA1_HASH MULTILINE_OCTAL
+-\200\045\357\364\156\160\310\324\162\044\145\204\376\100\073\212
+-\215\152\333\365
+-END
+-CKA_CERT_MD5_HASH MULTILINE_OCTAL
+-\126\137\252\200\141\022\027\366\147\041\346\053\155\141\126\216
+-END
+-CKA_ISSUER MULTILINE_OCTAL
+-\060\166\061\013\060\011\006\003\125\004\006\023\002\104\105\061
+-\034\060\032\006\003\125\004\012\023\023\124\103\040\124\162\165
+-\163\164\103\145\156\164\145\162\040\107\155\142\110\061\042\060
+-\040\006\003\125\004\013\023\031\124\103\040\124\162\165\163\164
+-\103\145\156\164\145\162\040\103\154\141\163\163\040\063\040\103
+-\101\061\045\060\043\006\003\125\004\003\023\034\124\103\040\124
+-\162\165\163\164\103\145\156\164\145\162\040\103\154\141\163\163
+-\040\063\040\103\101\040\111\111
+-END
+-CKA_SERIAL_NUMBER MULTILINE_OCTAL
+-\002\016\112\107\000\001\000\002\345\240\135\326\077\000\121\277
+-END
+-CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NSS_MUST_VERIFY_TRUST
+-CKA_TRUST_EMAIL_PROTECTION CK_TRUST CKT_NSS_TRUSTED_DELEGATOR
+-CKA_TRUST_CODE_SIGNING CK_TRUST CKT_NSS_MUST_VERIFY_TRUST
+-CKA_TRUST_STEP_UP_APPROVED CK_BBOOL CK_FALSE
+-
+-#
+ # Certificate "Deutsche Telekom Root CA 2"
+ #
+ # Issuer: CN=Deutsche Telekom Root CA 2,OU=T-TeleSec Trust Center,O=Deutsche Telekom AG,C=DE
+ # Serial Number: 38 (0x26)
+ # Subject: CN=Deutsche Telekom Root CA 2,OU=T-TeleSec Trust Center,O=Deutsche Telekom AG,C=DE
+ # Not Valid Before: Fri Jul 09 12:11:00 1999
+ # Not Valid After : Tue Jul 09 23:59:00 2019
+ # Fingerprint (MD5): 74:01:4A:91:B1:08:C4:58:CE:47:CD:F0:DD:11:53:08
+@@ -17878,165 +17721,16 @@ CKA_SERIAL_NUMBER MULTILINE_OCTAL
+ \000\002
+ END
+ CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NSS_TRUSTED_DELEGATOR
+ CKA_TRUST_EMAIL_PROTECTION CK_TRUST CKT_NSS_TRUSTED_DELEGATOR
+ CKA_TRUST_CODE_SIGNING CK_TRUST CKT_NSS_MUST_VERIFY_TRUST
+ CKA_TRUST_STEP_UP_APPROVED CK_BBOOL CK_FALSE
+ 
+ #
+-# Certificate "S-TRUST Universal Root CA"
+-#
+-# Issuer: CN=S-TRUST Universal Root CA,OU=S-TRUST Certification Services,O=Deutscher Sparkassen Verlag GmbH,C=DE
+-# Serial Number:60:56:c5:4b:23:40:5b:64:d4:ed:25:da:d9:d6:1e:1e
+-# Subject: CN=S-TRUST Universal Root CA,OU=S-TRUST Certification Services,O=Deutscher Sparkassen Verlag GmbH,C=DE
+-# Not Valid Before: Tue Oct 22 00:00:00 2013
+-# Not Valid After : Thu Oct 21 23:59:59 2038
+-# Fingerprint (SHA-256): D8:0F:EF:91:0A:E3:F1:04:72:3B:04:5C:EC:2D:01:9F:44:1C:E6:21:3A:DF:15:67:91:E7:0C:17:90:11:0A:31
+-# Fingerprint (SHA1): 1B:3D:11:14:EA:7A:0F:95:58:54:41:95:BF:6B:25:82:AB:40:CE:9A
+-CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE
+-CKA_TOKEN CK_BBOOL CK_TRUE
+-CKA_PRIVATE CK_BBOOL CK_FALSE
+-CKA_MODIFIABLE CK_BBOOL CK_FALSE
+-CKA_LABEL UTF8 "S-TRUST Universal Root CA"
+-CKA_CERTIFICATE_TYPE CK_CERTIFICATE_TYPE CKC_X_509
+-CKA_SUBJECT MULTILINE_OCTAL
+-\060\201\205\061\013\060\011\006\003\125\004\006\023\002\104\105
+-\061\051\060\047\006\003\125\004\012\023\040\104\145\165\164\163
+-\143\150\145\162\040\123\160\141\162\153\141\163\163\145\156\040
+-\126\145\162\154\141\147\040\107\155\142\110\061\047\060\045\006
+-\003\125\004\013\023\036\123\055\124\122\125\123\124\040\103\145
+-\162\164\151\146\151\143\141\164\151\157\156\040\123\145\162\166
+-\151\143\145\163\061\042\060\040\006\003\125\004\003\023\031\123
+-\055\124\122\125\123\124\040\125\156\151\166\145\162\163\141\154
+-\040\122\157\157\164\040\103\101
+-END
+-CKA_ID UTF8 "0"
+-CKA_ISSUER MULTILINE_OCTAL
+-\060\201\205\061\013\060\011\006\003\125\004\006\023\002\104\105
+-\061\051\060\047\006\003\125\004\012\023\040\104\145\165\164\163
+-\143\150\145\162\040\123\160\141\162\153\141\163\163\145\156\040
+-\126\145\162\154\141\147\040\107\155\142\110\061\047\060\045\006
+-\003\125\004\013\023\036\123\055\124\122\125\123\124\040\103\145
+-\162\164\151\146\151\143\141\164\151\157\156\040\123\145\162\166
+-\151\143\145\163\061\042\060\040\006\003\125\004\003\023\031\123
+-\055\124\122\125\123\124\040\125\156\151\166\145\162\163\141\154
+-\040\122\157\157\164\040\103\101
+-END
+-CKA_SERIAL_NUMBER MULTILINE_OCTAL
+-\002\020\140\126\305\113\043\100\133\144\324\355\045\332\331\326
+-\036\036
+-END
+-CKA_VALUE MULTILINE_OCTAL
+-\060\202\003\330\060\202\002\300\240\003\002\001\002\002\020\140
+-\126\305\113\043\100\133\144\324\355\045\332\331\326\036\036\060
+-\015\006\011\052\206\110\206\367\015\001\001\013\005\000\060\201
+-\205\061\013\060\011\006\003\125\004\006\023\002\104\105\061\051
+-\060\047\006\003\125\004\012\023\040\104\145\165\164\163\143\150
+-\145\162\040\123\160\141\162\153\141\163\163\145\156\040\126\145
+-\162\154\141\147\040\107\155\142\110\061\047\060\045\006\003\125
+-\004\013\023\036\123\055\124\122\125\123\124\040\103\145\162\164
+-\151\146\151\143\141\164\151\157\156\040\123\145\162\166\151\143
+-\145\163\061\042\060\040\006\003\125\004\003\023\031\123\055\124
+-\122\125\123\124\040\125\156\151\166\145\162\163\141\154\040\122
+-\157\157\164\040\103\101\060\036\027\015\061\063\061\060\062\062
+-\060\060\060\060\060\060\132\027\015\063\070\061\060\062\061\062
+-\063\065\071\065\071\132\060\201\205\061\013\060\011\006\003\125
+-\004\006\023\002\104\105\061\051\060\047\006\003\125\004\012\023
+-\040\104\145\165\164\163\143\150\145\162\040\123\160\141\162\153
+-\141\163\163\145\156\040\126\145\162\154\141\147\040\107\155\142
+-\110\061\047\060\045\006\003\125\004\013\023\036\123\055\124\122
+-\125\123\124\040\103\145\162\164\151\146\151\143\141\164\151\157
+-\156\040\123\145\162\166\151\143\145\163\061\042\060\040\006\003
+-\125\004\003\023\031\123\055\124\122\125\123\124\040\125\156\151
+-\166\145\162\163\141\154\040\122\157\157\164\040\103\101\060\202
+-\001\042\060\015\006\011\052\206\110\206\367\015\001\001\001\005
+-\000\003\202\001\017\000\060\202\001\012\002\202\001\001\000\250
+-\343\013\337\021\067\205\202\232\265\154\146\174\141\077\300\107
+-\032\035\106\343\260\125\144\345\270\202\071\050\007\176\027\377
+-\364\233\212\360\221\201\352\070\077\041\170\154\110\354\153\057
+-\242\323\212\162\262\247\327\331\352\177\264\300\111\153\060\045
+-\211\214\353\267\325\100\141\230\342\334\074\040\222\315\145\112
+-\162\237\032\216\214\372\045\025\277\363\041\203\050\015\213\257
+-\131\021\202\103\134\233\115\045\121\177\130\030\143\140\073\263
+-\265\212\213\130\143\067\110\110\220\104\302\100\335\135\367\103
+-\151\051\230\134\022\145\136\253\220\222\113\146\337\325\165\022
+-\123\124\030\246\336\212\326\273\127\003\071\131\231\030\005\014
+-\371\375\025\306\220\144\106\027\202\327\302\112\101\075\375\000
+-\276\127\162\030\224\167\033\123\132\211\001\366\063\162\016\223
+-\072\334\350\036\375\005\005\326\274\163\340\210\334\253\117\354
+-\265\030\206\117\171\204\016\110\052\146\052\335\062\310\170\145
+-\310\013\235\130\001\005\161\355\201\365\150\027\156\313\015\264
+-\113\330\241\354\256\070\353\034\130\057\241\145\003\064\057\002
+-\003\001\000\001\243\102\060\100\060\017\006\003\125\035\023\001
+-\001\377\004\005\060\003\001\001\377\060\016\006\003\125\035\017
+-\001\001\377\004\004\003\002\001\006\060\035\006\003\125\035\016
+-\004\026\004\024\232\175\327\353\353\177\124\230\105\051\264\040
+-\253\155\013\226\043\031\244\302\060\015\006\011\052\206\110\206
+-\367\015\001\001\013\005\000\003\202\001\001\000\116\226\022\333
+-\176\167\136\222\047\236\041\027\030\202\166\330\077\274\245\011
+-\004\146\210\211\255\333\125\263\063\152\306\145\304\217\115\363
+-\062\066\334\171\004\226\251\167\062\321\227\365\030\153\214\272
+-\355\316\021\320\104\307\222\361\264\104\216\355\210\122\110\236
+-\325\375\131\370\243\036\121\373\001\122\345\137\345\172\335\252
+-\044\117\042\213\335\166\106\366\245\240\017\065\330\312\017\230
+-\271\060\135\040\157\302\201\036\275\275\300\376\025\323\070\052
+-\011\223\230\047\033\223\173\320\053\064\136\150\245\025\117\321
+-\122\303\240\312\240\203\105\035\365\365\267\131\163\135\131\001
+-\217\252\302\107\057\024\161\325\051\343\020\265\107\223\045\314
+-\043\051\332\267\162\330\221\324\354\033\110\212\042\344\301\052
+-\367\072\150\223\237\105\031\156\103\267\314\376\270\221\232\141
+-\032\066\151\143\144\222\050\363\157\141\222\205\023\237\311\007
+-\054\213\127\334\353\236\171\325\302\336\010\325\124\262\127\116
+-\052\062\215\241\342\072\321\020\040\042\071\175\064\105\157\161
+-\073\303\035\374\377\262\117\250\342\366\060\036
+-END
+-CKA_NSS_MOZILLA_CA_POLICY CK_BBOOL CK_TRUE
+-
+-# Trust for "S-TRUST Universal Root CA"
+-# Issuer: CN=S-TRUST Universal Root CA,OU=S-TRUST Certification Services,O=Deutscher Sparkassen Verlag GmbH,C=DE
+-# Serial Number:60:56:c5:4b:23:40:5b:64:d4:ed:25:da:d9:d6:1e:1e
+-# Subject: CN=S-TRUST Universal Root CA,OU=S-TRUST Certification Services,O=Deutscher Sparkassen Verlag GmbH,C=DE
+-# Not Valid Before: Tue Oct 22 00:00:00 2013
+-# Not Valid After : Thu Oct 21 23:59:59 2038
+-# Fingerprint (SHA-256): D8:0F:EF:91:0A:E3:F1:04:72:3B:04:5C:EC:2D:01:9F:44:1C:E6:21:3A:DF:15:67:91:E7:0C:17:90:11:0A:31
+-# Fingerprint (SHA1): 1B:3D:11:14:EA:7A:0F:95:58:54:41:95:BF:6B:25:82:AB:40:CE:9A
+-CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST
+-CKA_TOKEN CK_BBOOL CK_TRUE
+-CKA_PRIVATE CK_BBOOL CK_FALSE
+-CKA_MODIFIABLE CK_BBOOL CK_FALSE
+-CKA_LABEL UTF8 "S-TRUST Universal Root CA"
+-CKA_CERT_SHA1_HASH MULTILINE_OCTAL
+-\033\075\021\024\352\172\017\225\130\124\101\225\277\153\045\202
+-\253\100\316\232
+-END
+-CKA_CERT_MD5_HASH MULTILINE_OCTAL
+-\130\366\101\001\256\365\133\121\231\116\134\041\350\117\324\146
+-END
+-CKA_ISSUER MULTILINE_OCTAL
+-\060\201\205\061\013\060\011\006\003\125\004\006\023\002\104\105
+-\061\051\060\047\006\003\125\004\012\023\040\104\145\165\164\163
+-\143\150\145\162\040\123\160\141\162\153\141\163\163\145\156\040
+-\126\145\162\154\141\147\040\107\155\142\110\061\047\060\045\006
+-\003\125\004\013\023\036\123\055\124\122\125\123\124\040\103\145
+-\162\164\151\146\151\143\141\164\151\157\156\040\123\145\162\166
+-\151\143\145\163\061\042\060\040\006\003\125\004\003\023\031\123
+-\055\124\122\125\123\124\040\125\156\151\166\145\162\163\141\154
+-\040\122\157\157\164\040\103\101
+-END
+-CKA_SERIAL_NUMBER MULTILINE_OCTAL
+-\002\020\140\126\305\113\043\100\133\144\324\355\045\332\331\326
+-\036\036
+-END
+-CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NSS_MUST_VERIFY_TRUST
+-CKA_TRUST_EMAIL_PROTECTION CK_TRUST CKT_NSS_TRUSTED_DELEGATOR
+-CKA_TRUST_CODE_SIGNING CK_TRUST CKT_NSS_MUST_VERIFY_TRUST
+-CKA_TRUST_STEP_UP_APPROVED CK_BBOOL CK_FALSE
+-
+-#
+ # Certificate "Entrust Root Certification Authority - G2"
+ #
+ # Issuer: CN=Entrust Root Certification Authority - G2,OU="(c) 2009 Entrust, Inc. - for authorized use only",OU=See www.entrust.net/legal-terms,O="Entrust, Inc.",C=US
+ # Serial Number: 1246989352 (0x4a538c28)
+ # Subject: CN=Entrust Root Certification Authority - G2,OU="(c) 2009 Entrust, Inc. - for authorized use only",OU=See www.entrust.net/legal-terms,O="Entrust, Inc.",C=US
+ # Not Valid Before: Tue Jul 07 17:25:54 2009
+ # Not Valid After : Sat Dec 07 17:55:54 2030
+ # Fingerprint (SHA-256): 43:DF:57:74:B0:3E:7F:EF:5F:E4:0D:93:1A:7B:ED:F1:BB:2E:6B:42:73:8C:4E:6D:38:41:10:3D:3A:A7:F3:39
+@@ -18504,177 +18198,16 @@ CKA_SERIAL_NUMBER MULTILINE_OCTAL
+ \002\004\030\112\314\326
+ END
+ CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NSS_TRUSTED_DELEGATOR
+ CKA_TRUST_EMAIL_PROTECTION CK_TRUST CKT_NSS_MUST_VERIFY_TRUST
+ CKA_TRUST_CODE_SIGNING CK_TRUST CKT_NSS_MUST_VERIFY_TRUST
+ CKA_TRUST_STEP_UP_APPROVED CK_BBOOL CK_FALSE
+ 
+ #
+-# Certificate "TÜRKTRUST Elektronik Sertifika Hizmet Sağlayıcısı H5"
+-#
+-# Issuer: CN=T..RKTRUST Elektronik Sertifika Hizmet Sa..lay..c..s.. H5,O=T..RKTRUST Bilgi ..leti..im ve Bili..im G..venli..i Hizmetleri A....,L=Ankara,C=TR
+-# Serial Number:00:8e:17:fe:24:20:81
+-# Subject: CN=T..RKTRUST Elektronik Sertifika Hizmet Sa..lay..c..s.. H5,O=T..RKTRUST Bilgi ..leti..im ve Bili..im G..venli..i Hizmetleri A....,L=Ankara,C=TR
+-# Not Valid Before: Tue Apr 30 08:07:01 2013
+-# Not Valid After : Fri Apr 28 08:07:01 2023
+-# Fingerprint (SHA-256): 49:35:1B:90:34:44:C1:85:CC:DC:5C:69:3D:24:D8:55:5C:B2:08:D6:A8:14:13:07:69:9F:4A:F0:63:19:9D:78
+-# Fingerprint (SHA1): C4:18:F6:4D:46:D1:DF:00:3D:27:30:13:72:43:A9:12:11:C6:75:FB
+-CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE
+-CKA_TOKEN CK_BBOOL CK_TRUE
+-CKA_PRIVATE CK_BBOOL CK_FALSE
+-CKA_MODIFIABLE CK_BBOOL CK_FALSE
+-CKA_LABEL UTF8 "TÜRKTRUST Elektronik Sertifika Hizmet Sağlayıcısı H5"
+-CKA_CERTIFICATE_TYPE CK_CERTIFICATE_TYPE CKC_X_509
+-CKA_SUBJECT MULTILINE_OCTAL
+-\060\201\261\061\013\060\011\006\003\125\004\006\023\002\124\122
+-\061\017\060\015\006\003\125\004\007\014\006\101\156\153\141\162
+-\141\061\115\060\113\006\003\125\004\012\014\104\124\303\234\122
+-\113\124\122\125\123\124\040\102\151\154\147\151\040\304\260\154
+-\145\164\151\305\237\151\155\040\166\145\040\102\151\154\151\305
+-\237\151\155\040\107\303\274\166\145\156\154\151\304\237\151\040
+-\110\151\172\155\145\164\154\145\162\151\040\101\056\305\236\056
+-\061\102\060\100\006\003\125\004\003\014\071\124\303\234\122\113
+-\124\122\125\123\124\040\105\154\145\153\164\162\157\156\151\153
+-\040\123\145\162\164\151\146\151\153\141\040\110\151\172\155\145
+-\164\040\123\141\304\237\154\141\171\304\261\143\304\261\163\304
+-\261\040\110\065
+-END
+-CKA_ID UTF8 "0"
+-CKA_ISSUER MULTILINE_OCTAL
+-\060\201\261\061\013\060\011\006\003\125\004\006\023\002\124\122
+-\061\017\060\015\006\003\125\004\007\014\006\101\156\153\141\162
+-\141\061\115\060\113\006\003\125\004\012\014\104\124\303\234\122
+-\113\124\122\125\123\124\040\102\151\154\147\151\040\304\260\154
+-\145\164\151\305\237\151\155\040\166\145\040\102\151\154\151\305
+-\237\151\155\040\107\303\274\166\145\156\154\151\304\237\151\040
+-\110\151\172\155\145\164\154\145\162\151\040\101\056\305\236\056
+-\061\102\060\100\006\003\125\004\003\014\071\124\303\234\122\113
+-\124\122\125\123\124\040\105\154\145\153\164\162\157\156\151\153
+-\040\123\145\162\164\151\146\151\153\141\040\110\151\172\155\145
+-\164\040\123\141\304\237\154\141\171\304\261\143\304\261\163\304
+-\261\040\110\065
+-END
+-CKA_SERIAL_NUMBER MULTILINE_OCTAL
+-\002\007\000\216\027\376\044\040\201
+-END
+-CKA_VALUE MULTILINE_OCTAL
+-\060\202\004\047\060\202\003\017\240\003\002\001\002\002\007\000
+-\216\027\376\044\040\201\060\015\006\011\052\206\110\206\367\015
+-\001\001\013\005\000\060\201\261\061\013\060\011\006\003\125\004
+-\006\023\002\124\122\061\017\060\015\006\003\125\004\007\014\006
+-\101\156\153\141\162\141\061\115\060\113\006\003\125\004\012\014
+-\104\124\303\234\122\113\124\122\125\123\124\040\102\151\154\147
+-\151\040\304\260\154\145\164\151\305\237\151\155\040\166\145\040
+-\102\151\154\151\305\237\151\155\040\107\303\274\166\145\156\154
+-\151\304\237\151\040\110\151\172\155\145\164\154\145\162\151\040
+-\101\056\305\236\056\061\102\060\100\006\003\125\004\003\014\071
+-\124\303\234\122\113\124\122\125\123\124\040\105\154\145\153\164
+-\162\157\156\151\153\040\123\145\162\164\151\146\151\153\141\040
+-\110\151\172\155\145\164\040\123\141\304\237\154\141\171\304\261
+-\143\304\261\163\304\261\040\110\065\060\036\027\015\061\063\060
+-\064\063\060\060\070\060\067\060\061\132\027\015\062\063\060\064
+-\062\070\060\070\060\067\060\061\132\060\201\261\061\013\060\011
+-\006\003\125\004\006\023\002\124\122\061\017\060\015\006\003\125
+-\004\007\014\006\101\156\153\141\162\141\061\115\060\113\006\003
+-\125\004\012\014\104\124\303\234\122\113\124\122\125\123\124\040
+-\102\151\154\147\151\040\304\260\154\145\164\151\305\237\151\155
+-\040\166\145\040\102\151\154\151\305\237\151\155\040\107\303\274
+-\166\145\156\154\151\304\237\151\040\110\151\172\155\145\164\154
+-\145\162\151\040\101\056\305\236\056\061\102\060\100\006\003\125
+-\004\003\014\071\124\303\234\122\113\124\122\125\123\124\040\105
+-\154\145\153\164\162\157\156\151\153\040\123\145\162\164\151\146
+-\151\153\141\040\110\151\172\155\145\164\040\123\141\304\237\154
+-\141\171\304\261\143\304\261\163\304\261\040\110\065\060\202\001
+-\042\060\015\006\011\052\206\110\206\367\015\001\001\001\005\000
+-\003\202\001\017\000\060\202\001\012\002\202\001\001\000\244\045
+-\031\341\145\236\353\110\041\120\112\010\345\021\360\132\272\046
+-\377\203\131\316\104\052\057\376\341\316\140\003\374\215\003\245
+-\355\377\153\250\272\314\064\006\237\131\065\366\354\054\273\235
+-\373\215\122\151\343\234\047\020\123\363\244\002\305\247\371\021
+-\032\151\165\156\303\035\213\321\230\215\223\207\247\161\227\015
+-\041\307\231\371\122\323\054\143\135\125\274\350\037\001\110\271
+-\140\376\102\112\366\310\200\256\315\146\172\236\105\212\150\167
+-\342\110\150\237\242\332\361\341\301\020\237\353\074\051\201\247
+-\341\062\010\324\240\005\261\214\373\215\226\000\016\076\045\337
+-\123\206\042\073\374\364\275\363\011\176\167\354\206\353\017\063
+-\345\103\117\364\124\165\155\051\231\056\146\132\103\337\313\134
+-\312\310\345\070\361\176\073\065\235\017\364\305\132\241\314\363
+-\040\200\044\323\127\354\025\272\165\045\233\350\144\113\263\064
+-\204\357\004\270\366\311\154\252\002\076\266\125\342\062\067\137
+-\374\146\227\137\315\326\236\307\040\277\115\306\254\077\165\137
+-\034\355\062\234\174\151\000\151\221\343\043\030\123\351\002\003
+-\001\000\001\243\102\060\100\060\035\006\003\125\035\016\004\026
+-\004\024\126\231\007\036\323\254\014\151\144\264\014\120\107\336
+-\103\054\276\040\300\373\060\016\006\003\125\035\017\001\001\377
+-\004\004\003\002\001\006\060\017\006\003\125\035\023\001\001\377
+-\004\005\060\003\001\001\377\060\015\006\011\052\206\110\206\367
+-\015\001\001\013\005\000\003\202\001\001\000\236\105\166\173\027
+-\110\062\362\070\213\051\275\356\226\112\116\201\030\261\121\107
+-\040\315\320\144\261\016\311\331\001\331\011\316\310\231\334\150
+-\045\023\324\134\362\243\350\004\376\162\011\307\013\252\035\045
+-\125\176\226\232\127\267\272\305\021\172\031\346\247\176\075\205
+-\016\365\371\056\051\057\347\371\154\130\026\127\120\045\366\076
+-\056\076\252\355\167\161\252\252\231\226\106\012\256\216\354\052
+-\121\026\260\136\315\352\147\004\034\130\060\365\140\212\275\246
+-\275\115\345\226\264\374\102\211\001\153\366\160\310\120\071\014
+-\055\325\146\331\310\322\263\062\267\033\031\155\313\063\371\337
+-\245\346\025\204\067\360\302\362\145\226\222\220\167\360\255\364
+-\220\351\021\170\327\223\211\300\075\013\272\051\364\350\231\235
+-\162\216\355\235\057\356\222\175\241\361\377\135\272\063\140\205
+-\142\376\007\002\241\204\126\106\276\226\012\232\023\327\041\114
+-\267\174\007\237\116\116\077\221\164\373\047\235\021\314\335\346
+-\261\312\161\115\023\027\071\046\305\051\041\053\223\051\152\226
+-\372\253\101\341\113\266\065\013\300\233\025
+-END
+-CKA_NSS_MOZILLA_CA_POLICY CK_BBOOL CK_TRUE
+-
+-# Trust for "TÜRKTRUST Elektronik Sertifika Hizmet Sağlayıcısı H5"
+-# Issuer: CN=T..RKTRUST Elektronik Sertifika Hizmet Sa..lay..c..s.. H5,O=T..RKTRUST Bilgi ..leti..im ve Bili..im G..venli..i Hizmetleri A....,L=Ankara,C=TR
+-# Serial Number:00:8e:17:fe:24:20:81
+-# Subject: CN=T..RKTRUST Elektronik Sertifika Hizmet Sa..lay..c..s.. H5,O=T..RKTRUST Bilgi ..leti..im ve Bili..im G..venli..i Hizmetleri A....,L=Ankara,C=TR
+-# Not Valid Before: Tue Apr 30 08:07:01 2013
+-# Not Valid After : Fri Apr 28 08:07:01 2023
+-# Fingerprint (SHA-256): 49:35:1B:90:34:44:C1:85:CC:DC:5C:69:3D:24:D8:55:5C:B2:08:D6:A8:14:13:07:69:9F:4A:F0:63:19:9D:78
+-# Fingerprint (SHA1): C4:18:F6:4D:46:D1:DF:00:3D:27:30:13:72:43:A9:12:11:C6:75:FB
+-CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST
+-CKA_TOKEN CK_BBOOL CK_TRUE
+-CKA_PRIVATE CK_BBOOL CK_FALSE
+-CKA_MODIFIABLE CK_BBOOL CK_FALSE
+-CKA_LABEL UTF8 "TÜRKTRUST Elektronik Sertifika Hizmet Sağlayıcısı H5"
+-CKA_CERT_SHA1_HASH MULTILINE_OCTAL
+-\304\030\366\115\106\321\337\000\075\047\060\023\162\103\251\022
+-\021\306\165\373
+-END
+-CKA_CERT_MD5_HASH MULTILINE_OCTAL
+-\332\160\216\360\042\337\223\046\366\137\237\323\025\006\122\116
+-END
+-CKA_ISSUER MULTILINE_OCTAL
+-\060\201\261\061\013\060\011\006\003\125\004\006\023\002\124\122
+-\061\017\060\015\006\003\125\004\007\014\006\101\156\153\141\162
+-\141\061\115\060\113\006\003\125\004\012\014\104\124\303\234\122
+-\113\124\122\125\123\124\040\102\151\154\147\151\040\304\260\154
+-\145\164\151\305\237\151\155\040\166\145\040\102\151\154\151\305
+-\237\151\155\040\107\303\274\166\145\156\154\151\304\237\151\040
+-\110\151\172\155\145\164\154\145\162\151\040\101\056\305\236\056
+-\061\102\060\100\006\003\125\004\003\014\071\124\303\234\122\113
+-\124\122\125\123\124\040\105\154\145\153\164\162\157\156\151\153
+-\040\123\145\162\164\151\146\151\153\141\040\110\151\172\155\145
+-\164\040\123\141\304\237\154\141\171\304\261\143\304\261\163\304
+-\261\040\110\065
+-END
+-CKA_SERIAL_NUMBER MULTILINE_OCTAL
+-\002\007\000\216\027\376\044\040\201
+-END
+-CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NSS_TRUSTED_DELEGATOR
+-CKA_TRUST_EMAIL_PROTECTION CK_TRUST CKT_NSS_MUST_VERIFY_TRUST
+-CKA_TRUST_CODE_SIGNING CK_TRUST CKT_NSS_MUST_VERIFY_TRUST
+-CKA_TRUST_STEP_UP_APPROVED CK_BBOOL CK_FALSE
+-
+-#
+ # Certificate "Certinomis - Root CA"
+ #
+ # Issuer: CN=Certinomis - Root CA,OU=0002 433998903,O=Certinomis,C=FR
+ # Serial Number: 1 (0x1)
+ # Subject: CN=Certinomis - Root CA,OU=0002 433998903,O=Certinomis,C=FR
+ # Not Valid Before: Mon Oct 21 09:17:18 2013
+ # Not Valid After : Fri Oct 21 09:17:18 2033
+ # Fingerprint (SHA-256): 2A:99:F5:BC:11:74:B7:3C:BB:1D:62:08:84:E0:1C:34:E5:1C:CB:39:78:DA:12:5F:0E:33:26:88:83:BF:41:58
+diff --git a/security/nss/lib/ckfw/builtins/nssckbi.h b/security/nss/lib/ckfw/builtins/nssckbi.h
+--- a/security/nss/lib/ckfw/builtins/nssckbi.h
++++ b/security/nss/lib/ckfw/builtins/nssckbi.h
+@@ -41,18 +41,18 @@
+  *   made on that branch.
+  *
+  * NSS_BUILTINS_LIBRARY_VERSION_MINOR is a CK_BYTE.  It's not clear
+  * whether we may use its full range (0-255) or only 0-99 because
+  * of the comment in the CK_VERSION type definition.
+  * It's recommend to switch back to 0 after having reached version 98/99.
+  */
+ #define NSS_BUILTINS_LIBRARY_VERSION_MAJOR 2
+-#define NSS_BUILTINS_LIBRARY_VERSION_MINOR 22
+-#define NSS_BUILTINS_LIBRARY_VERSION "2.22"
++#define NSS_BUILTINS_LIBRARY_VERSION_MINOR 24
++#define NSS_BUILTINS_LIBRARY_VERSION "2.24"
+ 
+ /* These version numbers detail the semantic changes to the ckfw engine. */
+ #define NSS_BUILTINS_HARDWARE_VERSION_MAJOR 1
+ #define NSS_BUILTINS_HARDWARE_VERSION_MINOR 0
+ 
+ /* These version numbers detail the semantic changes to ckbi itself
+  * (new PKCS #11 objects), etc. */
+ #define NSS_BUILTINS_FIRMWARE_VERSION_MAJOR 1
+diff --git a/security/nss/lib/freebl/verified/Hacl_Poly1305_32.c b/security/nss/lib/freebl/verified/Hacl_Poly1305_32.c
+--- a/security/nss/lib/freebl/verified/Hacl_Poly1305_32.c
++++ b/security/nss/lib/freebl/verified/Hacl_Poly1305_32.c
+@@ -54,17 +54,19 @@ Hacl_Bignum_Fproduct_copy_from_wide_(uin
+ }
+ 
+ inline static void
+ Hacl_Bignum_Fproduct_sum_scalar_multiplication_(uint64_t *output, uint32_t *input, uint32_t s)
+ {
+     for (uint32_t i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U) {
+         uint64_t xi = output[i];
+         uint32_t yi = input[i];
+-        output[i] = xi + (uint64_t)yi * (uint64_t)s;
++        uint64_t x_wide = (uint64_t)yi;
++        uint64_t y_wide = (uint64_t)s;
++        output[i] = xi + x_wide * y_wide;
+     }
+ }
+ 
+ inline static void
+ Hacl_Bignum_Fproduct_carry_wide_(uint64_t *tmp)
+ {
+     for (uint32_t i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U) {
+         uint32_t ctr = i;
+diff --git a/security/nss/lib/ssl/SSLerrs.h b/security/nss/lib/ssl/SSLerrs.h
+--- a/security/nss/lib/ssl/SSLerrs.h
++++ b/security/nss/lib/ssl/SSLerrs.h
+@@ -538,8 +538,14 @@ ER3(SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE, 
+ ER3(SSL_ERROR_RX_MALFORMED_KEY_UPDATE, (SSL_ERROR_BASE + 170),
+     "SSL received a malformed key update message.")
+ 
+ ER3(SSL_ERROR_TOO_MANY_KEY_UPDATES, (SSL_ERROR_BASE + 171),
+     "SSL attempted too many key updates.")
+ 
+ ER3(SSL_ERROR_HANDSHAKE_FAILED, (SSL_ERROR_BASE + 172),
+     "SSL handshake has already failed. No more operations possible.")
++
++ER3(SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR, (SSL_ERROR_BASE + 173),
++    "SSL received an invalid resumption token.")
++
++ER3(SSL_ERROR_RX_MALFORMED_DTLS_ACK, (SSL_ERROR_BASE + 174),
++    "SSL received a malformed DTLS ACK")
+diff --git a/security/nss/lib/ssl/dtls13con.c b/security/nss/lib/ssl/dtls13con.c
+--- a/security/nss/lib/ssl/dtls13con.c
++++ b/security/nss/lib/ssl/dtls13con.c
+@@ -114,33 +114,43 @@ dtls13_RememberFragment(sslSocket *ss,
+ 
+ SECStatus
+ dtls13_SendAck(sslSocket *ss)
+ {
+     sslBuffer buf = SSL_BUFFER_EMPTY;
+     SECStatus rv = SECSuccess;
+     PRCList *cursor;
+     PRInt32 sent;
++    unsigned int offset;
+ 
+     SSL_TRC(10, ("%d: SSL3[%d]: Sending ACK",
+                  SSL_GETPID(), ss->fd));
+ 
++    rv = sslBuffer_Skip(&buf, 2, &offset);
++    if (rv != SECSuccess) {
++        goto loser;
++    }
+     for (cursor = PR_LIST_HEAD(&ss->ssl3.hs.dtlsRcvdHandshake);
+          cursor != &ss->ssl3.hs.dtlsRcvdHandshake;
+          cursor = PR_NEXT_LINK(cursor)) {
+         DTLSHandshakeRecordEntry *entry = (DTLSHandshakeRecordEntry *)cursor;
+ 
+         SSL_TRC(10, ("%d: SSL3[%d]: ACK for record=%llx",
+                      SSL_GETPID(), ss->fd, entry->record));
+         rv = sslBuffer_AppendNumber(&buf, entry->record, 8);
+         if (rv != SECSuccess) {
+             goto loser;
+         }
+     }
+ 
++    rv = sslBuffer_InsertLength(&buf, offset, 2);
++    if (rv != SECSuccess) {
++        goto loser;
++    }
++
+     ssl_GetXmitBufLock(ss);
+     sent = ssl3_SendRecord(ss, NULL, content_ack,
+                            buf.buf, buf.len, 0);
+     ssl_ReleaseXmitBufLock(ss);
+     if (sent != buf.len) {
+         rv = SECFailure;
+         if (sent != -1) {
+             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+@@ -396,28 +406,38 @@ dtls13_HandleOutOfEpochRecord(sslSocket 
+     return SECFailure;
+ }
+ 
+ SECStatus
+ dtls13_HandleAck(sslSocket *ss, sslBuffer *databuf)
+ {
+     PRUint8 *b = databuf->buf;
+     PRUint32 l = databuf->len;
++    unsigned int length;
+     SECStatus rv;
+ 
+     /* Ensure we don't loop. */
+     databuf->len = 0;
+ 
+     PORT_Assert(IS_DTLS(ss));
+     if (!tls13_MaybeTls13(ss)) {
+         tls13_FatalError(ss, SSL_ERROR_RX_UNKNOWN_RECORD_TYPE, illegal_parameter);
+-        return SECSuccess;
++        return SECFailure;
+     }
+ 
+     SSL_TRC(10, ("%d: SSL3[%d]: Handling ACK", SSL_GETPID(), ss->fd));
++    rv = ssl3_ConsumeHandshakeNumber(ss, &length, 2, &b, &l);
++    if (rv != SECSuccess) {
++        return SECFailure;
++    }
++    if (length != l) {
++        tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_DTLS_ACK, decode_error);
++        return SECFailure;
++    }
++
+     while (l > 0) {
+         PRUint64 seq;
+         PRCList *cursor;
+ 
+         rv = ssl3_ConsumeHandshakeNumber64(ss, &seq, 8, &b, &l);
+         if (rv != SECSuccess) {
+             return SECFailure;
+         }
+diff --git a/security/nss/lib/ssl/ssl3con.c b/security/nss/lib/ssl/ssl3con.c
+--- a/security/nss/lib/ssl/ssl3con.c
++++ b/security/nss/lib/ssl/ssl3con.c
+@@ -6152,16 +6152,48 @@ ssl_ClientSetCipherSuite(sslSocket *ss, 
+         PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
+         return SECFailure;
+     }
+ 
+     ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)suite;
+     return ssl3_SetupCipherSuite(ss, initHashes);
+ }
+ 
++/* Check that session ID we received from the server, if any, matches our
++ * expectations, depending on whether we're in compat mode and whether we
++ * negotiated TLS 1.3+ or TLS 1.2-.
++ */
++static PRBool
++ssl_CheckServerSessionIdCorrectness(sslSocket *ss, SECItem *sidBytes)
++{
++    PRBool sid_match = PR_FALSE;
++    PRBool sent_fake_sid = ss->opt.enableTls13CompatMode && !IS_DTLS(ss);
++
++    /* If in compat mode and we received a session ID with the right length
++     * then compare it to the fake one we sent in the ClientHello. */
++    if (sent_fake_sid && sidBytes->len == SSL3_SESSIONID_BYTES) {
++        PRUint8 buf[SSL3_SESSIONID_BYTES];
++        ssl_MakeFakeSid(ss, buf);
++        sid_match = PORT_Memcmp(buf, sidBytes->data, sidBytes->len) == 0;
++    }
++
++    /* TLS 1.2: SessionID shouldn't match the fake one. */
++    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
++        return !sid_match;
++    }
++
++    /* TLS 1.3: [Compat Mode] Session ID should match the fake one. */
++    if (sent_fake_sid) {
++        return sid_match;
++    }
++
++    /* TLS 1.3: [Non-Compat Mode] Server shouldn't send a session ID. */
++    return sidBytes->len == 0;
++}
++
+ /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
+  * ssl3 ServerHello message.
+  * Caller must hold Handshake and RecvBuf locks.
+  */
+ static SECStatus
+ ssl3_HandleServerHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
+ {
+     PRUint32 cipher;
+@@ -6353,32 +6385,20 @@ ssl3_HandleServerHello(sslSocket *ss, PR
+      * in which case this is a no-op. */
+     if (!ss->firstHsDone && !isHelloRetry) {
+         ssl_GetSpecWriteLock(ss);
+         ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
+         ssl_ReleaseSpecWriteLock(ss);
+     }
+ 
+     /* Check that the session ID is as expected. */
+-    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+-        PRUint8 buf[SSL3_SESSIONID_BYTES];
+-        unsigned int expectedSidLen;
+-        if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
+-            expectedSidLen = SSL3_SESSIONID_BYTES;
+-            ssl_MakeFakeSid(ss, buf);
+-        } else {
+-            expectedSidLen = 0;
+-        }
+-        if (sidBytes.len != expectedSidLen ||
+-            (expectedSidLen > 0 &&
+-             PORT_Memcmp(buf, sidBytes.data, expectedSidLen) != 0)) {
+-            desc = illegal_parameter;
+-            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+-            goto alert_loser;
+-        }
++    if (!ssl_CheckServerSessionIdCorrectness(ss, &sidBytes)) {
++        desc = illegal_parameter;
++        errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
++        goto alert_loser;
+     }
+ 
+     /* Only initialize hashes if this isn't a Hello Retry. */
+     rv = ssl_ClientSetCipherSuite(ss, ss->version, cipher,
+                                   !isHelloRetry);
+     if (rv != SECSuccess) {
+         desc = illegal_parameter;
+         errCode = PORT_GetError();
+diff --git a/security/nss/lib/ssl/sslerr.h b/security/nss/lib/ssl/sslerr.h
+--- a/security/nss/lib/ssl/sslerr.h
++++ b/security/nss/lib/ssl/sslerr.h
+@@ -257,15 +257,16 @@ typedef enum {
+     SSL_ERROR_NO_TIMERS_FOUND = (SSL_ERROR_BASE + 167),
+     SSL_ERROR_MISSING_COOKIE_EXTENSION = (SSL_ERROR_BASE + 168),
+ 
+     SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE = (SSL_ERROR_BASE + 169),
+     SSL_ERROR_RX_MALFORMED_KEY_UPDATE = (SSL_ERROR_BASE + 170),
+     SSL_ERROR_TOO_MANY_KEY_UPDATES = (SSL_ERROR_BASE + 171),
+     SSL_ERROR_HANDSHAKE_FAILED = (SSL_ERROR_BASE + 172),
+     SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR = (SSL_ERROR_BASE + 173),
++    SSL_ERROR_RX_MALFORMED_DTLS_ACK = (SSL_ERROR_BASE + 174),
+     SSL_ERROR_END_OF_LIST   /* let the c compiler determine the value of this. */
+ } SSLErrorCodes;
+ #endif /* NO_SECURITY_ERROR_ENUM */
+ 
+ /* clang-format on */
+ 
+ #endif /* __SSL_ERR_H_ */
+diff --git a/security/nss/lib/ssl/tls13con.c b/security/nss/lib/ssl/tls13con.c
+--- a/security/nss/lib/ssl/tls13con.c
++++ b/security/nss/lib/ssl/tls13con.c
+@@ -3815,23 +3815,24 @@ tls13_HandleCertificateVerify(sslSocket 
+     rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
+     if (rv != SECSuccess) {
+         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+         return SECFailure;
+     }
+ 
+     rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
+     if (rv != SECSuccess) {
+-        PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_VERIFY);
++        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY, illegal_parameter);
+         return SECFailure;
+     }
+ 
+     rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme, ss->sec.peerCert);
+     if (rv != SECSuccess) {
+         /* Error set already */
++        FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
+         return SECFailure;
+     }
+     hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
+ 
+     rv = tls13_AddContextToHashes(ss, &hashes, hashAlg, PR_FALSE, &tbsHash);
+     if (rv != SECSuccess) {
+         FATAL_ERROR(ss, SSL_ERROR_DIGEST_FAILURE, internal_error);
+         return SECFailure;
+diff --git a/security/nss/mach b/security/nss/mach
+--- a/security/nss/mach
++++ b/security/nss/mach
+@@ -98,17 +98,17 @@ class cfAction(argparse.Action):
+             from distutils.spawn import find_executable
+             self.restorecon = find_executable('restorecon')
+             self.docker_command = ["sudo"] + self.docker_command
+ 
+     def modifiedFiles(self):
+         files = []
+         if os.path.exists(os.path.join(cwd, '.hg')):
+             st = subprocess.Popen(['hg', 'status', '-m', '-a'],
+-                                  cwd=cwd, stdout=subprocess.PIPE)
++                                  cwd=cwd, stdout=subprocess.PIPE, universal_newlines=True)
+             for line in iter(st.stdout.readline, ''):
+                 files += [line[2:].rstrip()]
+         elif os.path.exists(os.path.join(cwd, '.git')):
+             st = subprocess.Popen(['git', 'status', '--porcelain'],
+                                   cwd=cwd, stdout=subprocess.PIPE)
+             for line in iter(st.stdout.readline, ''):
+                 if line[1] == 'M' or line[1] != 'D' and \
+                         (line[0] == 'M' or line[0] == 'A' or
+@@ -189,17 +189,17 @@ def parse_arguments():
+         help="Specify files or directories to run clang-format on",
+         action=cfAction)
+ 
+     parser_test = subparsers.add_parser(
+         'tests', help='Run tests through tests/all.sh.')
+     tests = [
+         "cipher", "lowhash", "chains", "cert", "dbtests", "tools", "fips",
+         "sdr", "crmf", "smime", "ssl", "ocsp", "merge", "pkits", "ec",
+-        "gtests", "ssl_gtests"
++        "gtests", "ssl_gtests", "bogo"
+     ]
+     parser_test.add_argument(
+         'test', choices=tests, help="Available tests", action=testAction)
+ 
+     parser_commands = subparsers.add_parser(
+         'mach-commands',
+         help="list commands")
+     parser_commands.add_argument(
+diff --git a/security/nss/tests/bogo/bogo.sh b/security/nss/tests/bogo/bogo.sh
+--- a/security/nss/tests/bogo/bogo.sh
++++ b/security/nss/tests/bogo/bogo.sh
+@@ -34,20 +34,21 @@ bogo_init()
+ 
+ bogo_cleanup()
+ {
+   html "</TABLE><BR>"
+   cd ${QADIR}
+   . common/cleanup.sh
+ }
+ 
+-cd "$(dirname "$0")"
+-SOURCE_DIR="$PWD"/../..
++cd ../
++cwd=$(cd $(dirname $0); pwd -P)
++SOURCE_DIR="$cwd"/..
+ bogo_init
+ (cd "$BORING"/ssl/test/runner;
+- GOPATH="$PWD" go test -pipe -shim-path "${BINDIR}"/nss_bogo_shim \
++ GOPATH="$cwd" go test -pipe -shim-path "${BINDIR}"/nss_bogo_shim \
+ 	 -loose-errors -allow-unimplemented \
+ 	 -shim-config "${SOURCE_DIR}/gtests/nss_bogo_shim/config.json") \
+ 	 2>bogo.errors | tee bogo.log
+ html_msg "${PIPESTATUS[0]}" 0 "Bogo" "Run successfully"
+ grep -i 'FAILED\|Assertion failure' bogo.errors
+ html_msg $? 1 "Bogo" "No failures"
+ bogo_cleanup

+ 1532 - 0
rel-257/ian/patches/1445731-8-NSS337-61a1.patch

@@ -0,0 +1,1532 @@
+# HG changeset patch
+# User Tim Taubert <ttaubert@mozilla.com>
+# Date 1523866152 -7200
+#      Mon Apr 16 10:09:12 2018 +0200
+# Node ID c6757ad801fedaff8606b6ae34a276ce08714ce8
+# Parent  ac685df07bfc81d80f81e40d7cac55cbf56d84c1
+Bug 1445731 - land NSS c1a4035420c3 UPGRADE_NSS_RELEASE, r=me
+
+diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO
+--- a/security/nss/TAG-INFO
++++ b/security/nss/TAG-INFO
+@@ -1,1 +1,1 @@
+-2eefd697d661
++c1a4035420c3
+diff --git a/security/nss/automation/taskcluster/graph/src/extend.js b/security/nss/automation/taskcluster/graph/src/extend.js
+--- a/security/nss/automation/taskcluster/graph/src/extend.js
++++ b/security/nss/automation/taskcluster/graph/src/extend.js
+@@ -990,23 +990,23 @@ async function scheduleTools() {
+     command: [
+       "/bin/bash",
+       "-c",
+       "bin/checkout.sh && nss/automation/clang-format/run_clang_format.sh"
+     ]
+   }));
+ 
+   queue.scheduleTask(merge(base, {
+-    symbol: "scan-build-5.0",
+-    name: "scan-build-5.0",
+-    image: LINUX_IMAGE,
++    symbol: "scan-build",
++    name: "scan-build",
++    image: FUZZ_IMAGE,
+     env: {
+       USE_64: "1",
+-      CC: "clang-5.0",
+-      CCC: "clang++-5.0",
++      CC: "clang",
++      CCC: "clang++",
+     },
+     artifacts: {
+       public: {
+         expires: 24 * 7,
+         type: "directory",
+         path: "/home/worker/artifacts"
+       }
+     },
+@@ -1087,10 +1087,22 @@ async function scheduleTools() {
+     image: SAW_IMAGE,
+     command: [
+       "/bin/bash",
+       "-c",
+       "bin/checkout.sh && nss/automation/taskcluster/scripts/run_saw.sh poly1305"
+     ]
+   }));
+ 
++  queue.scheduleTask(merge(base, {
++    symbol: "Coverage",
++    name: "Coverage",
++    image: FUZZ_IMAGE,
++    features: ["allowPtrace"],
++    command: [
++      "/bin/bash",
++      "-c",
++      "bin/checkout.sh && nss/automation/taskcluster/scripts/gen_coverage_report.sh"
++    ]
++  }));
++
+   return queue.submit();
+ }
+diff --git a/security/nss/automation/taskcluster/graph/src/try_syntax.js b/security/nss/automation/taskcluster/graph/src/try_syntax.js
+--- a/security/nss/automation/taskcluster/graph/src/try_syntax.js
++++ b/security/nss/automation/taskcluster/graph/src/try_syntax.js
+@@ -46,17 +46,17 @@ function parseOptions(opts) {
+   // If it's nonsense then don't run any tests.
+   if (opts.unittests == "all") {
+     unittests = allUnitTests;
+   } else if (unittests.length == 0) {
+     unittests = [];
+   }
+ 
+   // Parse tools.
+-  let allTools = ["clang-format", "scan-build", "hacl", "saw", "abi"];
++  let allTools = ["clang-format", "scan-build", "hacl", "saw", "abi", "coverage"];
+   let tools = intersect(opts.tools.split(/\s*,\s*/), allTools);
+ 
+   // If the given value is "all" run all tools.
+   // If it's nonsense then don't run any tools.
+   if (opts.tools == "all") {
+     tools = allTools;
+   } else if (tools.length == 0) {
+     tools = [];
+diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep
+--- a/security/nss/coreconf/coreconf.dep
++++ b/security/nss/coreconf/coreconf.dep
+@@ -5,8 +5,9 @@
+ 
+ /*
+  * A dummy header file that is a dependency for all the object files.
+  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
+  * depend builds.  See comments in rules.mk.
+  */
+ 
+ #error "Do not include this header file."
++
+diff --git a/security/nss/gtests/ssl_gtest/ssl_0rtt_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_0rtt_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_0rtt_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_0rtt_unittest.cc
+@@ -340,18 +340,18 @@ TEST_P(TlsConnectTls13, TestTls13ZeroRtt
+   }
+   client_->CheckErrorCode(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
+ }
+ 
+ // Remove the old ALPN value and so the client will not offer early data.
+ TEST_P(TlsConnectTls13, TestTls13ZeroRttAlpnChangeBoth) {
+   EnableAlpn();
+   SetupForZeroRtt();
+-  static const uint8_t alpn[] = {0x01, 0x62};  // "b"
+-  EnableAlpn(alpn, sizeof(alpn));
++  static const std::vector<uint8_t> alpn({0x01, 0x62});  // "b"
++  EnableAlpn(alpn);
+   client_->Set0RttEnabled(true);
+   server_->Set0RttEnabled(true);
+   ExpectResumption(RESUME_TICKET);
+   ZeroRttSendReceive(true, false, [this]() {
+     client_->CheckAlpn(SSL_NEXT_PROTO_NO_SUPPORT);
+     return false;
+   });
+   Handshake();
+diff --git a/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_ecdh_unittest.cc
+@@ -554,16 +554,77 @@ TEST_P(TlsConnectGenericPre13, ConnectEC
+ }
+ 
+ TEST_P(TlsConnectGenericPre13, ConnectECDHEmptyClientPoint) {
+   MakeTlsFilter<ECCClientKEXFilter>(client_);
+   ConnectExpectAlert(server_, kTlsAlertIllegalParameter);
+   server_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_CLIENT_KEY_EXCH);
+ }
+ 
++// Damage ECParams/ECPoint of a SKE.
++class ECCServerKEXDamager : public TlsHandshakeFilter {
++ public:
++  ECCServerKEXDamager(const std::shared_ptr<TlsAgent> &server, ECType ec_type,
++                      SSLNamedGroup named_curve)
++      : TlsHandshakeFilter(server, {kTlsHandshakeServerKeyExchange}),
++        ec_type_(ec_type),
++        named_curve_(named_curve) {}
++
++ protected:
++  virtual PacketFilter::Action FilterHandshake(const HandshakeHeader &header,
++                                               const DataBuffer &input,
++                                               DataBuffer *output) {
++    size_t offset = 0;
++    output->Allocate(5);
++    offset = output->Write(offset, ec_type_, 1);
++    offset = output->Write(offset, named_curve_, 2);
++    // Write a point with fmt != EC_POINT_FORM_UNCOMPRESSED.
++    offset = output->Write(offset, 1U, 1);
++    (void)output->Write(offset, 0x02, 1);  // EC_POINT_FORM_COMPRESSED_Y0
++    return CHANGE;
++  }
++
++ private:
++  ECType ec_type_;
++  SSLNamedGroup named_curve_;
++};
++
++TEST_P(TlsConnectGenericPre13, ConnectUnsupportedCurveType) {
++  EnsureTlsSetup();
++  client_->DisableAllCiphers();
++  client_->EnableCiphersByKeyExchange(ssl_kea_ecdh);
++
++  MakeTlsFilter<ECCServerKEXDamager>(server_, ec_type_explicitPrime,
++                                     ssl_grp_none);
++  ConnectExpectAlert(client_, kTlsAlertHandshakeFailure);
++  client_->CheckErrorCode(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE);
++}
++
++TEST_P(TlsConnectGenericPre13, ConnectUnsupportedCurve) {
++  EnsureTlsSetup();
++  client_->DisableAllCiphers();
++  client_->EnableCiphersByKeyExchange(ssl_kea_ecdh);
++
++  MakeTlsFilter<ECCServerKEXDamager>(server_, ec_type_named,
++                                     ssl_grp_ffdhe_2048);
++  ConnectExpectAlert(client_, kTlsAlertHandshakeFailure);
++  client_->CheckErrorCode(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE);
++}
++
++TEST_P(TlsConnectGenericPre13, ConnectUnsupportedPointFormat) {
++  EnsureTlsSetup();
++  client_->DisableAllCiphers();
++  client_->EnableCiphersByKeyExchange(ssl_kea_ecdh);
++
++  MakeTlsFilter<ECCServerKEXDamager>(server_, ec_type_named,
++                                     ssl_grp_ec_secp256r1);
++  ConnectExpectAlert(client_, kTlsAlertHandshakeFailure);
++  client_->CheckErrorCode(SEC_ERROR_UNSUPPORTED_EC_POINT_FORM);
++}
++
+ INSTANTIATE_TEST_CASE_P(KeyExchangeTest, TlsKeyExchangeTest,
+                         ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll,
+                                            TlsConnectTestBase::kTlsV11Plus));
+ 
+ #ifndef NSS_DISABLE_TLS_1_3
+ INSTANTIATE_TEST_CASE_P(KeyExchangeTest, TlsKeyExchangeTest13,
+                         ::testing::Combine(TlsConnectTestBase::kTlsVariantsAll,
+                                            TlsConnectTestBase::kTlsV13));
+diff --git a/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc b/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc
+--- a/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc
++++ b/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc
+@@ -144,24 +144,72 @@ TEST_P(TlsConnectGenericPre13, ConnectFa
+ }
+ 
+ TEST_P(TlsConnectGeneric, ConnectAlpn) {
+   EnableAlpn();
+   Connect();
+   CheckAlpn("a");
+ }
+ 
++TEST_P(TlsConnectGeneric, ConnectAlpnPriorityA) {
++  // "alpn" "npn"
++  // alpn is the fallback here. npn has the highest priority and should be
++  // picked.
++  const std::vector<uint8_t> alpn = {0x04, 0x61, 0x6c, 0x70, 0x6e,
++                                     0x03, 0x6e, 0x70, 0x6e};
++  EnableAlpn(alpn);
++  Connect();
++  CheckAlpn("npn");
++}
++
++TEST_P(TlsConnectGeneric, ConnectAlpnPriorityB) {
++  // "alpn" "npn" "http"
++  // npn has the highest priority and should be picked.
++  const std::vector<uint8_t> alpn = {0x04, 0x61, 0x6c, 0x70, 0x6e, 0x03, 0x6e,
++                                     0x70, 0x6e, 0x04, 0x68, 0x74, 0x74, 0x70};
++  EnableAlpn(alpn);
++  Connect();
++  CheckAlpn("npn");
++}
++
+ TEST_P(TlsConnectGeneric, ConnectAlpnClone) {
+   EnsureModelSockets();
+   client_model_->EnableAlpn(alpn_dummy_val_, sizeof(alpn_dummy_val_));
+   server_model_->EnableAlpn(alpn_dummy_val_, sizeof(alpn_dummy_val_));
+   Connect();
+   CheckAlpn("a");
+ }
+ 
++TEST_P(TlsConnectGeneric, ConnectAlpnWithCustomCallbackA) {
++  // "ab" "alpn"
++  const std::vector<uint8_t> client_alpn = {0x02, 0x61, 0x62, 0x04,
++                                            0x61, 0x6c, 0x70, 0x6e};
++  EnableAlpnWithCallback(client_alpn, "alpn");
++  Connect();
++  CheckAlpn("alpn");
++}
++
++TEST_P(TlsConnectGeneric, ConnectAlpnWithCustomCallbackB) {
++  // "ab" "alpn"
++  const std::vector<uint8_t> client_alpn = {0x02, 0x61, 0x62, 0x04,
++                                            0x61, 0x6c, 0x70, 0x6e};
++  EnableAlpnWithCallback(client_alpn, "ab");
++  Connect();
++  CheckAlpn("ab");
++}
++
++TEST_P(TlsConnectGeneric, ConnectAlpnWithCustomCallbackC) {
++  // "cd" "npn" "alpn"
++  const std::vector<uint8_t> client_alpn = {0x02, 0x63, 0x64, 0x03, 0x6e, 0x70,
++                                            0x6e, 0x04, 0x61, 0x6c, 0x70, 0x6e};
++  EnableAlpnWithCallback(client_alpn, "npn");
++  Connect();
++  CheckAlpn("npn");
++}
++
+ TEST_P(TlsConnectDatagram, ConnectSrtp) {
+   EnableSrtp();
+   Connect();
+   CheckSrtp();
+   SendReceive();
+ }
+ 
+ TEST_P(TlsConnectGeneric, ConnectSendReceive) {
+diff --git a/security/nss/gtests/ssl_gtest/tls_agent.cc b/security/nss/gtests/ssl_gtest/tls_agent.cc
+--- a/security/nss/gtests/ssl_gtest/tls_agent.cc
++++ b/security/nss/gtests/ssl_gtest/tls_agent.cc
+@@ -594,32 +594,30 @@ void TlsAgent::EnableFalseStart() {
+                             ssl_fd(), CanFalseStartCallback, this));
+   SetOption(SSL_ENABLE_FALSE_START, PR_TRUE);
+ }
+ 
+ void TlsAgent::ExpectResumption() { expect_resumption_ = true; }
+ 
+ void TlsAgent::EnableAlpn(const uint8_t* val, size_t len) {
+   EXPECT_TRUE(EnsureTlsSetup());
+-
+-  SetOption(SSL_ENABLE_ALPN, PR_TRUE);
+   EXPECT_EQ(SECSuccess, SSL_SetNextProtoNego(ssl_fd(), val, len));
+ }
+ 
+ void TlsAgent::CheckAlpn(SSLNextProtoState expected_state,
+                          const std::string& expected) const {
+-  SSLNextProtoState npn_state;
++  SSLNextProtoState alpn_state;
+   char chosen[10];
+   unsigned int chosen_len;
+-  SECStatus rv = SSL_GetNextProto(ssl_fd(), &npn_state,
++  SECStatus rv = SSL_GetNextProto(ssl_fd(), &alpn_state,
+                                   reinterpret_cast<unsigned char*>(chosen),
+                                   &chosen_len, sizeof(chosen));
+   EXPECT_EQ(SECSuccess, rv);
+-  EXPECT_EQ(expected_state, npn_state);
+-  if (npn_state == SSL_NEXT_PROTO_NO_SUPPORT) {
++  EXPECT_EQ(expected_state, alpn_state);
++  if (alpn_state == SSL_NEXT_PROTO_NO_SUPPORT) {
+     EXPECT_EQ("", expected);
+   } else {
+     EXPECT_NE("", expected);
+     EXPECT_EQ(expected, std::string(chosen, chosen_len));
+   }
+ }
+ 
+ void TlsAgent::EnableSrtp() {
+diff --git a/security/nss/gtests/ssl_gtest/tls_agent.h b/security/nss/gtests/ssl_gtest/tls_agent.h
+--- a/security/nss/gtests/ssl_gtest/tls_agent.h
++++ b/security/nss/gtests/ssl_gtest/tls_agent.h
+@@ -263,16 +263,18 @@ class TlsAgent : public PollTarget {
+ 
+   void SetSniCallback(SniCallbackFunction sni_callback) {
+     sni_callback_ = sni_callback;
+   }
+ 
+   void ExpectReceiveAlert(uint8_t alert, uint8_t level = 0);
+   void ExpectSendAlert(uint8_t alert, uint8_t level = 0);
+ 
++  std::string alpn_value_to_use_ = "";
++
+  private:
+   const static char* states[];
+ 
+   void SetState(State state);
+   void ValidateCipherSpecs();
+ 
+   // Dummy auth certificate hook.
+   static SECStatus AuthCertificateHook(void* arg, PRFileDesc* fd,
+diff --git a/security/nss/gtests/ssl_gtest/tls_connect.cc b/security/nss/gtests/ssl_gtest/tls_connect.cc
+--- a/security/nss/gtests/ssl_gtest/tls_connect.cc
++++ b/security/nss/gtests/ssl_gtest/tls_connect.cc
+@@ -566,24 +566,67 @@ void TlsConnectTestBase::CheckResumption
+                 session_ids_[session_ids_.size() - 2]);
+     } else {
+       // TLS 1.3 only uses tickets.
+       EXPECT_TRUE(expected & RESUME_TICKET);
+     }
+   }
+ }
+ 
++static SECStatus NextProtoCallbackServer(void* arg, PRFileDesc* fd,
++                                         const unsigned char* protos,
++                                         unsigned int protos_len,
++                                         unsigned char* protoOut,
++                                         unsigned int* protoOutLen,
++                                         unsigned int protoMaxLen) {
++  EXPECT_EQ(protoMaxLen, 255U);
++  TlsAgent* agent = reinterpret_cast<TlsAgent*>(arg);
++  // Check that agent->alpn_value_to_use_ is in protos.
++  if (protos_len < 1) {
++    return SECFailure;
++  }
++  for (size_t i = 0; i < protos_len;) {
++    size_t l = protos[i];
++    EXPECT_LT(i + l, protos_len);
++    if (i + l >= protos_len) {
++      return SECFailure;
++    }
++    std::string protos_s(reinterpret_cast<const char*>(protos + i + 1), l);
++    if (protos_s == agent->alpn_value_to_use_) {
++      size_t s_len = agent->alpn_value_to_use_.size();
++      EXPECT_LE(s_len, 255U);
++      memcpy(protoOut, &agent->alpn_value_to_use_[0], s_len);
++      *protoOutLen = s_len;
++      return SECSuccess;
++    }
++    i += l + 1;
++  }
++  return SECFailure;
++}
++
+ void TlsConnectTestBase::EnableAlpn() {
+   client_->EnableAlpn(alpn_dummy_val_, sizeof(alpn_dummy_val_));
+   server_->EnableAlpn(alpn_dummy_val_, sizeof(alpn_dummy_val_));
+ }
+ 
+-void TlsConnectTestBase::EnableAlpn(const uint8_t* val, size_t len) {
+-  client_->EnableAlpn(val, len);
+-  server_->EnableAlpn(val, len);
++void TlsConnectTestBase::EnableAlpnWithCallback(
++    const std::vector<uint8_t>& client_vals, std::string server_choice) {
++  EnsureTlsSetup();
++  server_->alpn_value_to_use_ = server_choice;
++  EXPECT_EQ(SECSuccess,
++            SSL_SetNextProtoNego(client_->ssl_fd(), client_vals.data(),
++                                 client_vals.size()));
++  SECStatus rv = SSL_SetNextProtoCallback(
++      server_->ssl_fd(), NextProtoCallbackServer, server_.get());
++  EXPECT_EQ(SECSuccess, rv);
++}
++
++void TlsConnectTestBase::EnableAlpn(const std::vector<uint8_t>& vals) {
++  client_->EnableAlpn(vals.data(), vals.size());
++  server_->EnableAlpn(vals.data(), vals.size());
+ }
+ 
+ void TlsConnectTestBase::EnsureModelSockets() {
+   // Make sure models agents are available.
+   if (!client_model_) {
+     ASSERT_EQ(server_model_, nullptr);
+     client_model_.reset(
+         new TlsAgent(TlsAgent::kClient, TlsAgent::CLIENT, variant_));
+diff --git a/security/nss/gtests/ssl_gtest/tls_connect.h b/security/nss/gtests/ssl_gtest/tls_connect.h
+--- a/security/nss/gtests/ssl_gtest/tls_connect.h
++++ b/security/nss/gtests/ssl_gtest/tls_connect.h
+@@ -105,17 +105,19 @@ class TlsConnectTestBase : public ::test
+   void EnableOnlyStaticRsaCiphers();
+   void EnableOnlyDheCiphers();
+   void EnableSomeEcdhCiphers();
+   void EnableExtendedMasterSecret();
+   void ConfigureSelfEncrypt();
+   void ConfigureSessionCache(SessionResumptionMode client,
+                              SessionResumptionMode server);
+   void EnableAlpn();
+-  void EnableAlpn(const uint8_t* val, size_t len);
++  void EnableAlpnWithCallback(const std::vector<uint8_t>& client,
++                              std::string server_choice);
++  void EnableAlpn(const std::vector<uint8_t>& vals);
+   void EnsureModelSockets();
+   void CheckAlpn(const std::string& val);
+   void EnableSrtp();
+   void CheckSrtp() const;
+   void SendReceive(size_t total = 50);
+   void SetupForZeroRtt();
+   void SetupForResume();
+   void ZeroRttSendReceive(
+diff --git a/security/nss/lib/pk11wrap/pk11merge.c b/security/nss/lib/pk11wrap/pk11merge.c
+--- a/security/nss/lib/pk11wrap/pk11merge.c
++++ b/security/nss/lib/pk11wrap/pk11merge.c
+@@ -69,43 +69,44 @@ pk11_copyAttributes(PLArenaPool *arena,
+     /* if we have missing attributes, just skip them and create the object */
+     if (crv == CKR_ATTRIBUTE_TYPE_INVALID) {
+         CK_ULONG i, j;
+         newTemplate = PORT_NewArray(CK_ATTRIBUTE, copyTemplateCount);
+         if (!newTemplate) {
+             return SECFailure;
+         }
+         /* remove the unknown attributes. If we don't have enough attributes
+-	 * PK11_CreateNewObject() will fail */
++         * PK11_CreateNewObject() will fail */
+         for (i = 0, j = 0; i < copyTemplateCount; i++) {
+             if (copyTemplate[i].ulValueLen != -1) {
+                 newTemplate[j] = copyTemplate[i];
+                 j++;
+             }
+         }
+         copyTemplate = newTemplate;
+         copyTemplateCount = j;
+         crv = PK11_GetAttributes(arena, sourceSlot, sourceID,
+                                  copyTemplate, copyTemplateCount);
+     }
+     if (crv != CKR_OK) {
+         PORT_SetError(PK11_MapError(crv));
++        PORT_Free(newTemplate);
+         return SECFailure;
+     }
+     if (targetID == CK_INVALID_HANDLE) {
+         /* we need to create the object */
+         rv = PK11_CreateNewObject(targetSlot, CK_INVALID_SESSION,
+                                   copyTemplate, copyTemplateCount, PR_TRUE, &targetID);
+     } else {
+         /* update the existing object with the new attributes */
+         rv = pk11_setAttributes(targetSlot, targetID,
+                                 copyTemplate, copyTemplateCount);
+     }
+     if (newTemplate) {
+-        free(newTemplate);
++        PORT_Free(newTemplate);
+     }
+     return rv;
+ }
+ 
+ /*
+  * look for a matching object across tokens.
+  */
+ static SECStatus
+diff --git a/security/nss/lib/ssl/SSLerrs.h b/security/nss/lib/ssl/SSLerrs.h
+--- a/security/nss/lib/ssl/SSLerrs.h
++++ b/security/nss/lib/ssl/SSLerrs.h
+@@ -369,17 +369,17 @@ ER3(SSL_ERROR_UNSAFE_NEGOTIATION, (SSL_E
+ 
+ ER3(SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD, (SSL_ERROR_BASE + 114),
+     "SSL received an unexpected uncompressed record.")
+ 
+ ER3(SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY, (SSL_ERROR_BASE + 115),
+     "SSL received a weak ephemeral Diffie-Hellman key in Server Key Exchange handshake message.")
+ 
+ ER3(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID, (SSL_ERROR_BASE + 116),
+-    "SSL received invalid NPN extension data.")
++    "SSL received invalid ALPN extension data.")
+ 
+ ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2, (SSL_ERROR_BASE + 117),
+     "SSL feature not supported for SSL 2.0 connections.")
+ 
+ ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS, (SSL_ERROR_BASE + 118),
+     "SSL feature not supported for servers.")
+ 
+ ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_CLIENTS, (SSL_ERROR_BASE + 119),
+diff --git a/security/nss/lib/ssl/ssl.h b/security/nss/lib/ssl/ssl.h
+--- a/security/nss/lib/ssl/ssl.h
++++ b/security/nss/lib/ssl/ssl.h
+@@ -153,33 +153,28 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRF
+  * application_data records. Also, we only split application_data records and
+  * not other types of records, because some implementations will not accept
+  * fragmented records of some other types (e.g. some versions of NSS do not
+  * accept fragmented alerts).
+  */
+ #define SSL_CBC_RANDOM_IV 23
+ #define SSL_ENABLE_OCSP_STAPLING 24 /* Request OCSP stapling (client) */
+ 
+-/* SSL_ENABLE_NPN controls whether the NPN extension is enabled for the initial
+- * handshake when application layer protocol negotiation is used.
+- * SSL_SetNextProtoCallback or SSL_SetNextProtoNego must be used to control the
+- * application layer protocol negotiation; otherwise, the NPN extension will
+- * not be negotiated. SSL_ENABLE_NPN is currently enabled by default but this
+- * may change in future versions.
+- */
++/* SSL_ENABLE_NPN is defunct and defaults to false.
++ * Using this option will not have any effect but won't produce an error. */
+ #define SSL_ENABLE_NPN 25
+ 
+ /* SSL_ENABLE_ALPN controls whether the ALPN extension is enabled for the
+  * initial handshake when application layer protocol negotiation is used.
+- * SSL_SetNextProtoNego (not SSL_SetNextProtoCallback) must be used to control
+- * the application layer protocol negotiation; otherwise, the ALPN extension
+- * will not be negotiated. ALPN is not negotiated for renegotiation handshakes,
+- * even though the ALPN specification defines a way to use ALPN during
+- * renegotiations. SSL_ENABLE_ALPN is currently disabled by default, but this
+- * may change in future versions.
++ * SSL_SetNextProtoNego or SSL_SetNextProtoCallback can be used to control
++ * the application layer protocol negotiation;
++ * ALPN is not negotiated for renegotiation handshakes, even though the ALPN
++ * specification defines a way to use ALPN during renegotiations.
++ * SSL_ENABLE_ALPN is currently enabled by default, but this may change in
++ * future versions.
+  */
+ #define SSL_ENABLE_ALPN 26
+ 
+ /* SSL_REUSE_SERVER_ECDHE_KEY controls whether the ECDHE server key is
+  * reused for multiple handshakes or generated each time.
+  * SSL_REUSE_SERVER_ECDHE_KEY is currently enabled by default.
+  * This socket option is for ECDHE, only. It is unrelated to DHE.
+  */
+@@ -278,56 +273,53 @@ SSL_IMPORT SECStatus SSL_EnableDefault(i
+  * options will explain if other values are permitted.
+  */
+ SSL_IMPORT SECStatus SSL_OptionSet(PRFileDesc *fd, PRInt32 option, PRIntn val);
+ SSL_IMPORT SECStatus SSL_OptionGet(PRFileDesc *fd, PRInt32 option, PRIntn *val);
+ SSL_IMPORT SECStatus SSL_OptionSetDefault(PRInt32 option, PRIntn val);
+ SSL_IMPORT SECStatus SSL_OptionGetDefault(PRInt32 option, PRIntn *val);
+ SSL_IMPORT SECStatus SSL_CertDBHandleSet(PRFileDesc *fd, CERTCertDBHandle *dbHandle);
+ 
+-/* SSLNextProtoCallback is called during the handshake for the client, when a
+- * Next Protocol Negotiation (NPN) extension has been received from the server.
+- * |protos| and |protosLen| define a buffer which contains the server's
+- * advertisement. This data is guaranteed to be well formed per the NPN spec.
++/* SSLNextProtoCallback is called during the handshake for the server, when an
++ * Application-Layer Protocol Negotiation (ALPN) extension has been received
++ * from the client. |protos| and |protosLen| define a buffer which contains the
++ * client's advertisement.
+  * |protoOut| is a buffer provided by the caller, of length 255 (the maximum
+  * allowed by the protocol). On successful return, the protocol to be announced
+  * to the server will be in |protoOut| and its length in |*protoOutLen|.
+  *
+  * The callback must return SECFailure or SECSuccess (not SECWouldBlock).
+  */
+ typedef SECStatus(PR_CALLBACK *SSLNextProtoCallback)(
+     void *arg,
+     PRFileDesc *fd,
+     const unsigned char *protos,
+     unsigned int protosLen,
+     unsigned char *protoOut,
+     unsigned int *protoOutLen,
+     unsigned int protoMaxOut);
+ 
+-/* SSL_SetNextProtoCallback sets a callback function to handle Next Protocol
+- * Negotiation. It causes a client to advertise NPN. */
++/* SSL_SetNextProtoCallback sets a callback function to handle ALPN Negotiation.
++ * It causes a client to advertise ALPN. */
+ SSL_IMPORT SECStatus SSL_SetNextProtoCallback(PRFileDesc *fd,
+                                               SSLNextProtoCallback callback,
+                                               void *arg);
+ 
+ /* SSL_SetNextProtoNego can be used as an alternative to
+- * SSL_SetNextProtoCallback. It also causes a client to advertise NPN and
+- * installs a default callback function which selects the first supported
+- * protocol in server-preference order. If no matching protocol is found it
+- * selects the first supported protocol.
++ * SSL_SetNextProtoCallback.
+  *
+- * Using this function also allows the client to transparently support ALPN.
++ * Using this function allows client and server to transparently support ALPN.
+  * The same set of protocols will be advertised via ALPN and, if the server
+  * uses ALPN to select a protocol, SSL_GetNextProto will return
+  * SSL_NEXT_PROTO_SELECTED as the state.
+  *
+- * Since NPN uses the first protocol as the fallback protocol, when sending an
+- * ALPN extension, the first protocol is moved to the end of the list. This
+- * indicates that the fallback protocol is the least preferred. The other
+- * protocols should be in preference order.
++ * Because the predecessor to ALPN, NPN, used the first protocol as the fallback
++ * protocol, when sending an ALPN extension, the first protocol is moved to the
++ * end of the list. This indicates that the fallback protocol is the least
++ * preferred. The other protocols should be in preference order.
+  *
+  * The supported protocols are specified in |data| in wire-format (8-bit
+  * length-prefixed). For example: "\010http/1.1\006spdy/2". */
+ SSL_IMPORT SECStatus SSL_SetNextProtoNego(PRFileDesc *fd,
+                                           const unsigned char *data,
+                                           unsigned int length);
+ 
+ typedef enum SSLNextProtoState {
+diff --git a/security/nss/lib/ssl/ssl3con.c b/security/nss/lib/ssl/ssl3con.c
+--- a/security/nss/lib/ssl/ssl3con.c
++++ b/security/nss/lib/ssl/ssl3con.c
+@@ -7316,20 +7316,16 @@ ssl3_SendClientSecondRound(sslSocket *ss
+                      ss->ssl3.clientCertChain != NULL &&
+                      ss->ssl3.clientPrivateKey != NULL;
+ 
+     /* We must wait for the server's certificate to be authenticated before
+      * sending the client certificate in order to disclosing the client
+      * certificate to an attacker that does not have a valid cert for the
+      * domain we are connecting to.
+      *
+-     * XXX: We should do the same for the NPN extension, but for that we
+-     * need an option to give the application the ability to leak the NPN
+-     * information to get better performance.
+-     *
+      * During the initial handshake on a connection, we never send/receive
+      * application data until we have authenticated the server's certificate;
+      * i.e. we have fully authenticated the handshake before using the cipher
+      * specs agreed upon for that handshake. During a renegotiation, we may
+      * continue sending and receiving application data during the handshake
+      * interleaved with the handshake records. If we were to send the client's
+      * second round for a renegotiation before the server's certificate was
+      * authenticated, then the application data sent/received after this point
+@@ -7393,24 +7389,16 @@ ssl3_SendClientSecondRound(sslSocket *ss
+      * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
+      * from cwSpec. This must be done before we call ssl3_CheckFalseStart
+      * because the false start callback (if any) may need the information from
+      * the functions that depend on this being set.
+      */
+     ss->enoughFirstHsDone = PR_TRUE;
+ 
+     if (!ss->firstHsDone) {
+-        /* XXX: If the server's certificate hasn't been authenticated by this
+-         * point, then we may be leaking this NPN message to an attacker.
+-         */
+-        rv = ssl3_SendNextProto(ss);
+-        if (rv != SECSuccess) {
+-            goto loser; /* err code was set. */
+-        }
+-
+         if (ss->opt.enableFalseStart) {
+             if (!ss->ssl3.hs.authCertificatePending) {
+                 /* When we fix bug 589047, we will need to know whether we are
+                  * false starting before we try to flush the client second
+                  * round to the network. With that in mind, we purposefully
+                  * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
+                  * which includes a call to ssl3_FlushHandshake, so that
+                  * no application develops a reliance on such flushing being
+diff --git a/security/nss/lib/ssl/ssl3ext.c b/security/nss/lib/ssl/ssl3ext.c
+--- a/security/nss/lib/ssl/ssl3ext.c
++++ b/security/nss/lib/ssl/ssl3ext.c
+@@ -34,17 +34,16 @@ typedef struct {
+  */
+ /* This table is used by the server, to handle client hello extensions. */
+ static const ssl3ExtensionHandler clientHelloHandlers[] = {
+     { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
+     { ssl_supported_groups_xtn, &ssl_HandleSupportedGroupsXtn },
+     { ssl_ec_point_formats_xtn, &ssl3_HandleSupportedPointFormatsXtn },
+     { ssl_session_ticket_xtn, &ssl3_ServerHandleSessionTicketXtn },
+     { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
+-    { ssl_next_proto_nego_xtn, &ssl3_ServerHandleNextProtoNegoXtn },
+     { ssl_app_layer_protocol_xtn, &ssl3_ServerHandleAppProtoXtn },
+     { ssl_use_srtp_xtn, &ssl3_ServerHandleUseSRTPXtn },
+     { ssl_cert_status_xtn, &ssl3_ServerHandleStatusRequestXtn },
+     { ssl_signature_algorithms_xtn, &ssl3_HandleSigAlgsXtn },
+     { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn },
+     { ssl_signed_cert_timestamp_xtn, &ssl3_ServerHandleSignedCertTimestampXtn },
+     { ssl_tls13_key_share_xtn, &tls13_ServerHandleKeyShareXtn },
+     { ssl_tls13_pre_shared_key_xtn, &tls13_ServerHandlePreSharedKeyXtn },
+@@ -56,17 +55,16 @@ static const ssl3ExtensionHandler client
+ 
+ /* These two tables are used by the client, to handle server hello
+  * extensions. */
+ static const ssl3ExtensionHandler serverHelloHandlersTLS[] = {
+     { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
+     /* TODO: add a handler for ssl_ec_point_formats_xtn */
+     { ssl_session_ticket_xtn, &ssl3_ClientHandleSessionTicketXtn },
+     { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
+-    { ssl_next_proto_nego_xtn, &ssl3_ClientHandleNextProtoNegoXtn },
+     { ssl_app_layer_protocol_xtn, &ssl3_ClientHandleAppProtoXtn },
+     { ssl_use_srtp_xtn, &ssl3_ClientHandleUseSRTPXtn },
+     { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn },
+     { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn },
+     { ssl_signed_cert_timestamp_xtn, &ssl3_ClientHandleSignedCertTimestampXtn },
+     { ssl_tls13_key_share_xtn, &tls13_ClientHandleKeyShareXtn },
+     { ssl_tls13_pre_shared_key_xtn, &tls13_ClientHandlePreSharedKeyXtn },
+     { ssl_tls13_early_data_xtn, &tls13_ClientHandleEarlyDataXtn },
+@@ -117,17 +115,16 @@ static const ssl3ExtensionHandler certif
+ static const sslExtensionBuilder clientHelloSendersTLS[] =
+     {
+       { ssl_server_name_xtn, &ssl3_ClientSendServerNameXtn },
+       { ssl_extended_master_secret_xtn, &ssl3_SendExtendedMasterSecretXtn },
+       { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn },
+       { ssl_supported_groups_xtn, &ssl_SendSupportedGroupsXtn },
+       { ssl_ec_point_formats_xtn, &ssl3_SendSupportedPointFormatsXtn },
+       { ssl_session_ticket_xtn, &ssl3_ClientSendSessionTicketXtn },
+-      { ssl_next_proto_nego_xtn, &ssl3_ClientSendNextProtoNegoXtn },
+       { ssl_app_layer_protocol_xtn, &ssl3_ClientSendAppProtoXtn },
+       { ssl_use_srtp_xtn, &ssl3_ClientSendUseSRTPXtn },
+       { ssl_cert_status_xtn, &ssl3_ClientSendStatusRequestXtn },
+       { ssl_signed_cert_timestamp_xtn, &ssl3_ClientSendSignedCertTimestampXtn },
+       { ssl_tls13_key_share_xtn, &tls13_ClientSendKeyShareXtn },
+       { ssl_tls13_early_data_xtn, &tls13_ClientSendEarlyDataXtn },
+       /* Some servers (e.g. WebSphere Application Server 7.0 and Tomcat) will
+        * time out or terminate the connection if the last extension in the
+@@ -178,17 +175,16 @@ static const struct {
+     { ssl_tls13_key_share_xtn, ssl_ext_native_only },
+     { ssl_tls13_pre_shared_key_xtn, ssl_ext_native_only },
+     { ssl_tls13_early_data_xtn, ssl_ext_native_only },
+     { ssl_tls13_supported_versions_xtn, ssl_ext_native_only },
+     { ssl_tls13_cookie_xtn, ssl_ext_native_only },
+     { ssl_tls13_psk_key_exchange_modes_xtn, ssl_ext_native_only },
+     { ssl_tls13_ticket_early_data_info_xtn, ssl_ext_native_only },
+     { ssl_tls13_certificate_authorities_xtn, ssl_ext_native },
+-    { ssl_next_proto_nego_xtn, ssl_ext_none },
+     { ssl_renegotiation_info_xtn, ssl_ext_native }
+ };
+ 
+ static SSLExtensionSupport
+ ssl_GetExtensionSupport(PRUint16 type)
+ {
+     unsigned int i;
+     for (i = 0; i < PR_ARRAY_SIZE(ssl_supported_extensions); ++i) {
+diff --git a/security/nss/lib/ssl/ssl3exthandle.c b/security/nss/lib/ssl/ssl3exthandle.c
+--- a/security/nss/lib/ssl/ssl3exthandle.c
++++ b/security/nss/lib/ssl/ssl3exthandle.c
+@@ -237,43 +237,21 @@ ssl_AlpnTagAllowed(const sslSocket *ss, 
+             !PORT_Memcmp(data + offset + 1, tag->data, tag->len))
+             return PR_TRUE;
+         offset += 1 + taglen;
+     }
+ 
+     return PR_FALSE;
+ }
+ 
+-/* handle an incoming Next Protocol Negotiation extension. */
+-SECStatus
+-ssl3_ServerHandleNextProtoNegoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+-                                  SECItem *data)
+-{
+-    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
+-
+-    if (ss->firstHsDone || data->len != 0) {
+-        /* Clients MUST send an empty NPN extension, if any. */
+-        PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
+-        return SECFailure;
+-    }
+-
+-    xtnData->negotiated[xtnData->numNegotiated++] = ssl_next_proto_nego_xtn;
+-
+-    /* TODO: server side NPN support would require calling
+-     * ssl3_RegisterServerHelloExtensionSender here in order to echo the
+-     * extension back to the client. */
+-
+-    return SECSuccess;
+-}
+-
+-/* ssl3_ValidateNextProtoNego checks that the given block of data is valid: none
++/* ssl3_ValidateAppProtocol checks that the given block of data is valid: none
+  * of the lengths may be 0 and the sum of the lengths must equal the length of
+  * the block. */
+ SECStatus
+-ssl3_ValidateNextProtoNego(const unsigned char *data, unsigned int length)
++ssl3_ValidateAppProtocol(const unsigned char *data, unsigned int length)
+ {
+     unsigned int offset = 0;
+ 
+     while (offset < length) {
+         unsigned int newOffset = offset + 1 + (unsigned int)data[offset];
+         /* Reject embedded nulls to protect against buggy applications that
+          * store protocol identifiers in null-terminated strings.
+          */
+@@ -281,65 +259,66 @@ ssl3_ValidateNextProtoNego(const unsigne
+             return SECFailure;
+         }
+         offset = newOffset;
+     }
+ 
+     return SECSuccess;
+ }
+ 
+-/* protocol selection handler for ALPN (server side) and NPN (client side) */
++/* Protocol selection handler for ALPN. */
+ static SECStatus
+ ssl3_SelectAppProtocol(const sslSocket *ss, TLSExtensionData *xtnData,
+                        PRUint16 extension, SECItem *data)
+ {
+     SECStatus rv;
+     unsigned char resultBuffer[255];
+     SECItem result = { siBuffer, resultBuffer, 0 };
+ 
+-    rv = ssl3_ValidateNextProtoNego(data->data, data->len);
++    rv = ssl3_ValidateAppProtocol(data->data, data->len);
+     if (rv != SECSuccess) {
+         ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+         PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
+         return rv;
+     }
+ 
+     PORT_Assert(ss->nextProtoCallback);
+-    /* For ALPN, the cipher suite isn't selected yet.  Note that extensions
++    /* The cipher suite isn't selected yet.  Note that extensions
+      * sometimes affect what cipher suite is selected, e.g., for ECC. */
+     PORT_Assert((ss->ssl3.hs.preliminaryInfo &
+                  ssl_preinfo_all & ~ssl_preinfo_cipher_suite) ==
+                 (ssl_preinfo_all & ~ssl_preinfo_cipher_suite));
++    /* The callback has to make sure that either rv != SECSuccess or that result
++     * is not set if there is no common protocol. */
+     rv = ss->nextProtoCallback(ss->nextProtoArg, ss->fd, data->data, data->len,
+                                result.data, &result.len, sizeof(resultBuffer));
+     if (rv != SECSuccess) {
+         /* Expect callback to call PORT_SetError() */
+         ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
+         return SECFailure;
+     }
+ 
+     /* If the callback wrote more than allowed to |result| it has corrupted our
+      * stack. */
+     if (result.len > sizeof(resultBuffer)) {
+         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+-        /* TODO: crash */
++        PORT_Assert(PR_FALSE);
+         return SECFailure;
+     }
+ 
+     SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE);
+ 
+-    if (extension == ssl_app_layer_protocol_xtn &&
+-        xtnData->nextProtoState != SSL_NEXT_PROTO_NEGOTIATED) {
+-        /* The callback might say OK, but then it picks a default value - one
+-         * that was not listed.  That's OK for NPN, but not ALPN. */
++    if (result.len < 1 || !result.data) {
++        /* Check that we actually got a result. */
+         ssl3_ExtSendAlert(ss, alert_fatal, no_application_protocol);
+         PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL);
+         return SECFailure;
+     }
+ 
++    xtnData->nextProtoState = SSL_NEXT_PROTO_NEGOTIATED;
+     xtnData->negotiated[xtnData->numNegotiated++] = extension;
+     return SECITEM_CopyItem(NULL, &xtnData->nextProto, &result);
+ }
+ 
+ /* handle an incoming ALPN extension at the server */
+ SECStatus
+ ssl3_ServerHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+                              SECItem *data)
+@@ -351,17 +330,17 @@ ssl3_ServerHandleAppProtoXtn(const sslSo
+      * despite it being permitted by the spec. */
+     if (ss->firstHsDone || data->len == 0) {
+         /* Clients MUST send a non-empty ALPN extension. */
+         ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+         PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
+         return SECFailure;
+     }
+ 
+-    /* Unlike NPN, ALPN has extra redundant length information so that
++    /* ALPN has extra redundant length information so that
+      * the extension is the same in both ClientHello and ServerHello. */
+     rv = ssl3_ExtConsumeHandshakeNumber(ss, &count, 2, &data->data, &data->len);
+     if (rv != SECSuccess || count != data->len) {
+         ssl3_ExtDecodeError(ss);
+         return SECFailure;
+     }
+ 
+     if (!ss->nextProtoCallback) {
+@@ -384,49 +363,16 @@ ssl3_ServerHandleAppProtoXtn(const sslSo
+             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+             return rv;
+         }
+     }
+     return SECSuccess;
+ }
+ 
+ SECStatus
+-ssl3_ClientHandleNextProtoNegoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+-                                  SECItem *data)
+-{
+-    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
+-    PORT_Assert(!ss->firstHsDone);
+-
+-    if (ssl3_ExtensionNegotiated(ss, ssl_app_layer_protocol_xtn)) {
+-        /* If the server negotiated ALPN then it has already told us what
+-         * protocol to use, so it doesn't make sense for us to try to negotiate
+-         * a different one by sending the NPN handshake message. However, if
+-         * we've negotiated NPN then we're required to send the NPN handshake
+-         * message. Thus, these two extensions cannot both be negotiated on the
+-         * same connection. */
+-        ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+-        PORT_SetError(SSL_ERROR_BAD_SERVER);
+-        return SECFailure;
+-    }
+-
+-    /* We should only get this call if we sent the extension, so
+-     * ss->nextProtoCallback needs to be non-NULL.  However, it is possible
+-     * that an application erroneously cleared the callback between the time
+-     * we sent the ClientHello and now. */
+-    if (!ss->nextProtoCallback) {
+-        PORT_Assert(0);
+-        ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
+-        PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_CALLBACK);
+-        return SECFailure;
+-    }
+-
+-    return ssl3_SelectAppProtocol(ss, xtnData, ssl_next_proto_nego_xtn, data);
+-}
+-
+-SECStatus
+ ssl3_ClientHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+                              SECItem *data)
+ {
+     SECStatus rv;
+     PRUint32 list_len;
+     SECItem protocol_name;
+ 
+     if (ssl3_ExtensionNegotiated(ss, ssl_next_proto_nego_xtn)) {
+@@ -470,69 +416,36 @@ ssl3_ClientHandleAppProtoXtn(const sslSo
+ 
+     SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE);
+     xtnData->nextProtoState = SSL_NEXT_PROTO_SELECTED;
+     xtnData->negotiated[xtnData->numNegotiated++] = ssl_app_layer_protocol_xtn;
+     return SECITEM_CopyItem(NULL, &xtnData->nextProto, &protocol_name);
+ }
+ 
+ SECStatus
+-ssl3_ClientSendNextProtoNegoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+-                                sslBuffer *buf, PRBool *added)
+-{
+-    /* Renegotiations do not send this extension. */
+-    if (!ss->opt.enableNPN || !ss->nextProtoCallback || ss->firstHsDone) {
+-        return SECSuccess;
+-    }
+-
+-    *added = PR_TRUE;
+-    return SECSuccess;
+-}
+-
+-SECStatus
+ ssl3_ClientSendAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+                            sslBuffer *buf, PRBool *added)
+ {
+     SECStatus rv;
+     const unsigned int len = ss->opt.nextProtoNego.len;
+ 
+     /* Renegotiations do not send this extension. */
+     if (!ss->opt.enableALPN || !ss->opt.nextProtoNego.data || ss->firstHsDone) {
+         return SECSuccess;
+     }
+ 
+-    /* NPN requires that the client's fallback protocol is first in the
+-     * list. However, ALPN sends protocols in preference order. So move the
+-     * first protocol to the end of the list. */
+-
+     if (len > 0) {
+         /* Each protocol string is prefixed with a single byte length. */
+-        unsigned int i;
+-
+         rv = sslBuffer_AppendNumber(buf, len, 2);
+         if (rv != SECSuccess) {
+             return SECFailure;
+         }
+-
+-        i = ss->opt.nextProtoNego.data[0] + 1;
+-        if (i <= len) {
+-            rv = sslBuffer_Append(buf, &ss->opt.nextProtoNego.data[i], len - i);
+-            if (rv != SECSuccess) {
+-                return SECFailure;
+-            }
+-            rv = sslBuffer_Append(buf, ss->opt.nextProtoNego.data, i);
+-            if (rv != SECSuccess) {
+-                return SECFailure;
+-            }
+-        } else {
+-            /* This seems to be invalid data so we'll send as-is. */
+-            rv = sslBuffer_Append(buf, ss->opt.nextProtoNego.data, len);
+-            if (rv != SECSuccess) {
+-                return SECFailure;
+-            }
++        rv = sslBuffer_Append(buf, ss->opt.nextProtoNego.data, len);
++        if (rv != SECSuccess) {
++            return SECFailure;
+         }
+     }
+ 
+     *added = PR_TRUE;
+     return SECSuccess;
+ }
+ 
+ SECStatus
+diff --git a/security/nss/lib/ssl/sslimpl.h b/security/nss/lib/ssl/sslimpl.h
+--- a/security/nss/lib/ssl/sslimpl.h
++++ b/security/nss/lib/ssl/sslimpl.h
+@@ -246,17 +246,16 @@ typedef struct sslOptionsStr {
+     unsigned int noLocks : 1;
+     unsigned int enableSessionTickets : 1;
+     unsigned int enableDeflate : 1; /* Deprecated. */
+     unsigned int enableRenegotiation : 2;
+     unsigned int requireSafeNegotiation : 1;
+     unsigned int enableFalseStart : 1;
+     unsigned int cbcRandomIV : 1;
+     unsigned int enableOCSPStapling : 1;
+-    unsigned int enableNPN : 1;
+     unsigned int enableALPN : 1;
+     unsigned int reuseServerECDHEKey : 1;
+     unsigned int enableFallbackSCSV : 1;
+     unsigned int enableServerDhe : 1;
+     unsigned int enableExtendedMS : 1;
+     unsigned int enableSignedCertTimestamps : 1;
+     unsigned int requireDHENamedGroups : 1;
+     unsigned int enable0RttData : 1;
+@@ -438,17 +437,17 @@ struct sslSessionIDStr {
+ 
+             SECItem srvName;
+ 
+             /* Signed certificate timestamps received in a TLS extension.
+             ** (used only in client).
+             */
+             SECItem signedCertTimestamps;
+ 
+-            /* The NPN/ALPN value negotiated in the original connection.
++            /* The ALPN value negotiated in the original connection.
+              * Used for TLS 1.3. */
+             SECItem alpnSelection;
+ 
+             /* This lock is lazily initialized by CacheSID when a sid is first
+              * cached. Before then, there is no need to lock anything because
+              * the sid isn't being shared by anything.
+              */
+             PRRWLock *lock;
+@@ -1542,18 +1541,18 @@ SECStatus ssl3_EncodeSessionTicket(sslSo
+ SECStatus SSLExp_SendSessionTicket(PRFileDesc *fd, const PRUint8 *token,
+                                    unsigned int tokenLen);
+ 
+ SECStatus ssl_MaybeSetSelfEncryptKeyPair(const sslKeyPair *keyPair);
+ SECStatus ssl_GetSelfEncryptKeys(sslSocket *ss, unsigned char *keyName,
+                                  PK11SymKey **encKey, PK11SymKey **macKey);
+ void ssl_ResetSelfEncryptKeys();
+ 
+-extern SECStatus ssl3_ValidateNextProtoNego(const unsigned char *data,
+-                                            unsigned int length);
++extern SECStatus ssl3_ValidateAppProtocol(const unsigned char *data,
++                                          unsigned int length);
+ 
+ /* Construct a new NSPR socket for the app to use */
+ extern PRFileDesc *ssl_NewPRSocket(sslSocket *ss, PRFileDesc *fd);
+ extern void ssl_FreePRSocket(PRFileDesc *fd);
+ 
+ /* Internal config function so SSL3 can initialize the present state of
+  * various ciphers */
+ extern unsigned int ssl3_config_match_init(sslSocket *);
+diff --git a/security/nss/lib/ssl/sslsock.c b/security/nss/lib/ssl/sslsock.c
+--- a/security/nss/lib/ssl/sslsock.c
++++ b/security/nss/lib/ssl/sslsock.c
+@@ -67,17 +67,16 @@ static sslOptions ssl_defaults = {
+     .noLocks = PR_FALSE,
+     .enableSessionTickets = PR_FALSE,
+     .enableDeflate = PR_FALSE,
+     .enableRenegotiation = SSL_RENEGOTIATE_REQUIRES_XTN,
+     .requireSafeNegotiation = PR_FALSE,
+     .enableFalseStart = PR_FALSE,
+     .cbcRandomIV = PR_TRUE,
+     .enableOCSPStapling = PR_FALSE,
+-    .enableNPN = PR_FALSE,
+     .enableALPN = PR_TRUE,
+     .reuseServerECDHEKey = PR_TRUE,
+     .enableFallbackSCSV = PR_FALSE,
+     .enableServerDhe = PR_TRUE,
+     .enableExtendedMS = PR_FALSE,
+     .enableSignedCertTimestamps = PR_FALSE,
+     .requireDHENamedGroups = PR_FALSE,
+     .enable0RttData = PR_FALSE,
+@@ -914,17 +913,17 @@ SSL_OptionGet(PRFileDesc *fd, PRInt32 wh
+             break;
+         case SSL_CBC_RANDOM_IV:
+             val = ss->opt.cbcRandomIV;
+             break;
+         case SSL_ENABLE_OCSP_STAPLING:
+             val = ss->opt.enableOCSPStapling;
+             break;
+         case SSL_ENABLE_NPN:
+-            val = ss->opt.enableNPN;
++            val = PR_FALSE;
+             break;
+         case SSL_ENABLE_ALPN:
+             val = ss->opt.enableALPN;
+             break;
+         case SSL_REUSE_SERVER_ECDHE_KEY:
+             val = ss->opt.reuseServerECDHEKey;
+             break;
+         case SSL_ENABLE_FALLBACK_SCSV:
+@@ -1040,17 +1039,17 @@ SSL_OptionGetDefault(PRInt32 which, PRIn
+             break;
+         case SSL_CBC_RANDOM_IV:
+             val = ssl_defaults.cbcRandomIV;
+             break;
+         case SSL_ENABLE_OCSP_STAPLING:
+             val = ssl_defaults.enableOCSPStapling;
+             break;
+         case SSL_ENABLE_NPN:
+-            val = ssl_defaults.enableNPN;
++            val = PR_FALSE;
+             break;
+         case SSL_ENABLE_ALPN:
+             val = ssl_defaults.enableALPN;
+             break;
+         case SSL_REUSE_SERVER_ECDHE_KEY:
+             val = ssl_defaults.reuseServerECDHEKey;
+             break;
+         case SSL_ENABLE_FALLBACK_SCSV:
+@@ -1905,20 +1904,17 @@ SSL_ImportFD(PRFileDesc *model, PRFileDe
+ 
+ PRFileDesc *
+ DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd)
+ {
+     return ssl_ImportFD(model, fd, ssl_variant_datagram);
+ }
+ 
+ /* SSL_SetNextProtoCallback is used to select an application protocol
+- * for ALPN and NPN.  For ALPN, this runs on the server; for NPN it
+- * runs on the client. */
+-/* Note: The ALPN version doesn't allow for the use of a default, setting a
+- * status of SSL_NEXT_PROTO_NO_OVERLAP is treated as a failure. */
++ * for ALPN. */
+ SECStatus
+ SSL_SetNextProtoCallback(PRFileDesc *fd, SSLNextProtoCallback callback,
+                          void *arg)
+ {
+     sslSocket *ss = ssl_FindSocket(fd);
+ 
+     if (!ss) {
+         SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoCallback", SSL_GETPID(),
+@@ -1929,94 +1925,88 @@ SSL_SetNextProtoCallback(PRFileDesc *fd,
+     ssl_GetSSL3HandshakeLock(ss);
+     ss->nextProtoCallback = callback;
+     ss->nextProtoArg = arg;
+     ssl_ReleaseSSL3HandshakeLock(ss);
+ 
+     return SECSuccess;
+ }
+ 
+-/* ssl_NextProtoNegoCallback is set as an ALPN/NPN callback when
++/* ssl_NextProtoNegoCallback is set as an ALPN callback when
+  * SSL_SetNextProtoNego is used.
+  */
+ static SECStatus
+ ssl_NextProtoNegoCallback(void *arg, PRFileDesc *fd,
+                           const unsigned char *protos, unsigned int protos_len,
+                           unsigned char *protoOut, unsigned int *protoOutLen,
+                           unsigned int protoMaxLen)
+ {
+     unsigned int i, j;
+-    const unsigned char *result;
+     sslSocket *ss = ssl_FindSocket(fd);
+ 
+     if (!ss) {
+         SSL_DBG(("%d: SSL[%d]: bad socket in ssl_NextProtoNegoCallback",
+                  SSL_GETPID(), fd));
+         return SECFailure;
+     }
+-
+-    /* For each protocol in server preference, see if we support it. */
+-    for (i = 0; i < protos_len;) {
+-        for (j = 0; j < ss->opt.nextProtoNego.len;) {
++    PORT_Assert(protoMaxLen <= 255);
++    if (protoMaxLen > 255) {
++        PORT_SetError(SEC_ERROR_OUTPUT_LEN);
++        return SECFailure;
++    }
++
++    /* For each protocol in client preference, see if we support it. */
++    for (j = 0; j < ss->opt.nextProtoNego.len;) {
++        for (i = 0; i < protos_len;) {
+             if (protos[i] == ss->opt.nextProtoNego.data[j] &&
+                 PORT_Memcmp(&protos[i + 1], &ss->opt.nextProtoNego.data[j + 1],
+                             protos[i]) == 0) {
+                 /* We found a match. */
+-                ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NEGOTIATED;
+-                result = &protos[i];
+-                goto found;
++                const unsigned char *result = &protos[i];
++                memcpy(protoOut, result + 1, result[0]);
++                *protoOutLen = result[0];
++                return SECSuccess;
+             }
+-            j += 1 + (unsigned int)ss->opt.nextProtoNego.data[j];
++            i += 1 + (unsigned int)protos[i];
+         }
+-        i += 1 + (unsigned int)protos[i];
++        j += 1 + (unsigned int)ss->opt.nextProtoNego.data[j];
+     }
+ 
+-    /* The other side supports the extension, and either doesn't have any
+-     * protocols configured, or none of its options match ours. In this case we
+-     * request our favoured protocol. */
+-    /* This will be treated as a failure for ALPN. */
+-    ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NO_OVERLAP;
+-    result = ss->opt.nextProtoNego.data;
+-
+-found:
+-    if (protoMaxLen < result[0]) {
+-        PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+-        return SECFailure;
+-    }
+-    memcpy(protoOut, result + 1, result[0]);
+-    *protoOutLen = result[0];
+     return SECSuccess;
+ }
+ 
+ SECStatus
+ SSL_SetNextProtoNego(PRFileDesc *fd, const unsigned char *data,
+                      unsigned int length)
+ {
+     sslSocket *ss;
+-    SECStatus rv;
+-    SECItem dataItem = { siBuffer, (unsigned char *)data, length };
+ 
+     ss = ssl_FindSocket(fd);
+     if (!ss) {
+         SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoNego",
+                  SSL_GETPID(), fd));
+         return SECFailure;
+     }
+ 
+-    if (ssl3_ValidateNextProtoNego(data, length) != SECSuccess)
++    if (ssl3_ValidateAppProtocol(data, length) != SECSuccess) {
+         return SECFailure;
+-
++    }
++
++    /* NPN required that the client's fallback protocol is first in the
++     * list. However, ALPN sends protocols in preference order. So move the
++     * first protocol to the end of the list. */
+     ssl_GetSSL3HandshakeLock(ss);
+     SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE);
+-    rv = SECITEM_CopyItem(NULL, &ss->opt.nextProtoNego, &dataItem);
++    SECITEM_AllocItem(NULL, &ss->opt.nextProtoNego, length);
++    size_t firstLen = data[0] + 1;
++    /* firstLen <= length is ensured by ssl3_ValidateAppProtocol. */
++    PORT_Memcpy(ss->opt.nextProtoNego.data + (length - firstLen), data, firstLen);
++    PORT_Memcpy(ss->opt.nextProtoNego.data, data + firstLen, length - firstLen);
+     ssl_ReleaseSSL3HandshakeLock(ss);
+ 
+-    if (rv != SECSuccess)
+-        return rv;
+-
+     return SSL_SetNextProtoCallback(fd, ssl_NextProtoNegoCallback, NULL);
+ }
+ 
+ SECStatus
+ SSL_GetNextProto(PRFileDesc *fd, SSLNextProtoState *state, unsigned char *buf,
+                  unsigned int *bufLen, unsigned int bufLenMax)
+ {
+     sslSocket *ss = ssl_FindSocket(fd);
+diff --git a/security/nss/lib/ssl/tls13con.c b/security/nss/lib/ssl/tls13con.c
+--- a/security/nss/lib/ssl/tls13con.c
++++ b/security/nss/lib/ssl/tls13con.c
+@@ -3579,17 +3579,17 @@ tls13_ChaCha20Poly1305(ssl3KeyMaterial *
+                       (unsigned char *)&aeadParams, sizeof(aeadParams));
+ }
+ 
+ static SECStatus
+ tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b, PRUint32 length)
+ {
+     SECStatus rv;
+     PRUint32 innerLength;
+-    SECItem oldNpn = { siBuffer, NULL, 0 };
++    SECItem oldAlpn = { siBuffer, NULL, 0 };
+ 
+     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ 
+     SSL_TRC(3, ("%d: TLS13[%d]: handle encrypted extensions",
+                 SSL_GETPID(), ss->fd));
+ 
+     rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS,
+@@ -3603,21 +3603,21 @@ tls13_HandleEncryptedExtensions(sslSocke
+         return SECFailure; /* Alert already sent. */
+     }
+     if (innerLength != length) {
+         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
+                     illegal_parameter);
+         return SECFailure;
+     }
+ 
+-    /* If we are doing 0-RTT, then we already have an NPN value. Stash
++    /* If we are doing 0-RTT, then we already have an ALPN value. Stash
+      * it for comparison. */
+     if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent &&
+         ss->xtnData.nextProtoState == SSL_NEXT_PROTO_EARLY_VALUE) {
+-        oldNpn = ss->xtnData.nextProto;
++        oldAlpn = ss->xtnData.nextProto;
+         ss->xtnData.nextProto.data = NULL;
+         ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NO_SUPPORT;
+     }
+     rv = ssl3_HandleExtensions(ss, &b, &length, ssl_hs_encrypted_extensions);
+     if (rv != SECSuccess) {
+         return SECFailure; /* Error code set below */
+     }
+ 
+@@ -3627,18 +3627,18 @@ tls13_HandleEncryptedExtensions(sslSocke
+         if (!ss->statelessResume) {
+             /* Illegal to accept 0-RTT without also accepting PSK. */
+             FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
+                         illegal_parameter);
+         }
+         ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted;
+ 
+         /* Check that the server negotiated the same ALPN (if any). */
+-        if (SECITEM_CompareItem(&oldNpn, &ss->xtnData.nextProto)) {
+-            SECITEM_FreeItem(&oldNpn, PR_FALSE);
++        if (SECITEM_CompareItem(&oldAlpn, &ss->xtnData.nextProto)) {
++            SECITEM_FreeItem(&oldAlpn, PR_FALSE);
+             FATAL_ERROR(ss, SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID,
+                         illegal_parameter);
+             return SECFailure;
+         }
+         /* Check that the server negotiated the same cipher suite. */
+         if (ss->ssl3.hs.cipher_suite != ss->ssl3.hs.zeroRttSuite) {
+             FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
+                         illegal_parameter);
+@@ -3650,17 +3650,17 @@ tls13_HandleEncryptedExtensions(sslSocke
+         ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
+         ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
+     } else {
+         PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none ||
+                     (ss->ssl3.hs.helloRetry &&
+                      ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored));
+     }
+ 
+-    SECITEM_FreeItem(&oldNpn, PR_FALSE);
++    SECITEM_FreeItem(&oldAlpn, PR_FALSE);
+     if (ss->ssl3.hs.kea_def->authKeyType == ssl_auth_psk) {
+         TLS13_SET_HS_STATE(ss, wait_finished);
+     } else {
+         TLS13_SET_HS_STATE(ss, wait_cert_request);
+     }
+ 
+     return SECSuccess;
+ }
+diff --git a/security/nss/mach b/security/nss/mach
+--- a/security/nss/mach
++++ b/security/nss/mach
+@@ -5,23 +5,42 @@
+ # file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ ##########################################################################
+ #
+ # This is a collection of helper tools to get stuff done in NSS.
+ #
+ 
+ import sys
+ import argparse
++import fnmatch
+ import subprocess
+ import os
+ import platform
++import tempfile
++
+ from hashlib import sha256
+ 
++DEVNULL = open(os.devnull, 'wb')
+ cwd = os.path.dirname(os.path.abspath(__file__))
+ 
++def run_tests(test, cycles="standard", env={}, silent=False):
++    domsuf = os.getenv('DOMSUF', "localdomain")
++    host = os.getenv('HOST', "localhost")
++    env = env.copy()
++    env.update({
++        "NSS_TESTS": test,
++        "NSS_CYCLES": cycles,
++        "DOMSUF": domsuf,
++        "HOST": host
++    })
++    os_env = os.environ
++    os_env.update(env)
++    command = cwd + "/tests/all.sh"
++    stdout = stderr = DEVNULL if silent else None
++    subprocess.check_call(command, env=os_env, stdout=stdout, stderr=stderr)
+ 
+ class cfAction(argparse.Action):
+     docker_command = ["docker"]
+     restorecon = None
+ 
+     def __call__(self, parser, args, values, option_string=None):
+         if not args.noroot:
+             self.setDockerCommand()
+@@ -122,39 +141,73 @@ class cfAction(argparse.Action):
+         def isFormatted(x):
+             return x[-2:] == '.c' or x[-3:] == '.cc' or x[-2:] == '.h'
+         return [x for x in files if isFormatted(x)]
+ 
+ 
+ class buildAction(argparse.Action):
+ 
+     def __call__(self, parser, args, values, option_string=None):
+-        cwd = os.path.dirname(os.path.abspath(__file__))
+         subprocess.check_call([cwd + "/build.sh"] + values)
+ 
+ 
+ class testAction(argparse.Action):
+ 
+-    def runTest(self, test, cycles="standard"):
+-        cwd = os.path.dirname(os.path.abspath(__file__))
+-        domsuf = os.getenv('DOMSUF', "localdomain")
+-        host = os.getenv('HOST', "localhost")
++    def __call__(self, parser, args, values, option_string=None):
++        run_tests(values)
++
++
++class covAction(argparse.Action):
++
++    def runSslGtests(self, outdir):
+         env = {
+-            "NSS_TESTS": test,
+-            "NSS_CYCLES": cycles,
+-            "DOMSUF": domsuf,
+-            "HOST": host
++            "GTESTFILTER": "*", # Prevent parallel test runs.
++            "ASAN_OPTIONS": "coverage=1:coverage_dir=" + outdir
+         }
+-        os_env = os.environ
+-        os_env.update(env)
+-        command = cwd + "/tests/all.sh"
+-        subprocess.check_call(command, env=os_env)
++
++        run_tests("ssl_gtests", env=env, silent=True)
++
++    def findSanCovFile(self, outdir):
++        for file in os.listdir(outdir):
++            if fnmatch.fnmatch(file, 'ssl_gtest.*.sancov'):
++                return os.path.join(outdir, file)
++
++        return None
+ 
+     def __call__(self, parser, args, values, option_string=None):
+-        self.runTest(values)
++        outdir = args.outdir
++        print("Output directory: " + outdir)
++
++        print("\nBuild with coverage sanitizers...\n")
++        sancov_args = "edge,no-prune,trace-pc-guard,trace-cmp"
++        subprocess.check_call([
++            os.path.join(cwd, "build.sh"), "-c", "--clang", "--asan",
++            "--sancov=" + sancov_args
++        ])
++
++        print("\nRun ssl_gtests to get a coverage report...")
++        self.runSslGtests(outdir)
++        print("Done.")
++
++        sancov_file = self.findSanCovFile(outdir)
++        if not sancov_file:
++            print("Couldn't find .sancov file.")
++            sys.exit(1)
++
++        symcov_file = os.path.join(outdir, "ssl_gtest.symcov")
++        out = open(symcov_file, 'wb')
++        subprocess.check_call([
++            "sancov",
++            "-blacklist=" + os.path.join(cwd, ".sancov-blacklist"),
++            "-symbolize", sancov_file,
++            os.path.join(cwd, "../dist/Debug/bin/ssl_gtest")
++        ], stdout=out)
++        out.close()
++
++        print("\nCoverage report: " + symcov_file)
+ 
+ 
+ class commandsAction(argparse.Action):
+     commands = []
+ 
+     def __call__(self, parser, args, values, option_string=None):
+         for c in commandsAction.commands:
+             print(c)
+@@ -194,16 +247,26 @@ def parse_arguments():
+     tests = [
+         "cipher", "lowhash", "chains", "cert", "dbtests", "tools", "fips",
+         "sdr", "crmf", "smime", "ssl", "ocsp", "merge", "pkits", "ec",
+         "gtests", "ssl_gtests", "bogo"
+     ]
+     parser_test.add_argument(
+         'test', choices=tests, help="Available tests", action=testAction)
+ 
++    parser_cov = subparsers.add_parser(
++        'coverage', help='Generate coverage report')
++    cov_modules = ["ssl_gtests"]
++    parser_cov.add_argument(
++        '--outdir', help='Output directory for coverage report data.',
++        default=tempfile.mkdtemp())
++    parser_cov.add_argument(
++        'module', choices=cov_modules, help="Available coverage modules",
++        action=covAction)
++
+     parser_commands = subparsers.add_parser(
+         'mach-commands',
+         help="list commands")
+     parser_commands.add_argument(
+         'mach-commands',
+         nargs='*',
+         action=commandsAction)
+ 

+ 111 - 0
rel-257/ian/patches/1445731-9-NSS337-61a1.patch

@@ -0,0 +1,111 @@
+# HG changeset patch
+# User Tim Taubert <ttaubert@mozilla.com>
+# Date 1524126434 -7200
+#      Thu Apr 19 10:27:14 2018 +0200
+# Node ID dd2d50a70a7e972bb4a35a8895322b5a0ef6dd92
+# Parent  db38d1dfdb81580d204568da2bf172dc2bf83073
+Bug 1445731 - land NSS 3e452651e282 UPGRADE_NSS_RELEASE, r=me
+
+diff --git a/security/nss/.sancov-blacklist b/security/nss/.sancov-blacklist
+new file mode 100644
+--- /dev/null
++++ b/security/nss/.sancov-blacklist
+@@ -0,0 +1,2 @@
++src:*/gtests/google_test/*
++src:*/gtests/ssl_gtest/*
+diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO
+--- a/security/nss/TAG-INFO
++++ b/security/nss/TAG-INFO
+@@ -1,1 +1,1 @@
+-c1a4035420c3
++3e452651e282
+diff --git a/security/nss/automation/taskcluster/scripts/gen_coverage_report.sh b/security/nss/automation/taskcluster/scripts/gen_coverage_report.sh
+new file mode 100755
+--- /dev/null
++++ b/security/nss/automation/taskcluster/scripts/gen_coverage_report.sh
+@@ -0,0 +1,12 @@
++#!/usr/bin/env bash
++
++source $(dirname "$0")/tools.sh
++
++# Clone NSPR.
++hg_clone https://hg.mozilla.org/projects/nspr ./nspr default
++
++out=/home/worker/artifacts
++mkdir -p $out
++
++# Generate coverage report.
++cd nss && ./mach coverage --outdir=$out ssl_gtests
+diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep
+--- a/security/nss/coreconf/coreconf.dep
++++ b/security/nss/coreconf/coreconf.dep
+@@ -5,9 +5,8 @@
+ 
+ /*
+  * A dummy header file that is a dependency for all the object files.
+  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
+  * depend builds.  See comments in rules.mk.
+  */
+ 
+ #error "Do not include this header file."
+-
+diff --git a/security/nss/lib/softoken/sdb.c b/security/nss/lib/softoken/sdb.c
+--- a/security/nss/lib/softoken/sdb.c
++++ b/security/nss/lib/softoken/sdb.c
+@@ -639,23 +639,28 @@ sdb_closeDBLocal(SDBPrivate *sdb_p, sqli
+ 
+ /*
+  * wrapper to sqlite3_open which also sets the busy_timeout
+  */
+ static int
+ sdb_openDB(const char *name, sqlite3 **sqlDB, int flags)
+ {
+     int sqlerr;
+-    /*
+-     * in sqlite3 3.5.0, there is a new open call that allows us
+-     * to specify read only. Most new OS's are still on 3.3.x (including
+-     * NSS's internal version and the version shipped with Firefox).
+-     */
++    int openFlags;
++
+     *sqlDB = NULL;
+-    sqlerr = sqlite3_open(name, sqlDB);
++
++    if (flags & SDB_RDONLY) {
++        openFlags = SQLITE_OPEN_READONLY;
++    } else {
++        openFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
++    }
++
++    /* Requires SQLite 3.5.0 or newer. */
++    sqlerr = sqlite3_open_v2(name, sqlDB, openFlags, NULL);
+     if (sqlerr != SQLITE_OK) {
+         return sqlerr;
+     }
+ 
+     sqlerr = sqlite3_busy_timeout(*sqlDB, SDB_SQLITE_BUSY_TIMEOUT);
+     if (sqlerr != SQLITE_OK) {
+         sqlite3_close(*sqlDB);
+         *sqlDB = NULL;
+diff --git a/security/nss/lib/ssl/ssl3prot.h b/security/nss/lib/ssl/ssl3prot.h
+--- a/security/nss/lib/ssl/ssl3prot.h
++++ b/security/nss/lib/ssl/ssl3prot.h
+@@ -11,17 +11,17 @@
+ #define __ssl3proto_h_
+ 
+ typedef PRUint16 SSL3ProtocolVersion;
+ /* version numbers are defined in sslproto.h */
+ 
+ /* The TLS 1.3 draft version. Used to avoid negotiating
+  * between incompatible pre-standard TLS 1.3 drafts.
+  * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */
+-#define TLS_1_3_DRAFT_VERSION 26
++#define TLS_1_3_DRAFT_VERSION 28
+ 
+ typedef PRUint16 ssl3CipherSuite;
+ /* The cipher suites are defined in sslproto.h */
+ 
+ #define MAX_CERT_TYPES 10
+ #define MAX_MAC_LENGTH 64
+ #define MAX_PADDING_LENGTH 64
+ #define MAX_KEY_LENGTH 64

+ 90 - 0
rel-257/ian/patches/1445766-61a1.patch

@@ -0,0 +1,90 @@
+# HG changeset patch
+# User Ryan VanderMeulen <ryanvm@gmail.com>
+# Date 1521061409 14400
+# Node ID bfe4b0a2e835de50b680b787a32a4316f3cd9e22
+# Parent  0d6dd2674522e12d0cdef7f58a514ddf6589002d
+Bug 1445766 - Fix some non-unified build bustage in gfx/layers. r=lsalzman
+
+diff --git a/gfx/layers/TextureDIB.cpp b/gfx/layers/TextureDIB.cpp
+--- a/gfx/layers/TextureDIB.cpp
++++ b/gfx/layers/TextureDIB.cpp
+@@ -2,18 +2,19 @@
+ /* vim: set ts=8 sts=2 et sw=2 tw=80: */
+ /* This Source Code Form is subject to the terms of the Mozilla Public
+  * 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/. */
+ 
+ #include "TextureDIB.h"
+ #include "gfx2DGlue.h"
+ #include "mozilla/gfx/DataSurfaceHelpers.h"  // For BufferSizeFromDimensions
++#include "mozilla/ipc/ProtocolUtils.h"
+ #include "mozilla/layers/ISurfaceAllocator.h"
+-#include "mozilla/ipc/ProtocolUtils.h"
++#include "mozilla/layers/TextureForwarder.h" // For LayersIPCChannel
+ 
+ namespace mozilla {
+ 
+ using namespace gfx;
+ 
+ namespace layers {
+ 
+ /**
+diff --git a/gfx/layers/client/SingleTiledContentClient.cpp b/gfx/layers/client/SingleTiledContentClient.cpp
+--- a/gfx/layers/client/SingleTiledContentClient.cpp
++++ b/gfx/layers/client/SingleTiledContentClient.cpp
+@@ -268,18 +268,20 @@ void ClientSingleTiledLayerBuffer::Paint
+ 
+   if (dtOnWhite) {
+     dt = gfx::Factory::CreateDualDrawTarget(dt, dtOnWhite);
+     dtOnWhite = nullptr;
+   }
+ 
+   if (asyncPaint) {
+     // Create a capture draw target
+-    RefPtr<DrawTargetCapture> captureDT = Factory::CreateCaptureDrawTarget(
+-        dt->GetBackendType(), dt->GetSize(), dt->GetFormat());
++    RefPtr<gfx::DrawTargetCapture> captureDT =
++      gfx::Factory::CreateCaptureDrawTarget(dt->GetBackendType(),
++                                            dt->GetSize(),
++                                            dt->GetFormat());
+ 
+     RefPtr<gfxContext> ctx = gfxContext::CreateOrNull(captureDT);
+     if (!ctx) {
+       gfxDevCrash(gfx::LogReason::InvalidContext)
+           << "SingleTiledContextClient context problem " << gfx::hexa(dt);
+       return;
+     }
+     ctx->SetMatrix(
+diff --git a/gfx/layers/ipc/RefCountedShmem.cpp b/gfx/layers/ipc/RefCountedShmem.cpp
+--- a/gfx/layers/ipc/RefCountedShmem.cpp
++++ b/gfx/layers/ipc/RefCountedShmem.cpp
+@@ -68,26 +68,27 @@ int32_t RefCountedShm::Release(const Ref
+   auto* counter = aShm.buffer().get<Atomic<int32_t>>();
+   if (counter) {
+     return --(*counter);
+   }
+ 
+   return 0;
+ }
+ 
+-bool RefCountedShm::Alloc(IProtocol* aAllocator, size_t aSize,
++bool RefCountedShm::Alloc(mozilla::ipc::IProtocol* aAllocator, size_t aSize,
+                           RefCountedShmem& aShm) {
+   MOZ_ASSERT(!IsValid(aShm));
+   auto shmType = ipc::SharedMemory::SharedMemoryType::TYPE_BASIC;
+   auto size = aSize + SHM_REFCOUNT_HEADER_SIZE;
+   if (!aAllocator->AllocUnsafeShmem(size, shmType, &aShm.buffer())) {
+     return false;
+   }
+   return true;
+ }
+ 
+-void RefCountedShm::Dealloc(IProtocol* aAllocator, RefCountedShmem& aShm) {
++void RefCountedShm::Dealloc(mozilla::ipc::IProtocol* aAllocator,
++                            RefCountedShmem& aShm) {
+   aAllocator->DeallocShmem(aShm.buffer());
+   aShm.buffer() = ipc::Shmem();
+ }
+ 
+ }  // namespace layers
+ }  // namespace mozilla

+ 36 - 0
rel-257/ian/patches/1445969-61a1.patch

@@ -0,0 +1,36 @@
+# HG changeset patch
+# User Yan Or <yor@mozilla.com>
+# Date 1521581154 25200
+# Node ID 317c00f07c399fbe97abcea33029bc416e064347
+# Parent  6f4319fc1bd24a2b2be82a7375176397e1bbdfb6
+Bug 1445969 - removed obsolete code related to b2g r=sylvestre
+
+MozReview-Commit-ID: Hs3lI1nSKWi
+
+diff --git a/js/src/make-source-package.sh b/js/src/make-source-package.sh
+--- a/js/src/make-source-package.sh
++++ b/js/src/make-source-package.sh
+@@ -216,21 +216,17 @@ This release is based on a revision of M
+ The changes in the patches/ directory were applied.
+ 
+ MDN hosts the latest SpiderMonkey ${MOZJS_MAJOR_VERSION} release notes:
+   https://developer.mozilla.org/en-US/docs/SpiderMonkey/${MOZJS_MAJOR_VERSION}
+ README_EOF
+     fi
+ 
+     # copy LICENSE
+-    if [ -e ${TOPSRCDIR}/b2g/LICENSE ]; then
+-        cp ${TOPSRCDIR}/b2g/LICENSE ${tgtpath}/
+-    else
+-        cp ${TOPSRCDIR}/LICENSE ${tgtpath}/
+-    fi
++    cp ${TOPSRCDIR}/LICENSE ${tgtpath}/
+ 
+     # copy patches dir, if it currently exists in STAGING
+     if [ -d ${STAGING}/patches ]; then
+         cp -pPR ${STAGING}/patches ${tgtpath}
+     elif [ -d ${TOPSRCDIR}/patches ]; then
+         cp -pPR ${TOPSRCDIR}/patches ${tgtpath}
+     fi
+ 
+

+ 104 - 0
rel-257/ian/patches/1446809-1-61a1.patch

@@ -0,0 +1,104 @@
+# HG changeset patch
+# User Sylvestre Ledru <sledru@mozilla.com>
+# Date 1521397625 -3600
+# Node ID 3dedc3e974318acc9b72fc89d8ce77217c467f21
+# Parent  24a247584c0648db30cb725558d491fd12aef4cc
+Bug 1446809 - Remove some b2g leftover in desktop/ r=florian
+
+MozReview-Commit-ID: FPwAZmpoiUV
+
+diff --git a/browser/components/BrowserComponents.manifest b/browser/components/BrowserComponents.manifest
+--- a/browser/components/BrowserComponents.manifest
++++ b/browser/components/BrowserComponents.manifest
+@@ -24,21 +24,19 @@ category command-line-handler x-default 
+ category command-line-validator b-browser @mozilla.org/browser/clh;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
+ 
+ # nsBrowserGlue.js
+ 
+ # This component must restrict its registration for the app-startup category
+ # to the specific list of apps that use it so it doesn't get loaded in xpcshell.
+ # Thus we restrict it to these apps:
+ #
+-#   b2g:            {3c2e2abc-06d4-11e1-ac3b-374f68613e61}
+ #   browser:        {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
+ #   mobile/android: {aa3c5121-dab2-40e2-81ca-7ea25febc110}
+ #   mobile/xul:     {a23983c0-fd0e-11dc-95ff-0800200c9a66}
+-#   graphene:       {d1bfe7d9-c01e-4237-998b-7b5f960a4314}
+ 
+ component {eab9012e-5f74-4cbc-b2b5-a590235513cc} nsBrowserGlue.js
+ contract @mozilla.org/browser/browserglue;1 {eab9012e-5f74-4cbc-b2b5-a590235513cc}
+-category app-startup nsBrowserGlue service,@mozilla.org/browser/browserglue;1 application={3c2e2abc-06d4-11e1-ac3b-374f68613e61} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66} application={d1bfe7d9-c01e-4237-998b-7b5f960a4314}
++category app-startup nsBrowserGlue service,@mozilla.org/browser/browserglue;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66}
+ component {d8903bf6-68d5-4e97-bcd1-e4d3012f721a} nsBrowserGlue.js
+ #ifndef MOZ_MULET
+ contract @mozilla.org/content-permission/prompt;1 {d8903bf6-68d5-4e97-bcd1-e4d3012f721a}
+ #endif
+diff --git a/browser/components/feeds/BrowserFeeds.manifest b/browser/components/feeds/BrowserFeeds.manifest
+--- a/browser/components/feeds/BrowserFeeds.manifest
++++ b/browser/components/feeds/BrowserFeeds.manifest
+@@ -1,21 +1,19 @@
+ # This component must restrict its registration for the app-startup category
+ # to the specific list of apps that use it so it doesn't get loaded in xpcshell.
+ # Thus we restrict it to these apps:
+ #
+-#   b2g:            {3c2e2abc-06d4-11e1-ac3b-374f68613e61}
+ #   browser:        {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
+ #   mobile/android: {aa3c5121-dab2-40e2-81ca-7ea25febc110}
+ #   mobile/xul:     {a23983c0-fd0e-11dc-95ff-0800200c9a66}
+-#   graphene:       {d1bfe7d9-c01e-4237-998b-7b5f960a4314}
+ 
+ component {229fa115-9412-4d32-baf3-2fc407f76fb1} FeedConverter.js
+ contract @mozilla.org/streamconv;1?from=application/vnd.mozilla.maybe.feed&to=*/* {229fa115-9412-4d32-baf3-2fc407f76fb1}
+ contract @mozilla.org/streamconv;1?from=application/vnd.mozilla.maybe.video.feed&to=*/* {229fa115-9412-4d32-baf3-2fc407f76fb1}
+ contract @mozilla.org/streamconv;1?from=application/vnd.mozilla.maybe.audio.feed&to=*/* {229fa115-9412-4d32-baf3-2fc407f76fb1}
+ component {2376201c-bbc6-472f-9b62-7548040a61c6} FeedConverter.js
+ contract @mozilla.org/browser/feeds/result-service;1 {2376201c-bbc6-472f-9b62-7548040a61c6}
+ component {49bb6593-3aff-4eb3-a068-2712c28bd58e} FeedWriter.js
+ contract @mozilla.org/browser/feeds/result-writer;1 {49bb6593-3aff-4eb3-a068-2712c28bd58e}
+ component {792a7e82-06a0-437c-af63-b2d12e808acc} WebContentConverter.js
+ contract @mozilla.org/embeddor.implemented/web-content-handler-registrar;1 {792a7e82-06a0-437c-af63-b2d12e808acc}
+-category app-startup WebContentConverter service,@mozilla.org/embeddor.implemented/web-content-handler-registrar;1 application={3c2e2abc-06d4-11e1-ac3b-374f68613e61} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66} application={d1bfe7d9-c01e-4237-998b-7b5f960a4314}
++category app-startup WebContentConverter service,@mozilla.org/embeddor.implemented/web-content-handler-registrar;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66}
+diff --git a/browser/components/sessionstore/nsSessionStore.manifest b/browser/components/sessionstore/nsSessionStore.manifest
+--- a/browser/components/sessionstore/nsSessionStore.manifest
++++ b/browser/components/sessionstore/nsSessionStore.manifest
+@@ -1,15 +1,13 @@
+ # This component must restrict its registration for the app-startup category
+ # to the specific list of apps that use it so it doesn't get loaded in xpcshell.
+ # Thus we restrict it to these apps:
+ #
+-#   b2g:            {3c2e2abc-06d4-11e1-ac3b-374f68613e61}
+ #   browser:        {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
+ #   mobile/android: {aa3c5121-dab2-40e2-81ca-7ea25febc110}
+ #   mobile/xul:     {a23983c0-fd0e-11dc-95ff-0800200c9a66}
+-#   graphene:       {d1bfe7d9-c01e-4237-998b-7b5f960a4314}
+ 
+ component {5280606b-2510-4fe0-97ef-9b5a22eafe6b} nsSessionStore.js
+ contract @mozilla.org/browser/sessionstore;1 {5280606b-2510-4fe0-97ef-9b5a22eafe6b}
+ component {ec7a6c20-e081-11da-8ad9-0800200c9a66} nsSessionStartup.js
+ contract @mozilla.org/browser/sessionstartup;1 {ec7a6c20-e081-11da-8ad9-0800200c9a66}
+-category app-startup nsSessionStartup service,@mozilla.org/browser/sessionstartup;1 application={3c2e2abc-06d4-11e1-ac3b-374f68613e61} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66} application={d1bfe7d9-c01e-4237-998b-7b5f960a4314}
++category app-startup nsSessionStartup service,@mozilla.org/browser/sessionstartup;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66}
+diff --git a/browser/experiments/docs/manifest.rst b/browser/experiments/docs/manifest.rst
+--- a/browser/experiments/docs/manifest.rst
++++ b/browser/experiments/docs/manifest.rst
+@@ -96,17 +96,17 @@ maxActiveSeconds
+    initial activation.
+ 
+    This value only involves wall time, not browser activity or session time.
+ 
+ appName
+    Array of application names this experiment should run on.
+ 
+    An application name comes from ``nsIXULAppInfo.name``. It is a value
+-   like ``Firefox``, ``Fennec``, or `B2G`.
++   like ``Firefox`` or ``Fennec``.
+ 
+    The client should compare its application name against the members of
+    this array. If a match is found, the experiment is applicable.
+ 
+ minVersion
+    (optional) String version number of the minimum application version this
+    experiment should run on.
+ 
+

+ 128 - 0
rel-257/ian/patches/1446809-2-61a1.patch

@@ -0,0 +1,128 @@
+# HG changeset patch
+# User Sylvestre Ledru <sledru@mozilla.com>
+# Date 1521539183 -3600
+# Node ID b909b93e90f9bdde2cefe9c09f55b0c8b68722ef
+# Parent  3dedc3e974318acc9b72fc89d8ce77217c467f21
+Bug 1446809 - Remove some b2g leftover in the build r=glandium
+
+MozReview-Commit-ID: EAXd3JmiL2Z
+
+diff --git a/build/docs/mozinfo.rst b/build/docs/mozinfo.rst
+--- a/build/docs/mozinfo.rst
++++ b/build/docs/mozinfo.rst
+@@ -58,17 +58,17 @@ bits
+    this key defined.
+ 
+    Optional.
+ 
+ buildapp
+    The path to the XUL application being built.
+ 
+    For desktop Firefox, this is ``browser``. For Fennec, it's
+-   ``mobile/android``. For B2G, it's ``b2g``.
++   ``mobile/android``.
+ 
+ crashreporter
+    Whether the crash reporter is enabled for this build.
+ 
+    Values are ``true`` and ``false``.
+ 
+    Always defined.
+ 
+@@ -109,17 +109,17 @@ nightly_build
+    Whether this is a nightly build.
+ 
+    Values are ``true`` and ``false``.
+ 
+    Always defined.
+ 
+ os
+    The operating system the build is produced for. Values for tier-1
+-   supported platforms are ``linux``, ``win``, ``mac``, ``b2g``, and
++   supported platforms are ``linux``, ``win``, ``mac``, and
+    ``android``. For other platforms, the value is the lowercase version
+    of the ``OS_TARGET`` variable from ``config.status``.
+ 
+    Always defined.
+ 
+ processor
+    Information about the processor architecture this build targets.
+ 
+diff --git a/build/unix/mozconfig.linux b/build/unix/mozconfig.linux
+--- a/build/unix/mozconfig.linux
++++ b/build/unix/mozconfig.linux
+@@ -2,26 +2,17 @@ if [ "x$IS_NIGHTLY" = "xyes" ]; then
+   # Some nightlies (eg: Mulet) don't want these set.
+   MOZ_AUTOMATION_UPDATE_PACKAGING=${MOZ_AUTOMATION_UPDATE_PACKAGING-1}
+ fi
+ 
+ . "$topsrcdir/build/mozconfig.common"
+ 
+ TOOLTOOL_DIR=${TOOLTOOL_DIR:-$topsrcdir}
+ 
+-# some b2g desktop builds still happen on i686 machines, and the tooltool
+-# toolchain is x86_64 only.
+-# We also deal with valgrind builds here, they don't use tooltool manifests at
+-# all yet.
+-if [ -z "$no_tooltool" ]
+-then
+-  CC="$TOOLTOOL_DIR/gcc/bin/gcc"
+-  CXX="$TOOLTOOL_DIR/gcc/bin/g++"
++# We deal with valgrind builds here
++CC="$TOOLTOOL_DIR/gcc/bin/gcc"
++CXX="$TOOLTOOL_DIR/gcc/bin/g++"
+ 
+-  # We want to make sure we use binutils and other binaries in the tooltool
+-  # package.
+-  mk_add_options "export PATH=$TOOLTOOL_DIR/gcc/bin:$PATH"
+-else
+-  CC="/tools/gcc-4.7.3-0moz1/bin/gcc"
+-  CXX="/tools/gcc-4.7.3-0moz1/bin/g++"
+-fi
++# We want to make sure we use binutils and other binaries in the tooltool
++# package.
++mk_add_options "export PATH=$TOOLTOOL_DIR/gcc/bin:$PATH"
+ 
+ . "$topsrcdir/build/unix/mozconfig.stdcxx"
+diff --git a/toolkit/nss.configure b/toolkit/nss.configure
+--- a/toolkit/nss.configure
++++ b/toolkit/nss.configure
+@@ -4,13 +4,13 @@
+ # 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/.
+ 
+ 
+ # DBM support in NSS
+ # ==============================================================
+ @depends(build_project, '--help')
+ def dbm_default(build_project, _):
+-    return build_project not in ('mobile/android', 'b2g', 'b2g/graphene')
++    return build_project != 'mobile/android'
+ 
+ option('--enable-dbm', default=dbm_default, help='Enable building DBM')
+ 
+ set_config('NSS_DISABLE_DBM', depends('--enable-dbm')(lambda x: not x))
+diff --git a/toolkit/toolkit.mozbuild b/toolkit/toolkit.mozbuild
+--- a/toolkit/toolkit.mozbuild
++++ b/toolkit/toolkit.mozbuild
+@@ -36,18 +36,17 @@ if CONFIG['ENABLE_TESTS']:
+ DIRS += [
+     '/toolkit/library/rust',
+ ]
+ 
+ if CONFIG['MOZ_SANDBOX']:
+     DIRS += ['/security/sandbox']
+ 
+ DIRS += [
+-    # Depends on NSS and NSPR, and must be built after sandbox or else B2G emulator
+-    # builds fail.
++    # Depends on NSS and NSPR
+     '/security/certverifier',
+     # Depends on certverifier
+     '/security/apps',
+ ]
+ 
+ # the signing related bits of libmar depend on nss
+ if CONFIG['MOZ_UPDATER']:
+     DIRS += ['/modules/libmar']
+

+ 64 - 0
rel-257/ian/patches/1446809-3-61a1.patch

@@ -0,0 +1,64 @@
+# HG changeset patch
+# User Sylvestre Ledru <sledru@mozilla.com>
+# Date 1521577226 -3600
+# Node ID db5c66fc744811eb8984b8b98e8d990145374755
+# Parent  b909b93e90f9bdde2cefe9c09f55b0c8b68722ef
+Bug 1446809 - Remove some b2g leftover in the testing/mozbase r=jgraham
+
+MozReview-Commit-ID: 6PGuSXVjMB9
+
+diff --git a/testing/mozbase/moztest/tests/test.py b/testing/mozbase/moztest/tests/test.py
+--- a/testing/mozbase/moztest/tests/test.py
++++ b/testing/mozbase/moztest/tests/test.py
+@@ -36,25 +36,24 @@ class Result(unittest.TestCase):
+ 
+ 
+ class Collection(unittest.TestCase):
+ 
+     def setUp(self):
+         c1 = TestContext('host1')
+         c2 = TestContext('host2')
+         c3 = TestContext('host2')
+-        c3.os = 'B2G'
+         c4 = TestContext('host1')
+ 
+         t1 = TestResult('t1', context=c1)
+         t2 = TestResult('t2', context=c2)
+         t3 = TestResult('t3', context=c3)
+         t4 = TestResult('t4', context=c4)
+ 
+         self.collection = TestResultCollection('tests')
+         self.collection.extend([t1, t2, t3, t4])
+ 
+     def test_unique_contexts(self):
+-        self.assertEqual(len(self.collection.contexts), 3)
++        self.assertEqual(len(self.collection.contexts), 2)
+ 
+ 
+ if __name__ == '__main__':
+     mozunit.main()
+diff --git a/testing/mozbase/mozversion/tests/manifest.ini b/testing/mozbase/mozversion/tests/manifest.ini
+--- a/testing/mozbase/mozversion/tests/manifest.ini
++++ b/testing/mozbase/mozversion/tests/manifest.ini
+@@ -1,6 +1,5 @@
+ [DEFAULT]
+ subsuite = mozbase, os == "linux"
+ [test_binary.py]
+ [test_sources.py]
+-[test_b2g.py]
+ [test_apk.py]
+diff --git a/testing/mozbase/packages.txt b/testing/mozbase/packages.txt
+--- a/testing/mozbase/packages.txt
++++ b/testing/mozbase/packages.txt
+@@ -1,10 +1,9 @@
+ manifestparser.pth:testing/mozbase/manifestparser
+-mozb2g.pth:testing/mozbase/mozb2g
+ mozcrash.pth:testing/mozbase/mozcrash
+ mozdebug.pth:testing/mozbase/mozdebug
+ mozdevice.pth:testing/mozbase/mozdevice
+ mozfile.pth:testing/mozbase/mozfile
+ mozhttpd.pth:testing/mozbase/mozhttpd
+ mozinfo.pth:testing/mozbase/mozinfo
+ mozinstall.pth:testing/mozbase/mozinstall
+ mozleak.pth:testing/mozbase/mozleak
+

+ 97 - 0
rel-257/ian/patches/1446809-4-61a1.patch

@@ -0,0 +1,97 @@
+# HG changeset patch
+# User Sylvestre Ledru <sledru@mozilla.com>
+# Date 1521397805 -3600
+# Node ID 2c827ac938dcbdd7224bb9bc0b2345eb82393d36
+# Parent  6419a201e2d9410ce725bbea4b739fa5816a8102
+Bug 1446809 - Remove some b2g leftover in widget/NativeKeyToDOMKeyName.h r=froydnj
+
+MozReview-Commit-ID: 7nRuHThygp1
+
+diff --git a/widget/NativeKeyToDOMKeyName.h b/widget/NativeKeyToDOMKeyName.h
+--- a/widget/NativeKeyToDOMKeyName.h
++++ b/widget/NativeKeyToDOMKeyName.h
+@@ -20,22 +20,18 @@
+ #define KEY_MAP_WIN_JPN(aCPPKeyName, aNativeKey)
+ #define KEY_MAP_WIN_KOR(aCPPKeyName, aNativeKey)
+ #define KEY_MAP_WIN_OTH(aCPPKeyName, aNativeKey)
+ #define KEY_MAP_WIN_CMD(aCPPKeyName, aAppCommand)
+ // Mac OS X
+ #define KEY_MAP_COCOA(aCPPKeyName, aNativeKey)
+ // GTK
+ #define KEY_MAP_GTK(aCPPKeyName, aNativeKey)
+-// Android and B2G
++// Only for Android
+ #define KEY_MAP_ANDROID(aCPPKeyName, aNativeKey)
+-// Only for Android
+-#define KEY_MAP_ANDROID_EXCEPT_B2G(aCPPKeyName, aNativeKey)
+-// Only for B2G
+-#define KEY_MAP_B2G(aCPPKeyName, aNativeKey)
+ 
+ #if defined(XP_WIN)
+ #if defined(NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX)
+ // KEY_MAP_WIN() defines the mapping not depending on keyboard layout.
+ #undef KEY_MAP_WIN
+ #define KEY_MAP_WIN(aCPPKeyName, aNativeKey) \
+   NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, KEY_NAME_INDEX_##aCPPKeyName)
+ #elif defined(NS_JAPANESE_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX)
+@@ -74,19 +70,16 @@
+ #elif defined(MOZ_WIDGET_GTK)
+ #undef KEY_MAP_GTK
+ #define KEY_MAP_GTK(aCPPKeyName, aNativeKey) \
+   NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, KEY_NAME_INDEX_##aCPPKeyName)
+ #elif defined(ANDROID)
+ #undef KEY_MAP_ANDROID
+ #define KEY_MAP_ANDROID(aCPPKeyName, aNativeKey) \
+   NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, KEY_NAME_INDEX_##aCPPKeyName)
+-#undef KEY_MAP_ANDROID_EXCEPT_B2G
+-#define KEY_MAP_ANDROID_EXCEPT_B2G(aCPPKeyName, aNativeKey) \
+-  NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, KEY_NAME_INDEX_##aCPPKeyName)
+ #endif
+ 
+ /******************************************************************************
+  * Modifier Keys
+  ******************************************************************************/
+ // Alt
+ KEY_MAP_WIN(Alt, VK_MENU)
+ KEY_MAP_WIN(Alt, VK_LMENU)
+@@ -1047,27 +1040,26 @@ KEY_MAP_ANDROID(AppSwitch, AKEYCODE_APP_
+ 
+ // Call
+ KEY_MAP_ANDROID(Call, AKEYCODE_CALL)
+ 
+ // Camera
+ KEY_MAP_ANDROID(Camera, AKEYCODE_CAMERA)
+ 
+ // CameraFocus
+-KEY_MAP_ANDROID_EXCEPT_B2G(CameraFocus, AKEYCODE_FOCUS)
++KEY_MAP_ANDROID(CameraFocus, AKEYCODE_FOCUS)
+ 
+ // EndCall
+ KEY_MAP_ANDROID(EndCall, AKEYCODE_ENDCALL)
+ 
+ // GoBack
+ KEY_MAP_ANDROID(GoBack, AKEYCODE_BACK)
+ 
+ // GoHome
+-KEY_MAP_ANDROID_EXCEPT_B2G(GoHome, AKEYCODE_HOME)
+-KEY_MAP_B2G(HomeScreen, AKEYCODE_HOME)
++KEY_MAP_ANDROID(GoHome,     AKEYCODE_HOME)
+ 
+ // HeadsetHook
+ KEY_MAP_ANDROID(HeadsetHook, AKEYCODE_HEADSETHOOK)
+ 
+ // Notification
+ KEY_MAP_ANDROID(Notification, AKEYCODE_NOTIFICATION)
+ 
+ // MannerMode
+@@ -1280,10 +1272,8 @@ KEY_MAP_ANDROID(SoftRight, AKEYCODE_SOFT
+ #undef KEY_MAP_WIN
+ #undef KEY_MAP_WIN_JPN
+ #undef KEY_MAP_WIN_KOR
+ #undef KEY_MAP_WIN_OTH
+ #undef KEY_MAP_WIN_CMD
+ #undef KEY_MAP_COCOA
+ #undef KEY_MAP_GTK
+ #undef KEY_MAP_ANDROID
+-#undef KEY_MAP_ANDROID_EXCEPT_B2G
+-#undef KEY_MAP_B2G

+ 44 - 0
rel-257/ian/patches/1446809-5-61a1.patch

@@ -0,0 +1,44 @@
+# HG changeset patch
+# User Sylvestre Ledru <sledru@mozilla.com>
+# Date 1521397856 -3600
+# Node ID b2647d006cf4fe5d7147ef1eda48c93d54a7af5a
+# Parent  2c827ac938dcbdd7224bb9bc0b2345eb82393d36
+Bug 1446809 - Remove some b2g leftover in the devtools doc r=jdescottes
+
+MozReview-Commit-ID: L6CYiizDSwF
+
+diff --git a/devtools/docs/backend/actor-registration.md b/devtools/docs/backend/actor-registration.md
+--- a/devtools/docs/backend/actor-registration.md
++++ b/devtools/docs/backend/actor-registration.md
+@@ -1,17 +1,17 @@
+ # How to register an actor
+ 
+ ## Tab actors vs. global actors
+ 
+ Tab actors are the most common types of actors. That's the type of actors you will most probably be adding.
+ 
+-Tab actors target a document, this could be a tab in Firefox, an app on B2G or a remote document in Firefox for Android/Safari/Chrome for Android (via Valence).
++Tab actors target a document, this could be a tab in Firefox or a remote document in Firefox for Android/Safari/Chrome for Android (via Valence).
+ 
+-Global actors however are for the rest, for things not related to any particular document but instead for things global to the whole Firefox/B2G/Chrome/Safari intance the toolbox is connected to (e.g. the preference actor).
++Global actors however are for the rest, for things not related to any particular document but instead for things global to the whole Firefox/Chrome/Safari intance the toolbox is connected to (e.g. the preference actor).
+ 
+ ## The DebuggerServer.registerModule function
+ 
+ To register a tab actor:
+ 
+ ```
+ DebuggerServer.registerModule("devtools/server/actors/webconsole", {
+   prefix: "console",
+@@ -33,9 +33,9 @@ DebuggerServer.registerModule("devtools/
+ If you are adding a new built-in devtools actor, you should be registering it using `DebuggerServer.registerModule` in `_addBrowserActors` or `addTabActors` in `/devtools/server/main.js`.
+ 
+ If you are adding a new actor from an add-on, you should call `DebuggerServer.registerModule` directly from your add-on code.
+ 
+ ## A note about lazy registration
+ 
+ The `DebuggerServer` loads and creates all of the actors lazily to keep the initial memory usage down (which is extremely important on lower end devices).
+ 
+-It becomes especially important when debugging apps on b2g or pages with e10s when there are more than one process, because that's when we need to spawn a `DebuggerServer` per process (it may not be immediately obvious that the server in the main process is mostly only here for piping messages to the actors in the child process).
++It becomes especially important when debugging pages with e10s when there are more than one process, because that's when we need to spawn a `DebuggerServer` per process (it may not be immediately obvious that the server in the main process is mostly only here for piping messages to the actors in the child process).
+

+ 255 - 0
rel-257/ian/patches/1446809-6-61a1.patch

@@ -0,0 +1,255 @@
+# HG changeset patch
+# User Sylvestre Ledru <sledru@mozilla.com>
+# Date 1521397922 -3600
+# Node ID 4ab35ba9af3d26556b17a54f0e451b30dfd5a88a
+# Parent  b2647d006cf4fe5d7147ef1eda48c93d54a7af5a
+Bug 1446809 - Remove some b2g leftover in some webgl tests r=jgilbert
+
+MozReview-Commit-ID: Etx3KYygQgl
+
+diff --git a/dom/canvas/test/webgl-conf/generated-mochitest.ini b/dom/canvas/test/webgl-conf/generated-mochitest.ini
+--- a/dom/canvas/test/webgl-conf/generated-mochitest.ini
++++ b/dom/canvas/test/webgl-conf/generated-mochitest.ini
+@@ -1,15 +1,15 @@
+ # This is a GENERATED FILE. Do not edit it directly.
+ # Regenerated it by using `python generate-wrappers-and-manifest.py`.
+ # Mark failing (fail-if) and crashing (skip-if) tests in mochitest-errata.ini.
+ 
+ [DEFAULT]
+ subsuite = webgl
+-skip-if = os == 'b2g' || ((os == 'linux') && (buildapp == 'mulet'))
++skip-if = (os == 'linux') && (buildapp == 'mulet')
+ 
+ support-files = always-fail.html
+                 checkout/00_test_list.txt
+                 checkout/CONFORMANCE_RULES.txt
+                 checkout/README.md
+                 checkout/closure-library/AUTHORS
+                 checkout/closure-library/CONTRIBUTING
+                 checkout/closure-library/LICENSE
+@@ -7532,17 +7532,17 @@ skip-if = (os == 'mac')
+ skip-if = (os == 'android')
+ [generated/test_conformance__canvas__texture-bindings-unaffected-on-resize.html]
+ [generated/test_conformance__canvas__to-data-url-test.html]
+ [generated/test_conformance__canvas__viewport-unchanged-upon-resize.html]
+ skip-if = (os == 'mac')
+ [generated/test_conformance__context__constants-and-properties.html]
+ [generated/test_conformance__context__context-attribute-preserve-drawing-buffer.html]
+ [generated/test_conformance__context__context-attributes-alpha-depth-stencil-antialias.html]
+-skip-if = (os == 'b2g') || (os == 'linux') || (os == 'android')
++skip-if = (os == 'linux') || (os == 'android')
+ fail-if = (os == 'mac' && os_version == '10.6')
+ [generated/test_conformance__context__context-creation-and-destruction.html]
+ [generated/test_conformance__context__context-creation.html]
+ skip-if = (os == 'android')
+ [generated/test_conformance__context__context-eviction-with-garbage-collection.html]
+ skip-if = (os == 'android')
+ [generated/test_conformance__context__context-hidden-alpha.html]
+ [generated/test_conformance__context__context-lost-restored.html]
+@@ -7926,22 +7926,20 @@ fail-if = (os == 'android')
+ [generated/test_conformance__glsl__misc__struct-specifiers-in-uniforms.html]
+ [generated/test_conformance__glsl__misc__struct-unary-operators.html]
+ [generated/test_conformance__glsl__misc__ternary-operator-on-arrays.html]
+ [generated/test_conformance__glsl__misc__ternary-operators-in-global-initializers.html]
+ [generated/test_conformance__glsl__misc__ternary-operators-in-initializers.html]
+ [generated/test_conformance__glsl__misc__uniform-location-length-limits.html]
+ [generated/test_conformance__glsl__reserved___webgl_field.vert.html]
+ [generated/test_conformance__glsl__reserved___webgl_function.vert.html]
+-fail-if = (os == 'b2g')
+ [generated/test_conformance__glsl__reserved___webgl_struct.vert.html]
+ [generated/test_conformance__glsl__reserved___webgl_variable.vert.html]
+ [generated/test_conformance__glsl__reserved__webgl_field.vert.html]
+ [generated/test_conformance__glsl__reserved__webgl_function.vert.html]
+-fail-if = (os == 'b2g')
+ [generated/test_conformance__glsl__reserved__webgl_struct.vert.html]
+ [generated/test_conformance__glsl__reserved__webgl_variable.vert.html]
+ [generated/test_conformance__glsl__samplers__glsl-function-texture2d-bias.html]
+ [generated/test_conformance__glsl__samplers__glsl-function-texture2dlod.html]
+ [generated/test_conformance__glsl__samplers__glsl-function-texture2dproj.html]
+ skip-if = (os == 'android')
+ [generated/test_conformance__glsl__samplers__glsl-function-texture2dprojlod.html]
+ skip-if = (os == 'android')
+@@ -7963,31 +7961,30 @@ skip-if = (os == 'linux')
+ [generated/test_conformance__limits__gl-min-uniforms.html]
+ [generated/test_conformance__misc__bad-arguments-test.html]
+ skip-if = (os == 'mac') || (os == 'win') || (os == 'linux') || (os == 'android')
+ [generated/test_conformance__misc__boolean-argument-conversion.html]
+ skip-if = (os == 'android')
+ [generated/test_conformance__misc__delayed-drawing.html]
+ skip-if = (os == 'android' && android_version == '10')
+ [generated/test_conformance__misc__error-reporting.html]
+-fail-if = (os == 'b2g')
+ [generated/test_conformance__misc__expando-loss.html]
+ [generated/test_conformance__misc__functions-returning-strings.html]
+ [generated/test_conformance__misc__instanceof-test.html]
+ [generated/test_conformance__misc__invalid-passed-params.html]
+ skip-if = (os == 'android') || (os == 'linux')
+ [generated/test_conformance__misc__is-object.html]
+ [generated/test_conformance__misc__null-object-behaviour.html]
+ [generated/test_conformance__misc__object-deletion-behaviour.html]
+ skip-if = (os == 'android' && debug)
+ fail-if = (os == 'android')
+ [generated/test_conformance__misc__shader-precision-format.html]
+ skip-if = (os == 'android')
+ [generated/test_conformance__misc__type-conversion-test.html]
+-skip-if = (os == 'android') || (os == 'b2g') || (os == 'linux')
++skip-if = (os == 'android') || (os == 'linux')
+ fail-if = (os == 'linux')
+ [generated/test_conformance__misc__uninitialized-test.html]
+ skip-if = (os == 'android')
+ [generated/test_conformance__misc__webgl-specific.html]
+ [generated/test_conformance__more__conformance__constants.html]
+ [generated/test_conformance__more__conformance__getContext.html]
+ [generated/test_conformance__more__conformance__methods.html]
+ [generated/test_conformance__more__conformance__quickCheckAPI-A.html]
+@@ -8203,17 +8200,16 @@ fail-if = (os == 'mac' && os_version == 
+ [generated/test_conformance__ogles__GL__swizzlers__swizzlers_105_to_112.html]
+ [generated/test_conformance__ogles__GL__swizzlers__swizzlers_113_to_120.html]
+ [generated/test_conformance__ogles__GL__tan__tan_001_to_006.html]
+ [generated/test_conformance__ogles__GL__vec3__vec3_001_to_008.html]
+ [generated/test_conformance__ogles__GL__vec__vec_001_to_008.html]
+ [generated/test_conformance__ogles__GL__vec__vec_009_to_016.html]
+ [generated/test_conformance__ogles__GL__vec__vec_017_to_018.html]
+ [generated/test_conformance__programs__get-active-test.html]
+-fail-if = (os == 'b2g')
+ [generated/test_conformance__programs__gl-bind-attrib-location-long-names-test.html]
+ [generated/test_conformance__programs__gl-bind-attrib-location-test.html]
+ [generated/test_conformance__programs__gl-get-active-attribute.html]
+ [generated/test_conformance__programs__gl-get-active-uniform.html]
+ [generated/test_conformance__programs__gl-getshadersource.html]
+ [generated/test_conformance__programs__gl-shader-test.html]
+ [generated/test_conformance__programs__invalid-UTF-16.html]
+ [generated/test_conformance__programs__program-infolog.html]
+diff --git a/dom/canvas/test/webgl-conf/mochitest-errata.ini b/dom/canvas/test/webgl-conf/mochitest-errata.ini
+--- a/dom/canvas/test/webgl-conf/mochitest-errata.ini
++++ b/dom/canvas/test/webgl-conf/mochitest-errata.ini
+@@ -18,19 +18,18 @@
+ #   https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832%28v=vs.85%29.aspx
+ #   * Windows 7: 6.1
+ #   * Windows 8: 6.2
+ #   * Windows 8.1: 6.3
+ #   * Windows 10: 10.0
+ 
+ [DEFAULT]
+ subsuite = webgl
+-# Skip B2G for now, until we get a handle on the longer tail of emulator bugs.
+ # Bug 1136181 disabled on Mulet for intermittent failures
+-skip-if = os == 'b2g' || ((os == 'linux') && (buildapp == 'mulet'))
++skip-if = (os == 'linux') && (buildapp == 'mulet')
+ 
+ [generated/test_..__always-fail.html]
+ fail-if = 1
+ 
+ ####################
+ # Tests requesting non-local network connections.
+ 
+ [generated/test_conformance__more__functions__readPixelsBadArgs.html]
+@@ -71,18 +70,18 @@ skip-if = (os == 'android') || (os == 'l
+ # Timeout on D3D11
+ skip-if = (os == 'win')
+ 
+ ########################################################################
+ # Complicated
+ 
+ [generated/test_conformance__context__context-attributes-alpha-depth-stencil-antialias.html]
+ fail-if = (os == 'mac' && os_version == '10.6')
+-# Asserts on 'B2G ICS Emulator Debug' and linux debug. Crashes on Android.
+-skip-if = (os == 'b2g') || (os == 'linux') || (os == 'android')
++# Asserts on linux debug. Crashes on Android.
++skip-if = (os == 'linux') || (os == 'android')
+ 
+ [generated/test_conformance__extensions__webgl-draw-buffers.html]
+ # Crashes
+ skip-if = (os == 'linux')
+ 
+ [generated/test_conformance__glsl__constructors__glsl-construct-bvec3.html]
+ # Crashes from libglsl.so
+ # application crashed [@ jemalloc_crash] on Android
+@@ -107,18 +106,18 @@ skip-if = ((os == 'linux') && asan)
+ [generated/test_conformance__glsl__bugs__sampler-array-using-loop-index.html]
+ # Testfail on Linux after removing SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX.
+ # Only happen on tryserver
+ fail-if = (os == 'linux')
+ 
+ [generated/test_conformance__misc__type-conversion-test.html]
+ fail-if = (os == 'linux')
+ # Resets device on Android 2.3.
+-# Crashes on B2G ICS Emulator, desktop Linux, and Mulet Linux x64.
+-skip-if = (os == 'android') || (os == 'b2g') || (os == 'linux')
++# Crashes on desktop Linux, and Mulet Linux x64.
++skip-if = (os == 'android') || (os == 'linux')
+ 
+ [generated/test_conformance__misc__object-deletion-behaviour.html]
+ fail-if = (os == 'android')
+ # void mozilla::gl::GLContext::fDetachShader(GLuint, GLuint): Generated unexpected GL_INVALID_VALUE error. (0x0501)
+ skip-if = (os == 'android' && debug)
+ 
+ [generated/test_conformance__extensions__oes-vertex-array-object.html]
+ fail-if = (os == 'mac') || (os == 'linux') || (os == 'win')
+@@ -333,36 +332,34 @@ fail-if = (os == 'mac') || (os == 'win')
+ [generated/test_2_conformance__textures__video__tex-2d-rgba-rgba-unsigned_byte.html]
+ fail-if = (os == 'mac') || (os == 'win')
+ [generated/test_2_conformance__textures__video__tex-2d-rgba-rgba-unsigned_short_4_4_4_4.html]
+ fail-if = (os == 'mac') || (os == 'win')
+ [generated/test_2_conformance__textures__video__tex-2d-rgba-rgba-unsigned_short_5_5_5_1.html]
+ fail-if = (os == 'mac') || (os == 'win')
+ ########################################################################
+ # "tst-linux{32,64}-spot-NNN" Slaves:
+-#   Android 2.3, B2G Emu, Linux, and Mulet.
++#   Android 2.3, Linux, and Mulet.
+ # Android: os == 'android'. (Not enough info to separate out 2.3)
+-# B2G Emu: os == 'b2g'.
+ # Linux: os == 'linux'.
+-# Mulet: os == 'b2g' && buildapp == 'mulet'.
++# Mulet: buildapp == 'mulet'.
+ [generated/test_conformance__glsl__bugs__temp-expressions-should-not-crash.html]
+ # Coincidentally enough, crashes on Linux and Android 4.0.
+ skip-if = (os == 'android') || (os == 'linux')
+ [generated/test_conformance__misc__invalid-passed-params.html]
+ # Causes consistent *blues*: "DMError: Remote Device Error: unable to
+ # connect to 127.0.0.1 after 5 attempts" on 'Android 2.3 Opt'.
+ skip-if = (os == 'android') || (os == 'linux')
+ [generated/test_conformance__ogles__GL__functions__functions_001_to_008.html]
+ fail-if = (os == 'android')
+ [generated/test_conformance__ogles__GL__sin__sin_001_to_006.html]
+ fail-if = (os == 'android')
+ [generated/test_conformance__reading__read-pixels-test.html]
+ # Causes consistent *blues*: "DMError: Remote Device Error: unable to
+ # connect to 127.0.0.1 after 5 attempts" on 'Android 2.3 Opt'.
+-# Crashes near on B2G ICS Emulator.
+ skip-if = (os == 'android') || (os == 'linux')
+ [generated/test_conformance__textures__misc__texture-upload-size.html]
+ # application crashed [@ mozilla::WebGLTexture::TexSubImage]
+ skip-if = (os == 'win') || (os == 'android')
+ 
+ ########################################################################
+ ########################################################################
+ # Android
+@@ -578,26 +575,20 @@ skip-if = (os == 'android')
+ # Crashes
+ skip-if = (os == 'android')
+ [generated/test_conformance__renderbuffers__framebuffer-object-attachment.html]
+ # Crashes
+ skip-if = (os == 'android')
+ 
+ ########################################################################
+ ########################################################################
+-# B2G
+ [generated/test_conformance__glsl__reserved___webgl_function.vert.html]
+-fail-if = (os == 'b2g')
+ [generated/test_conformance__glsl__reserved__webgl_function.vert.html]
+-fail-if = (os == 'b2g')
+ [generated/test_conformance__misc__error-reporting.html]
+-fail-if = (os == 'b2g')
+ [generated/test_conformance__programs__get-active-test.html]
+-fail-if = (os == 'b2g')
+-
+ 
+ ########################################################################
+ ########################################################################
+ # Linux
+ [generated/test_conformance__glsl__constructors__glsl-construct-vec-mat-corner-cases.html]
+ # mozalloc_abort in libglsl.so
+ skip-if = (os == 'linux')
+ [generated/test_conformance__glsl__constructors__glsl-construct-vec3.html]
+

+ 33 - 0
rel-257/ian/patches/1446809-7-61a1.patch

@@ -0,0 +1,33 @@
+# HG changeset patch
+# User Sylvestre Ledru <sledru@mozilla.com>
+# Date 1521397984 -3600
+# Node ID c37d8315a391f97e8ee4d30d1ca9735e51ddf61a
+# Parent  4ab35ba9af3d26556b17a54f0e451b30dfd5a88a
+Bug 1446809 - Remove some b2g leftover in a service worker test r=florian
+
+MozReview-Commit-ID: EOLOB3Fe35X
+
+diff --git a/dom/cache/test/mochitest/serviceworker_driver.js b/dom/cache/test/mochitest/serviceworker_driver.js
+--- a/dom/cache/test/mochitest/serviceworker_driver.js
++++ b/dom/cache/test/mochitest/serviceworker_driver.js
+@@ -1,19 +1,12 @@
+ // Any copyright is dedicated to the Public Domain.
+ // http://creativecommons.org/publicdomain/zero/1.0/
+ 
+ function serviceWorkerTestExec(testFile) {
+-  var isB2G = !navigator.userAgent.includes("Android") &&
+-              /Mobile|Tablet/.test(navigator.userAgent);
+-  if (isB2G) {
+-    // TODO B2G doesn't support running service workers for now due to bug 1137683.
+-    dump("Skipping running the test in SW until bug 1137683 gets fixed.\n");
+-    return Promise.resolve();
+-  }
+   return new Promise(function(resolve, reject) {
+     function setupSW(registration) {
+       var worker = registration.waiting ||
+                    registration.active;
+ 
+       window.addEventListener("message",function onMessage(event) {
+         if (event.data.context != "ServiceWorker") {
+           return;
+

+ 140 - 0
rel-257/ian/patches/1446809-8-61a1.patch

@@ -0,0 +1,140 @@
+# HG changeset patch
+# User Sylvestre Ledru <sledru@mozilla.com>
+# Date 1521452597 -3600
+# Node ID 613729ea03d7cd8be60299086a2e4dd1f4431962
+# Parent  29f30bc08ca7b6f27e074e1b6134f5deb2dce227
+Bug 1446809 - Ride along: also remove some mobile/xul/ legacy declaration r=florian
+
+MozReview-Commit-ID: 102syxweBN3
+
+diff --git a/accessible/jsat/Utils.jsm b/accessible/jsat/Utils.jsm
+--- a/accessible/jsat/Utils.jsm
++++ b/accessible/jsat/Utils.jsm
+@@ -24,18 +24,17 @@ ChromeUtils.defineModuleGetter(this, "Pl
+ 
+ var EXPORTED_SYMBOLS = ["Utils", "Logger", "PivotContext", "PrefCache"]; // jshint ignore:line
+ 
+ var Utils = { // jshint ignore:line
+   _buildAppMap: {
+     "{3c2e2abc-06d4-11e1-ac3b-374f68613e61}": "b2g",
+     "{d1bfe7d9-c01e-4237-998b-7b5f960a4314}": "graphene",
+     "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}": "browser",
+-    "{aa3c5121-dab2-40e2-81ca-7ea25febc110}": "mobile/android",
+-    "{a23983c0-fd0e-11dc-95ff-0800200c9a66}": "mobile/xul"
++    "{aa3c5121-dab2-40e2-81ca-7ea25febc110}": "mobile/android"
+   },
+ 
+   init: function Utils_init(aWindow) {
+     if (this._win) {
+       // XXX: only supports attaching to one window now.
+       throw new Error("Only one top-level window could used with AccessFu");
+     }
+     this._win = Cu.getWeakReference(aWindow);
+diff --git a/browser/components/BrowserComponents.manifest b/browser/components/BrowserComponents.manifest
+--- a/browser/components/BrowserComponents.manifest
++++ b/browser/components/BrowserComponents.manifest
+@@ -26,17 +26,16 @@ category command-line-validator b-browse
+ # nsBrowserGlue.js
+ 
+ # This component must restrict its registration for the app-startup category
+ # to the specific list of apps that use it so it doesn't get loaded in xpcshell.
+ # Thus we restrict it to these apps:
+ #
+ #   browser:        {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
+ #   mobile/android: {aa3c5121-dab2-40e2-81ca-7ea25febc110}
+-#   mobile/xul:     {a23983c0-fd0e-11dc-95ff-0800200c9a66}
+ 
+ component {eab9012e-5f74-4cbc-b2b5-a590235513cc} nsBrowserGlue.js
+ contract @mozilla.org/browser/browserglue;1 {eab9012e-5f74-4cbc-b2b5-a590235513cc}
+-category app-startup nsBrowserGlue service,@mozilla.org/browser/browserglue;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66}
++category app-startup nsBrowserGlue service,@mozilla.org/browser/browserglue;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110}
+ component {d8903bf6-68d5-4e97-bcd1-e4d3012f721a} nsBrowserGlue.js
+ #ifndef MOZ_MULET
+ contract @mozilla.org/content-permission/prompt;1 {d8903bf6-68d5-4e97-bcd1-e4d3012f721a}
+ #endif
+diff --git a/browser/components/feeds/BrowserFeeds.manifest b/browser/components/feeds/BrowserFeeds.manifest
+--- a/browser/components/feeds/BrowserFeeds.manifest
++++ b/browser/components/feeds/BrowserFeeds.manifest
+@@ -1,19 +1,18 @@
+ # This component must restrict its registration for the app-startup category
+ # to the specific list of apps that use it so it doesn't get loaded in xpcshell.
+ # Thus we restrict it to these apps:
+ #
+ #   browser:        {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
+ #   mobile/android: {aa3c5121-dab2-40e2-81ca-7ea25febc110}
+-#   mobile/xul:     {a23983c0-fd0e-11dc-95ff-0800200c9a66}
+ 
+ component {229fa115-9412-4d32-baf3-2fc407f76fb1} FeedConverter.js
+ contract @mozilla.org/streamconv;1?from=application/vnd.mozilla.maybe.feed&to=*/* {229fa115-9412-4d32-baf3-2fc407f76fb1}
+ contract @mozilla.org/streamconv;1?from=application/vnd.mozilla.maybe.video.feed&to=*/* {229fa115-9412-4d32-baf3-2fc407f76fb1}
+ contract @mozilla.org/streamconv;1?from=application/vnd.mozilla.maybe.audio.feed&to=*/* {229fa115-9412-4d32-baf3-2fc407f76fb1}
+ component {2376201c-bbc6-472f-9b62-7548040a61c6} FeedConverter.js
+ contract @mozilla.org/browser/feeds/result-service;1 {2376201c-bbc6-472f-9b62-7548040a61c6}
+ component {49bb6593-3aff-4eb3-a068-2712c28bd58e} FeedWriter.js
+ contract @mozilla.org/browser/feeds/result-writer;1 {49bb6593-3aff-4eb3-a068-2712c28bd58e}
+ component {792a7e82-06a0-437c-af63-b2d12e808acc} WebContentConverter.js
+ contract @mozilla.org/embeddor.implemented/web-content-handler-registrar;1 {792a7e82-06a0-437c-af63-b2d12e808acc}
+-category app-startup WebContentConverter service,@mozilla.org/embeddor.implemented/web-content-handler-registrar;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66}
++category app-startup WebContentConverter service,@mozilla.org/embeddor.implemented/web-content-handler-registrar;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110}
+diff --git a/browser/components/sessionstore/nsSessionStore.manifest b/browser/components/sessionstore/nsSessionStore.manifest
+--- a/browser/components/sessionstore/nsSessionStore.manifest
++++ b/browser/components/sessionstore/nsSessionStore.manifest
+@@ -1,13 +1,12 @@
+ # This component must restrict its registration for the app-startup category
+ # to the specific list of apps that use it so it doesn't get loaded in xpcshell.
+ # Thus we restrict it to these apps:
+ #
+ #   browser:        {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
+ #   mobile/android: {aa3c5121-dab2-40e2-81ca-7ea25febc110}
+-#   mobile/xul:     {a23983c0-fd0e-11dc-95ff-0800200c9a66}
+ 
+ component {5280606b-2510-4fe0-97ef-9b5a22eafe6b} nsSessionStore.js
+ contract @mozilla.org/browser/sessionstore;1 {5280606b-2510-4fe0-97ef-9b5a22eafe6b}
+ component {ec7a6c20-e081-11da-8ad9-0800200c9a66} nsSessionStartup.js
+ contract @mozilla.org/browser/sessionstartup;1 {ec7a6c20-e081-11da-8ad9-0800200c9a66}
+-category app-startup nsSessionStartup service,@mozilla.org/browser/sessionstartup;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66}
++category app-startup nsSessionStartup service,@mozilla.org/browser/sessionstartup;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110}
+diff --git a/devtools/shared/system.js b/devtools/shared/system.js
+--- a/devtools/shared/system.js
++++ b/devtools/shared/system.js
+@@ -35,18 +35,17 @@ loader.lazyGetter(this, "endianness", ()
+ });
+ 
+ const APP_MAP = {
+   "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}": "firefox",
+   "{3550f703-e582-4d05-9a08-453d09bdfdc6}": "thunderbird",
+   "{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}": "seamonkey",
+   "{718e30fb-e89b-41dd-9da7-e25a45638b28}": "sunbird",
+   "{3c2e2abc-06d4-11e1-ac3b-374f68613e61}": "b2g",
+-  "{aa3c5121-dab2-40e2-81ca-7ea25febc110}": "mobile/android",
+-  "{a23983c0-fd0e-11dc-95ff-0800200c9a66}": "mobile/xul"
++  "{aa3c5121-dab2-40e2-81ca-7ea25febc110}": "mobile/android"
+ };
+ 
+ var CACHED_INFO = null;
+ 
+ async function getSystemInfo() {
+   if (CACHED_INFO) {
+     return CACHED_INFO;
+   }
+diff --git a/mobile/android/modules/FormAssistant.jsm b/mobile/android/modules/FormAssistant.jsm
+--- a/mobile/android/modules/FormAssistant.jsm
++++ b/mobile/android/modules/FormAssistant.jsm
+@@ -230,17 +230,16 @@ var FormAssistant = {
+     };
+ 
+     this._formAutoCompleteService.autoCompleteSearchAsync(aElement.name || aElement.id,
+                                                           aSearchString, aElement, null,
+                                                           null, resultsAvailable);
+   },
+ 
+   /**
+-   * (Copied from mobile/xul/chrome/content/forms.js)
+    * This function is similar to getListSuggestions from
+    * components/satchel/src/nsInputListAutoComplete.js but sadly this one is
+    * used by the autocomplete.xml binding which is not in used in fennec
+    */
+   _getListSuggestions: function(aElement) {
+     if (!(aElement instanceof Ci.nsIDOMHTMLInputElement) || !aElement.list) {
+       return [];
+     }

+ 119 - 0
rel-257/ian/patches/1446809-9-61a1.patch

@@ -0,0 +1,119 @@
+# HG changeset patch
+# User Sylvestre Ledru <sledru@mozilla.com>
+# Date 1521452729 -3600
+# Node ID 2ad7c7ea01be13997598d954528af7c12f70dd39
+# Parent  83b1bb8ef93475ebdd22eb8a75a49d9539a8a964
+Bug 1446809 - Remove some b2g leftover in devtools/shared/system.js r=jdescottes
+
+MozReview-Commit-ID: 1YlBPwjyWO2
+
+diff --git a/devtools/shared/system.js b/devtools/shared/system.js
+--- a/devtools/shared/system.js
++++ b/devtools/shared/system.js
+@@ -34,17 +34,16 @@ loader.lazyGetter(this, "endianness", ()
+   return "BE";
+ });
+ 
+ const APP_MAP = {
+   "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}": "firefox",
+   "{3550f703-e582-4d05-9a08-453d09bdfdc6}": "thunderbird",
+   "{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}": "seamonkey",
+   "{718e30fb-e89b-41dd-9da7-e25a45638b28}": "sunbird",
+-  "{3c2e2abc-06d4-11e1-ac3b-374f68613e61}": "b2g",
+   "{aa3c5121-dab2-40e2-81ca-7ea25febc110}": "mobile/android"
+ };
+ 
+ var CACHED_INFO = null;
+ 
+ async function getSystemInfo() {
+   if (CACHED_INFO) {
+     return CACHED_INFO;
+@@ -62,32 +61,18 @@ async function getSystemInfo() {
+     os,
+     brandName;
+   let appid = appInfo.ID;
+   let apptype = APP_MAP[appid];
+   let geckoVersion = appInfo.platformVersion;
+   let hardware = "unknown";
+   let version = "unknown";
+ 
+-  // B2G specific
+-  if (apptype === "b2g") {
+-    os = "B2G";
+-    // `getSetting` does not work in child processes on b2g.
+-    // TODO bug 1205797, make this work in child processes.
+-    try {
+-      hardware = await exports.getSetting("deviceinfo.hardware");
+-      version = await exports.getSetting("deviceinfo.os");
+-    } catch (e) {
+-      // Ignore.
+-    }
+-  } else {
+-    // Not B2G
+-    os = appInfo.OS;
+-    version = appInfo.version;
+-  }
++  os = appInfo.OS;
++  version = appInfo.version;
+ 
+   let bundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
+   if (bundle) {
+     brandName = bundle.GetStringFromName("brandFullName");
+   } else {
+     brandName = null;
+   }
+ 
+@@ -119,17 +104,16 @@ async function getSystemInfo() {
+     vendor: appInfo.vendor,
+ 
+     // Name of the application, like "Firefox", "Thunderbird".
+     name: appInfo.name,
+ 
+     // The application's version, for example "0.8.0+" or "3.7a1pre".
+     // Typically, the version of Firefox, for example.
+     // It is different than the version of Gecko or the XULRunner platform.
+-    // On B2G, this is the Gaia version.
+     version,
+ 
+     // The application's build ID/date, for example "2004051604".
+     appbuildid: appInfo.appBuildID,
+ 
+     // The build ID/date of Gecko and the XULRunner platform.
+     platformbuildid: appInfo.platformBuildID,
+     geckobuildid: appInfo.platformBuildID,
+@@ -150,17 +134,16 @@ async function getSystemInfo() {
+     // Returns the endianness of the architecture: either "LE" or "BE"
+     endianness: endianness,
+ 
+     // Returns the hostname of the machine
+     hostname: hostname,
+ 
+     // Name of the OS type. Typically the same as `uname -s`. Possible values:
+     // https://developer.mozilla.org/en/OS_TARGET
+-    // Also may be "B2G".
+     os,
+     platform: os,
+ 
+     // hardware and version info from `deviceinfo.hardware`
+     // and `deviceinfo.os`.
+     hardware,
+ 
+     // Type of process architecture running:
+@@ -298,17 +281,16 @@ function getOSCPU() {
+ }
+ 
+ function getSetting(name) {
+   let deferred = defer();
+ 
+   if ("@mozilla.org/settingsService;1" in Cc) {
+     let settingsService;
+ 
+-    // settingsService fails in b2g child processes
+     // TODO bug 1205797, make this work in child processes.
+     try {
+       settingsService = Cc["@mozilla.org/settingsService;1"]
+                           .getService(Ci.nsISettingsService);
+     } catch (e) {
+       return promise.reject(e);
+     }
+ 

Some files were not shown because too many files changed in this diff