How should we surface imported unsafe C functions in the language? #1841
tothambrus11
started this conversation in
Language design
Replies: 1 comment 1 reply
|
C functions would all be imported as |
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
In Swift, you can import the C standard library using a seemingly harmless line:
import GlibcAfterwards, we can freely use
malloc,free, and other, less obviously dangerous functions. In effect, there is a high chance that code including C interop is not scanned with the diligence we like to do when seeingunsafesomewhere explicitly. Marking the import asunsafe import Glibcwouldn't help, since often we don't look at the whole file (e.g. if a PR only modifies the bottom of the file).This leads me to believe that some local marker for recognizing C function calls would be useful. In the future, we may also interop with safe languages, or other, lower-risk but still unsafe languages. I think in the end the direct consumer of the foreign API should be able to fine-tune what are mapped as unsafe functions.
It's an open question whether we want either function or type coloring with safe/unsafe. Swift doesn't have an unsafe keyword, but usually includes
unsafein the function name. Unfortunately, some functions that expose the possibility of UB don't include unsafe in the function name, which can have security implications.As for C interop, I think the default should be to prepend
unsafe_. But for example, if a library we are importing always starts its function names viaLLVM, it's easy to recognize that as something with C interop, so I would want to add that to the allowlist for brevity.CONTRIBUTING.md. We can provide tools that enforce & update that documentation based on the preset rules.))Maybe the reason why Swift chose to not rename C functions by default is that most C functions will require an
UnsafeMutablePointer, which will likely be present in the neighbourhood of any dangerous call. Any opinions or good/bad experiences?All reactions