Skip to content

SR-8560: XMLDocument on Linux crashes with a Segmentation Fault #1664

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 22, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Foundation/XMLNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ open class XMLNode: NSObject, NSCopying {
}

internal let _xmlNode: _CFXMLNodePtr
internal var _xmlDocument: XMLDocument?

open func copy(with zone: NSZone? = nil) -> Any {
let newNode = _CFXMLCopyNode(_xmlNode, true)
Expand Down Expand Up @@ -761,6 +762,8 @@ open class XMLNode: NSObject, NSCopying {
node.detach()
}

_xmlDocument = nil

switch kind {
case .document:
_CFXMLFreeDocument(_CFXMLDocPtr(_xmlNode))
Expand Down Expand Up @@ -790,6 +793,11 @@ open class XMLNode: NSObject, NSCopying {
withUnretainedReference {
_CFXMLNodeSetPrivateData(_xmlNode, $0)
}
if let documentPtr = _CFXMLNodeGetDocument(_xmlNode) {
if documentPtr != ptr {
_xmlDocument = XMLDocument._objectNodeForNode(documentPtr)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Won't this create a cyclic strong reference? The document has a reference to its children, and children have a reference to the document. The objects will never be deallocated unless you detach all the children to break the cycle.

}
}
}

internal class func _objectNodeForNode(_ node: _CFXMLNodePtr) -> XMLNode {
Expand Down
17 changes: 17 additions & 0 deletions TestFoundation/TestXMLDocument.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class TestXMLDocument : LoopbackServerTest {
("test_addNamespace", test_addNamespace),
("test_removeNamespace", test_removeNamespace),
("test_optionPreserveAll", test_optionPreserveAll),
("test_rootElementRetainsDocument", test_rootElementRetainsDocument),
]
}

Expand Down Expand Up @@ -527,6 +528,22 @@ class TestXMLDocument : LoopbackServerTest {
let expected = xmlString.lowercased() + "\n"
XCTAssertEqual(expected, String(describing: document))
}

func test_rootElementRetainsDocument() {
let str = """
<?xml version="1.0" encoding="UTF-8"?>
<plans></plans>
"""

let data = str.data(using: .utf8)!

func test() throws -> String? {
let doc = try XMLDocument(data: data, options: []).rootElement()
return doc?.name
}

XCTAssertEqual(try? test(), "plans")
}
}

fileprivate extension XMLNode {
Expand Down