Skip to content

Commit b9b4c78

Browse files
committed
Fix a data race on _swiftEmptyArrayStorage reported by TSan. Array.append(contentsOf) used to write a 0 into _buffer.count causing a race.
1 parent f19aca6 commit b9b4c78

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

stdlib/public/core/Array.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1162,7 +1162,10 @@ extension Array: RangeReplaceableCollection {
11621162
"newElements.underestimatedCount was an overestimate")
11631163
// can't check for overflow as sequences can underestimate
11641164

1165-
_buffer.count += writtenCount
1165+
// This check prevents a data race writting to _swiftEmptyArrayStorage
1166+
if writtenCount > 0 {
1167+
_buffer.count += writtenCount
1168+
}
11661169

11671170
if writtenUpTo == buf.endIndex {
11681171
// there may be elements that didn't fit in the existing buffer,
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=thread -o %t_tsan-binary
2+
// RUN: %target-codesign %t_tsan-binary
3+
// RUN: %target-run %t_tsan-binary 2>&1 | %FileCheck %s
4+
// REQUIRES: executable_test
5+
// REQUIRES: tsan_runtime
6+
// UNSUPPORTED: OS=tvos
7+
8+
// FIXME: This should be covered by "tsan_runtime"; older versions of Apple OSs
9+
// don't support TSan.
10+
// UNSUPPORTED: remote_run
11+
12+
import Foundation
13+
14+
let sem = DispatchSemaphore(value: 0)
15+
16+
class T1: Thread {
17+
override func main() {
18+
var oneEmptyArray: [[String:String]] = []
19+
oneEmptyArray.append(contentsOf: [])
20+
sem.signal()
21+
}
22+
}
23+
let t1 = T1()
24+
t1.start()
25+
26+
class T2: Thread {
27+
override func main() {
28+
var aCompletelyUnrelatedOtherEmptyArray: [[Double:Double]] = []
29+
aCompletelyUnrelatedOtherEmptyArray.append(contentsOf: [])
30+
sem.signal()
31+
}
32+
}
33+
let t2 = T2()
34+
t2.start()
35+
36+
sem.wait()
37+
sem.wait()
38+
print("Done!")
39+
40+
// CHECK: Done!

0 commit comments

Comments
 (0)