Merge pull request #1009 from mamabusi/appSpecificSharedCookies

diff --git a/Foundation.xcodeproj/project.pbxproj b/Foundation.xcodeproj/project.pbxproj
index 99f3978..77ead89 100644
--- a/Foundation.xcodeproj/project.pbxproj
+++ b/Foundation.xcodeproj/project.pbxproj
@@ -249,6 +249,7 @@
 		5BA9BEA61CF3D747009DBD6C /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BA9BEA51CF3D747009DBD6C /* Data.swift */; };
 		5BA9BEA81CF3E7E7009DBD6C /* CharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BA9BEA71CF3E7E7009DBD6C /* CharacterSet.swift */; };
 		5BA9BEBD1CF4F3B8009DBD6C /* Notification.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BA9BEBC1CF4F3B8009DBD6C /* Notification.swift */; };
+		5BB2C75F1ED9F96200B7BDBD /* CFUserNotification.h in Headers */ = {isa = PBXBuildFile; fileRef = 5B5D89391BBDA7AB00234F36 /* CFUserNotification.h */; settings = {ATTRIBUTES = (Public, ); }; };
 		5BB5256C1BEC057200E63BE3 /* module.modulemap in Headers */ = {isa = PBXBuildFile; fileRef = 5BDC3F721BCC60EF00ED97BB /* module.modulemap */; settings = {ATTRIBUTES = (Public, ); }; };
 		5BC2C00F1C07833200CC214E /* CFStringTransform.c in Sources */ = {isa = PBXBuildFile; fileRef = 5BC2C00D1C07832E00CC214E /* CFStringTransform.c */; };
 		5BC46D541D05D6D900005853 /* DateInterval.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BC46D531D05D6D900005853 /* DateInterval.swift */; };
@@ -765,6 +766,7 @@
 		90E645DE1E4C89A400D0D47C /* TestNSCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSCache.swift; sourceTree = "<group>"; };
 		A5A34B551C18C85D00FD972B /* TestNSByteCountFormatter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSByteCountFormatter.swift; sourceTree = "<group>"; };
 		AE35A1851CBAC85E0042DB84 /* SwiftFoundation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SwiftFoundation.h; sourceTree = "<group>"; };
+		B167A6641ED7303F0040B09A /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = "<group>"; };
 		BD8042151E09857800487EB8 /* TestNSLengthFormatter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSLengthFormatter.swift; sourceTree = "<group>"; };
 		BDBB658F1E256BFA001A7286 /* TestNSEnergyFormatter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSEnergyFormatter.swift; sourceTree = "<group>"; };
 		BDFDF0A61DFF5B3E00C04CC5 /* TestNSPersonNameComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSPersonNameComponents.swift; sourceTree = "<group>"; };
@@ -956,6 +958,7 @@
 		5B5D88531BBC938800234F36 = {
 			isa = PBXGroup;
 			children = (
+				B167A6641ED7303F0040B09A /* README.md */,
 				5BDC3F2C1BCC5DB500ED97BB /* Foundation */,
 				EAB57B681BD1A255004AC5C5 /* CoreFoundation */,
 				EA66F65B1BF2DF3200136161 /* Bootstrap */,
@@ -1805,6 +1808,7 @@
 				5B7C8ADB1BEA80FC00C5B690 /* CFRunLoop.h in Headers */,
 				5B7C8AFC1BEA81AC00C5B690 /* CFUnicodeDecomposition.h in Headers */,
 				5B7C8AF41BEA81AC00C5B690 /* CFCharacterSetPriv.h in Headers */,
+				5BB2C75F1ED9F96200B7BDBD /* CFUserNotification.h in Headers */,
 				5B7C8AEF1BEA81AC00C5B690 /* CFBundlePriv.h in Headers */,
 				5B7C8B011BEA82F800C5B690 /* CFError_Private.h in Headers */,
 				5B7C8AF31BEA81AC00C5B690 /* CFStreamPriv.h in Headers */,
@@ -2502,6 +2506,7 @@
 				PRODUCT_BUNDLE_IDENTIFIER = org.swift.Foundation;
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SKIP_INSTALL = YES;
+				SWIFT_INDEX_STORE_ENABLE = NO;
 				SWIFT_INSTALL_OBJC_HEADER = NO;
 				SWIFT_OBJC_INTERFACE_HEADER_NAME = "";
 				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
@@ -2574,6 +2579,7 @@
 				PRODUCT_BUNDLE_IDENTIFIER = org.swift.Foundation;
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SKIP_INSTALL = YES;
+				SWIFT_INDEX_STORE_ENABLE = NO;
 				SWIFT_INSTALL_OBJC_HEADER = NO;
 				SWIFT_OBJC_INTERFACE_HEADER_NAME = "";
 				SWIFT_VERSION = 3.0;
diff --git a/Foundation/NSDecimal.swift b/Foundation/NSDecimal.swift
index 88785f2..e22cfcd 100644
--- a/Foundation/NSDecimal.swift
+++ b/Foundation/NSDecimal.swift
@@ -205,29 +205,16 @@
         if _length == 0 && _isNegative == 1 {
             return Double.nan
         }
-        for i in 0..<8 {
-            let index = 8 - i - 1
-            switch index {
-            case 0:
-                d = d * 65536 + Double(_mantissa.0)
-            case 1:
-                d = d * 65536 + Double(_mantissa.1)
-            case 2:
-                d = d * 65536 + Double(_mantissa.2)
-            case 3:
-                d = d * 65536 + Double(_mantissa.3)
-            case 4:
-                d = d * 65536 + Double(_mantissa.4)
-            case 5:
-                d = d * 65536 + Double(_mantissa.5)
-            case 6:
-                d = d * 65536 + Double(_mantissa.6)
-            case 7:
-                d = d * 65536 + Double(_mantissa.7)
-            default:
-                fatalError("conversion overflow")
-            }
-        }
+        
+        d = d * 65536 + Double(_mantissa.7)
+        d = d * 65536 + Double(_mantissa.6)
+        d = d * 65536 + Double(_mantissa.5)
+        d = d * 65536 + Double(_mantissa.4)
+        d = d * 65536 + Double(_mantissa.3)
+        d = d * 65536 + Double(_mantissa.2)
+        d = d * 65536 + Double(_mantissa.1)
+        d = d * 65536 + Double(_mantissa.0)
+        
         if _exponent < 0 {
             for _ in _exponent..<0 {
                 d /= 10.0
diff --git a/Foundation/NSStringAPI.swift b/Foundation/NSStringAPI.swift
index 3b781df..baa36f8 100644
--- a/Foundation/NSStringAPI.swift
+++ b/Foundation/NSStringAPI.swift
@@ -1562,7 +1562,7 @@
     fatalError("unavailable function can't be called")
   }
 
-  @available(*, unavailable, renamed: "componentsSeparated(by:)")
+  @available(*, unavailable, renamed: "components(separatedBy:)")
   public func componentsSeparatedBy(_ separator: String) -> [String] {
     fatalError("unavailable function can't be called")
   }
diff --git a/TestFoundation/TestNSURLSession.swift b/TestFoundation/TestNSURLSession.swift
index 493f0da..d06e88d 100644
--- a/TestFoundation/TestNSURLSession.swift
+++ b/TestFoundation/TestNSURLSession.swift
@@ -24,19 +24,19 @@
 //Disabling to avoid https://bugs.swift.org/browse/SR-4677 and a timeout failure
 //            ("test_dataTaskWithURL", test_dataTaskWithURL),
 //            ("test_dataTaskWithURLRequest", test_dataTaskWithURLRequest),
-//            ("test_dataTaskWithURLCompletionHandler", test_dataTaskWithURLCompletionHandler),
-//            ("test_dataTaskWithURLRequestCompletionHandler", test_dataTaskWithURLRequestCompletionHandler),
+            ("test_dataTaskWithURLCompletionHandler", test_dataTaskWithURLCompletionHandler),
+            ("test_dataTaskWithURLRequestCompletionHandler", test_dataTaskWithURLRequestCompletionHandler),
 //            ("test_downloadTaskWithURL", test_downloadTaskWithURL),
 //            ("test_downloadTaskWithURLRequest", test_downloadTaskWithURLRequest),
-//            ("test_downloadTaskWithRequestAndHandler", test_downloadTaskWithRequestAndHandler),
-//            ("test_downloadTaskWithURLAndHandler", test_downloadTaskWithURLAndHandler),
+            ("test_downloadTaskWithRequestAndHandler", test_downloadTaskWithRequestAndHandler),
+            ("test_downloadTaskWithURLAndHandler", test_downloadTaskWithURLAndHandler),
 //            ("test_finishTaskAndInvalidate", test_finishTasksAndInvalidate),
 //            ("test_taskError", test_taskError),
-//            ("test_taskCopy", test_taskCopy),
+            ("test_taskCopy", test_taskCopy),
 //            ("test_cancelTask", test_cancelTask),
 //            ("test_taskTimeout", test_taskTimeout),
-//            ("test_verifyRequestHeaders", test_verifyRequestHeaders),
-//            ("test_verifyHttpAdditionalHeaders", test_verifyHttpAdditionalHeaders),
+            ("test_verifyRequestHeaders", test_verifyRequestHeaders),
+            ("test_verifyHttpAdditionalHeaders", test_verifyHttpAdditionalHeaders),
             ("test_timeoutInterval", test_timeoutInterval),
         ]
     }
@@ -97,17 +97,14 @@
         let expect = expectation(description: "URL test with completion handler")
         var expectedResult = "unknown"
         let task = session.dataTask(with: url) { data, response, error in
-            if let e = error as? URLError {
-                XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
-                expect.fulfill()
-                return
-            }
-
-            let httpResponse = response as! HTTPURLResponse?
-            XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200")
-            expectedResult = String(data: data!, encoding: String.Encoding.utf8)!
+            defer { expect.fulfill() }
+            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
+            XCTAssertNotNil(response)
+            XCTAssertNotNil(data)
+            guard let httpResponse = response as? HTTPURLResponse, let data = data else { return }
+            XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
+            expectedResult = String(data: data, encoding: String.Encoding.utf8) ?? ""
             XCTAssertEqual("Washington, D.C.", expectedResult, "Did not receive expected value")
-            expect.fulfill()
         }
         task.resume()
         waitForExpectations(timeout: 12)
@@ -153,16 +150,14 @@
         let expect = expectation(description: "URL test with completion handler")
         var expectedResult = "unknown"
         let task = session.dataTask(with: urlRequest) { data, response, error in
-            if let e = error as? URLError {
-                XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
-                expect.fulfill()
-                return
-            }
-            let httpResponse = response as! HTTPURLResponse?
-            XCTAssertEqual(200, httpResponse!.statusCode, "HTTP response code is not 200")
-            expectedResult = String(data: data!, encoding: String.Encoding.utf8)!
+            defer { expect.fulfill() }
+            XCTAssertNotNil(data)
+            XCTAssertNotNil(response)
+            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
+            guard let httpResponse = response as? HTTPURLResponse, let data = data else { return }
+            XCTAssertEqual(200, httpResponse.statusCode, "HTTP response code is not 200")
+            expectedResult = String(data: data, encoding: String.Encoding.utf8) ?? ""
             XCTAssertEqual("Rome", expectedResult, "Did not receive expected value")
-            expect.fulfill()
         }
         task.resume()
         waitForExpectations(timeout: 12)
@@ -221,9 +216,7 @@
         let expect = expectation(description: "download task with handler")
         let req = URLRequest(url: URL(string: "http://127.0.0.1:\(serverPort)/country.txt")!)
         let task = session.downloadTask(with: req) { (_, _, error) -> Void in
-            if let e = error as? URLError {
-                XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
-            }
+            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
             expect.fulfill()
         }
         task.resume()
@@ -344,7 +337,10 @@
         req.allHTTPHeaderFields = headers
         var task = session.dataTask(with: req) { (data, _, error) -> Void in
             defer { expect.fulfill() }
-            let headers = String(data: data!, encoding: String.Encoding.utf8)!
+            XCTAssertNotNil(data)
+            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
+            guard let data = data else { return }
+            let headers = String(data: data, encoding: String.Encoding.utf8) ?? ""
             XCTAssertNotNil(headers.range(of: "header1: value1"))
         }
         task.resume()
@@ -377,7 +373,9 @@
         req.allHTTPHeaderFields = headers
         var task = session.dataTask(with: req) { (data, _, error) -> Void in
             defer { expect.fulfill() }
-            let headers = String(data: data!, encoding: String.Encoding.utf8)!
+            XCTAssertNotNil(data)
+            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
+            let headers = String(data: data!, encoding: String.Encoding.utf8) ?? ""
             XCTAssertNotNil(headers.range(of: "header1: rvalue1"))
             XCTAssertNotNil(headers.range(of: "header2: rvalue2"))
             XCTAssertNotNil(headers.range(of: "header3: svalue3"))
@@ -405,7 +403,7 @@
         let req = URLRequest(url: URL(string: "http://127.0.0.1:\(serverPort)/Peru")!)
         var task = session.dataTask(with: req) { (data, _, error) -> Void in
             defer { expect.fulfill() }
-            XCTAssertNil(error)
+            XCTAssertNil(error as? URLError, "error = \(error as! URLError)")
         }
         task.resume()
 
diff --git a/lib/product.py b/lib/product.py
index 925cd78..851b39e 100644
--- a/lib/product.py
+++ b/lib/product.py
@@ -77,11 +77,12 @@
     def __init__(self, name):
         Product.__init__(self, name)
 
-    def generate(self, flags):
-        generated = Product.generate(self)
-        objects = []
-        for phase in self.phases:
-            objects += phase.objects
+    def generate(self, flags, objects = []):
+        generated = ""
+        if len(objects) == 0:
+            generated = Product.generate(self)
+            for phase in self.phases:
+                objects += phase.objects
 
         product_flags = " ".join(flags)
         if self.LDFLAGS is not None:
@@ -106,7 +107,7 @@
 
 """
 
-        return generated
+        return objects, generated
 
 
 class DynamicLibrary(Library):
@@ -114,15 +115,15 @@
         Library.__init__(self, name)
         self.name = name
 
-    def generate(self):
+    def generate(self, objects = []):
         self.rule = "Link"
         self.product_name = Configuration.current.target.dynamic_library_prefix + self.name + Configuration.current.target.dynamic_library_suffix
         if Configuration.current.target.sdk == OSType.Linux or Configuration.current.target.sdk == OSType.FreeBSD:
             self.conformance_begin = '${SDKROOT}/lib/swift/${OS}/${ARCH}/swift_begin.o' 
             self.conformance_end = '${SDKROOT}/lib/swift/${OS}/${ARCH}/swift_end.o' 
-            return Library.generate(self, ["-shared", "-Wl,-soname," + self.product_name, "-Wl,--no-undefined"])
+            return Library.generate(self, ["-shared", "-Wl,-soname," + self.product_name, "-Wl,--no-undefined"], objects)
         else:
-            return Library.generate(self, ["-shared"])
+            return Library.generate(self, ["-shared"], objects)
 
 
 class Framework(Product):
@@ -189,7 +190,9 @@
         DynamicLibrary.__init__(self, name)
 
     def generate(self):
-        return StaticLibrary.generate(self) + DynamicLibrary.generate(self)
+        objects, generatedForStatic = StaticLibrary.generate(self)
+        _, generatedForDynamic = DynamicLibrary.generate(self, objects)
+        return generatedForStatic + generatedForDynamic
 
 class Executable(Product):
     def __init__(self, name):