Binary produced in a different directory cannot be copied correctly with NSFileManager.copyItem* on an APFS volume

Originator:marquissm
Number:rdar://32984063 Date Originated:06/26/2017
Status:Duplicate/32747641 Resolved:
Product: Product Version:
Classification: Reproducible:
 
Area:
AppKit

Summary:
This was originally discovered while investigating https://github.com/Carthage/Carthage/issues/1982. I narrowed it down to a simple example, which I've attached, which results in an invalid binary being produced. I believe it's related to the APFS cloning capability, but it only seems to show up in certain circumstances

Steps to Reproduce:
In the attached sample there's a 'runExample.sh' that performs these steps, but the reproduction is (on an APFS volume)
- Create a simple swift 'main.swift' file
- Create a subdirectory
- Run `swift -o subdirectory/Binary main.swift` to compile the binary into another directory (the bug only happens if it gets compiled to a different directory)
- Run the binary to verify it works correctly
- In another program, use 'FileManager.copyItem(at:to:)' to copy the resulting binary from the subdirectory into the main directory
- Run the copy. Mac os will throw an error.

Expected Results:
The binary should be a valid copy, capable of running.

Observed Results:
The binary is invalid. If you inspect the binary, it's the exact same size as the original, but filled with zeroed bytes. This only seems to happens when directories are involved, and only with binaries produced during compiling (at least I haven't found another way to produce a binary that does this). Note that if you cp the binary via the command line, that copy no longer produces this behavior, you can use copyItem on that binary without issue. It's only the originally produced binary that this behavior arises.

Version:
mac os sierra 10.12.5 (16F73)

Though it was originally found on High Sierra

Notes:


Configuration:
The most important aspect is it being on an APFS volume

Comments

Oh and the Xcode version I was using was "Version 8.3.2 (8E2002)", with swift "Apple Swift version 3.1 (swiftlang-802.0.53 clang-802.0.42)". It also reproduces with the Xcode 9 beta tools.


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!