502 lines
16 KiB

8 years ago
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <meta name="theme-color" content="#375EAB">
  7. <title>unsafe - The Go Programming Language</title>
  8. <link type="text/css" rel="stylesheet" href="../../lib/godoc/style.css">
  9. <link rel="stylesheet" href="../../lib/godoc/jquery.treeview.css">
  10. <script type="text/javascript">window.initFuncs = [];</script>
  11. </head>
  12. <body>
  13. <div id='lowframe' style="position: fixed; bottom: 0; left: 0; height: 0; width: 100%; border-top: thin solid grey; background-color: white; overflow: auto;">
  14. ...
  15. </div><!-- #lowframe -->
  16. <div id="topbar" class="wide"><div class="container">
  17. <div class="top-heading" id="heading-wide"><a href="http://localhost:6060/">The Go Programming Language</a></div>
  18. <div class="top-heading" id="heading-narrow"><a href="http://localhost:6060/">Go</a></div>
  19. <a href="index.html#" id="menu-button"><span id="menu-button-arrow">&#9661;</span></a>
  20. <form method="GET" action="http://localhost:6060/search">
  21. <div id="menu">
  22. <a href="http://localhost:6060/doc/">Documents</a>
  23. <a href="http://localhost:6060/pkg/">Packages</a>
  24. <a href="http://localhost:6060/project/">The Project</a>
  25. <a href="http://localhost:6060/help/">Help</a>
  26. <a href="http://localhost:6060/blog/">Blog</a>
  27. <input type="text" id="search" name="q" class="inactive" value="Search" placeholder="Search">
  28. </div>
  29. </form>
  30. </div></div>
  31. <div id="page" class="wide">
  32. <div class="container">
  33. <h1>Package unsafe</h1>
  34. <div id="nav"></div>
  35. <!--
  36. Copyright 2009 The Go Authors. All rights reserved.
  37. Use of this source code is governed by a BSD-style
  38. license that can be found in the LICENSE file.
  39. -->
  40. <!--
  41. Note: Static (i.e., not template-generated) href and id
  42. attributes start with "pkg-" to make it impossible for
  43. them to conflict with generated attributes (some of which
  44. correspond to Go identifiers).
  45. -->
  46. <script type='text/javascript'>
  47. document.ANALYSIS_DATA = null;
  48. document.CALLGRAPH = null;
  49. </script>
  50. <div id="short-nav">
  51. <dl>
  52. <dd><code>import "unsafe"</code></dd>
  53. </dl>
  54. <dl>
  55. <dd><a href="index.html#pkg-overview" class="overviewLink">Overview</a></dd>
  56. <dd><a href="index.html#pkg-index" class="indexLink">Index</a></dd>
  57. </dl>
  58. </div>
  59. <!-- The package's Name is printed as title by the top-level template -->
  60. <div id="pkg-overview" class="toggleVisible">
  61. <div class="collapsed">
  62. <h2 class="toggleButton" title="Click to show Overview section">Overview ▹</h2>
  63. </div>
  64. <div class="expanded">
  65. <h2 class="toggleButton" title="Click to hide Overview section">Overview ▾</h2>
  66. <p>
  67. Package unsafe contains operations that step around the type safety of Go programs.
  68. </p>
  69. <p>
  70. Packages that import unsafe may be non-portable and are not protected by the
  71. Go 1 compatibility guidelines.
  72. </p>
  73. </div>
  74. </div>
  75. <div id="pkg-index" class="toggleVisible">
  76. <div class="collapsed">
  77. <h2 class="toggleButton" title="Click to show Index section">Index ▹</h2>
  78. </div>
  79. <div class="expanded">
  80. <h2 class="toggleButton" title="Click to hide Index section">Index ▾</h2>
  81. <!-- Table of contents for API; must be named manual-nav to turn off auto nav. -->
  82. <div id="manual-nav">
  83. <dl>
  84. <dd><a href="index.html#Alignof">func Alignof(x ArbitraryType) uintptr</a></dd>
  85. <dd><a href="index.html#Offsetof">func Offsetof(x ArbitraryType) uintptr</a></dd>
  86. <dd><a href="index.html#Sizeof">func Sizeof(x ArbitraryType) uintptr</a></dd>
  87. <dd><a href="index.html#ArbitraryType">type ArbitraryType</a></dd>
  88. <dd><a href="index.html#Pointer">type Pointer</a></dd>
  89. </dl>
  90. </div><!-- #manual-nav -->
  91. <h4>Package files</h4>
  92. <p>
  93. <span style="font-size:90%">
  94. <a href="http://localhost:6060/src/unsafe/unsafe.go">unsafe.go</a>
  95. </span>
  96. </p>
  97. </div><!-- .expanded -->
  98. </div><!-- #pkg-index -->
  99. <div id="pkg-callgraph" class="toggle" style="display: none">
  100. <div class="collapsed">
  101. <h2 class="toggleButton" title="Click to show Internal Call Graph section">Internal call graph ▹</h2>
  102. </div> <!-- .expanded -->
  103. <div class="expanded">
  104. <h2 class="toggleButton" title="Click to hide Internal Call Graph section">Internal call graph ▾</h2>
  105. <p>
  106. In the call graph viewer below, each node
  107. is a function belonging to this package
  108. and its children are the functions it
  109. calls&mdash;perhaps dynamically.
  110. </p>
  111. <p>
  112. The root nodes are the entry points of the
  113. package: functions that may be called from
  114. outside the package.
  115. There may be non-exported or anonymous
  116. functions among them if they are called
  117. dynamically from another package.
  118. </p>
  119. <p>
  120. Click a node to visit that function's source code.
  121. From there you can visit its callers by
  122. clicking its declaring <code>func</code>
  123. token.
  124. </p>
  125. <p>
  126. Functions may be omitted if they were
  127. determined to be unreachable in the
  128. particular programs or tests that were
  129. analyzed.
  130. </p>
  131. <!-- Zero means show all package entry points. -->
  132. <ul style="margin-left: 0.5in" id="callgraph-0" class="treeview"></ul>
  133. </div>
  134. </div> <!-- #pkg-callgraph -->
  135. <h2 id="Alignof">func <a href="http://localhost:6060/src/unsafe/unsafe.go?s=8764:8801#L184">Alignof</a></h2>
  136. <pre>func Alignof(x <a href="index.html#ArbitraryType">ArbitraryType</a>) <a href="../builtin/index.html#uintptr">uintptr</a></pre>
  137. <p>
  138. Alignof takes an expression x of any type and returns the required alignment
  139. of a hypothetical variable v as if v was declared via var v = x.
  140. It is the largest value m such that the address of v is always zero mod m.
  141. It is the same as the value returned by reflect.TypeOf(x).Align().
  142. As a special case, if a variable s is of struct type and f is a field
  143. within that struct, then Alignof(s.f) will return the required alignment
  144. of a field of that type within a struct. This case is the same as the
  145. value returned by reflect.TypeOf(s.f).FieldAlign().
  146. </p>
  147. <h2 id="Offsetof">func <a href="http://localhost:6060/src/unsafe/unsafe.go?s=8150:8188#L174">Offsetof</a></h2>
  148. <pre>func Offsetof(x <a href="index.html#ArbitraryType">ArbitraryType</a>) <a href="../builtin/index.html#uintptr">uintptr</a></pre>
  149. <p>
  150. Offsetof returns the offset within the struct of the field represented by x,
  151. which must be of the form structValue.field. In other words, it returns the
  152. number of bytes between the start of the struct and the start of the field.
  153. </p>
  154. <h2 id="Sizeof">func <a href="http://localhost:6060/src/unsafe/unsafe.go?s=7873:7909#L169">Sizeof</a></h2>
  155. <pre>func Sizeof(x <a href="index.html#ArbitraryType">ArbitraryType</a>) <a href="../builtin/index.html#uintptr">uintptr</a></pre>
  156. <p>
  157. Sizeof takes an expression x of any type and returns the size in bytes
  158. of a hypothetical variable v as if v was declared via var v = x.
  159. The size does not include any memory possibly referenced by x.
  160. For instance, if x is a slice, Sizeof returns the size of the slice
  161. descriptor, not the size of the memory referenced by the slice.
  162. </p>
  163. <h2 id="ArbitraryType">type <a href="http://localhost:6060/src/unsafe/unsafe.go?s=548:570#L5">ArbitraryType</a></h2>
  164. <pre>type ArbitraryType <a href="../builtin/index.html#int">int</a></pre>
  165. <p>
  166. ArbitraryType is here for the purposes of documentation only and is not actually
  167. part of the unsafe package. It represents the type of an arbitrary Go expression.
  168. </p>
  169. <h2 id="Pointer">type <a href="http://localhost:6060/src/unsafe/unsafe.go?s=7497:7524#L162">Pointer</a></h2>
  170. <pre>type Pointer *<a href="index.html#ArbitraryType">ArbitraryType</a></pre>
  171. <p>
  172. Pointer represents a pointer to an arbitrary type. There are four special operations
  173. available for type Pointer that are not available for other types:
  174. </p>
  175. <pre>- A pointer value of any type can be converted to a Pointer.
  176. - A Pointer can be converted to a pointer value of any type.
  177. - A uintptr can be converted to a Pointer.
  178. - A Pointer can be converted to a uintptr.
  179. </pre>
  180. <p>
  181. Pointer therefore allows a program to defeat the type system and read and write
  182. arbitrary memory. It should be used with extreme care.
  183. </p>
  184. <p>
  185. The following patterns involving Pointer are valid.
  186. Code not using these patterns is likely to be invalid today
  187. or to become invalid in the future.
  188. Even the valid patterns below come with important caveats.
  189. </p>
  190. <p>
  191. Running &#34;go vet&#34; can help find uses of Pointer that do not conform to these patterns,
  192. but silence from &#34;go vet&#34; is not a guarantee that the code is valid.
  193. </p>
  194. <p>
  195. (1) Conversion of a *T1 to Pointer to *T2.
  196. </p>
  197. <p>
  198. Provided that T2 is no larger than T1 and that the two share an equivalent
  199. memory layout, this conversion allows reinterpreting data of one type as
  200. data of another type. An example is the implementation of
  201. math.Float64bits:
  202. </p>
  203. <pre>func Float64bits(f float64) uint64 {
  204. return *(*uint64)(unsafe.Pointer(&amp;f))
  205. }
  206. </pre>
  207. <p>
  208. (2) Conversion of a Pointer to a uintptr (but not back to Pointer).
  209. </p>
  210. <p>
  211. Converting a Pointer to a uintptr produces the memory address of the value
  212. pointed at, as an integer. The usual use for such a uintptr is to print it.
  213. </p>
  214. <p>
  215. Conversion of a uintptr back to Pointer is not valid in general.
  216. </p>
  217. <p>
  218. A uintptr is an integer, not a reference.
  219. Converting a Pointer to a uintptr creates an integer value
  220. with no pointer semantics.
  221. Even if a uintptr holds the address of some object,
  222. the garbage collector will not update that uintptr&#39;s value
  223. if the object moves, nor will that uintptr keep the object
  224. from being reclaimed.
  225. </p>
  226. <p>
  227. The remaining patterns enumerate the only valid conversions
  228. from uintptr to Pointer.
  229. </p>
  230. <p>
  231. (3) Conversion of a Pointer to a uintptr and back, with arithmetic.
  232. </p>
  233. <p>
  234. If p points into an allocated object, it can be advanced through the object
  235. by conversion to uintptr, addition of an offset, and conversion back to Pointer.
  236. </p>
  237. <pre>p = unsafe.Pointer(uintptr(p) + offset)
  238. </pre>
  239. <p>
  240. The most common use of this pattern is to access fields in a struct
  241. or elements of an array:
  242. </p>
  243. <pre>// equivalent to f := unsafe.Pointer(&amp;s.f)
  244. f := unsafe.Pointer(uintptr(unsafe.Pointer(&amp;s)) + unsafe.Offsetof(s.f))
  245. // equivalent to e := unsafe.Pointer(&amp;x[i])
  246. e := unsafe.Pointer(uintptr(unsafe.Pointer(&amp;x[0])) + i*unsafe.Sizeof(x[0]))
  247. </pre>
  248. <p>
  249. It is valid both to add and to subtract offsets from a pointer in this way,
  250. but the result must continue to point into the original allocated object.
  251. Unlike in C, it is not valid to advance a pointer just beyond the end of
  252. its original allocation:
  253. </p>
  254. <pre>// INVALID: end points outside allocated space.
  255. var s thing
  256. end = unsafe.Pointer(uintptr(unsafe.Pointer(&amp;s)) + unsafe.Sizeof(s))
  257. // INVALID: end points outside allocated space.
  258. b := make([]byte, n)
  259. end = unsafe.Pointer(uintptr(unsafe.Pointer(&amp;b[0])) + uintptr(n))
  260. </pre>
  261. <p>
  262. Note that both conversions must appear in the same expression, with only
  263. the intervening arithmetic between them:
  264. </p>
  265. <pre>// INVALID: uintptr cannot be stored in variable
  266. // before conversion back to Pointer.
  267. u := uintptr(p)
  268. p = unsafe.Pointer(u + offset)
  269. </pre>
  270. <p>
  271. (4) Conversion of a Pointer to a uintptr when calling syscall.Syscall.
  272. </p>
  273. <p>
  274. The Syscall functions in package syscall pass their uintptr arguments directly
  275. to the operating system, which then may, depending on the details of the call,
  276. reinterpret some of them as pointers.
  277. That is, the system call implementation is implicitly converting certain arguments
  278. back from uintptr to pointer.
  279. </p>
  280. <p>
  281. If a pointer argument must be converted to uintptr for use as an argument,
  282. that conversion must appear in the call expression itself:
  283. </p>
  284. <pre>syscall.Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(n))
  285. </pre>
  286. <p>
  287. The compiler handles a Pointer converted to a uintptr in the argument list of
  288. a call to a function implemented in assembly by arranging that the referenced
  289. allocated object, if any, is retained and not moved until the call completes,
  290. even though from the types alone it would appear that the object is no longer
  291. needed during the call.
  292. </p>
  293. <p>
  294. For the compiler to recognize this pattern,
  295. the conversion must appear in the argument list:
  296. </p>
  297. <pre>// INVALID: uintptr cannot be stored in variable
  298. // before implicit conversion back to Pointer during system call.
  299. u := uintptr(unsafe.Pointer(p))
  300. syscall.Syscall(SYS_READ, uintptr(fd), u, uintptr(n))
  301. </pre>
  302. <p>
  303. (5) Conversion of the result of reflect.Value.Pointer or reflect.Value.UnsafeAddr
  304. from uintptr to Pointer.
  305. </p>
  306. <p>
  307. Package reflect&#39;s Value methods named Pointer and UnsafeAddr return type uintptr
  308. instead of unsafe.Pointer to keep callers from changing the result to an arbitrary
  309. type without first importing &#34;unsafe&#34;. However, this means that the result is
  310. fragile and must be converted to Pointer immediately after making the call,
  311. in the same expression:
  312. </p>
  313. <pre>p := (*int)(unsafe.Pointer(reflect.ValueOf(new(int)).Pointer()))
  314. </pre>
  315. <p>
  316. As in the cases above, it is invalid to store the result before the conversion:
  317. </p>
  318. <pre>// INVALID: uintptr cannot be stored in variable
  319. // before conversion back to Pointer.
  320. u := reflect.ValueOf(new(int)).Pointer()
  321. p := (*int)(unsafe.Pointer(u))
  322. </pre>
  323. <p>
  324. (6) Conversion of a reflect.SliceHeader or reflect.StringHeader Data field to or from Pointer.
  325. </p>
  326. <p>
  327. As in the previous case, the reflect data structures SliceHeader and StringHeader
  328. declare the field Data as a uintptr to keep callers from changing the result to
  329. an arbitrary type without first importing &#34;unsafe&#34;. However, this means that
  330. SliceHeader and StringHeader are only valid when interpreting the content
  331. of an actual slice or string value.
  332. </p>
  333. <pre>var s string
  334. hdr := (*reflect.StringHeader)(unsafe.Pointer(&amp;s)) // case 1
  335. hdr.Data = uintptr(unsafe.Pointer(p)) // case 6 (this case)
  336. hdr.Len = uintptr(n)
  337. </pre>
  338. <p>
  339. In this usage hdr.Data is really an alternate way to refer to the underlying
  340. pointer in the slice header, not a uintptr variable itself.
  341. </p>
  342. <p>
  343. In general, reflect.SliceHeader and reflect.StringHeader should be used
  344. only as *reflect.SliceHeader and *reflect.StringHeader pointing at actual
  345. slices or strings, never as plain structs.
  346. A program should not declare or allocate variables of these struct types.
  347. </p>
  348. <pre>// INVALID: a directly-declared header will not hold Data as a reference.
  349. var hdr reflect.StringHeader
  350. hdr.Data = uintptr(unsafe.Pointer(p))
  351. hdr.Len = uintptr(n)
  352. s := *(*string)(unsafe.Pointer(&amp;hdr)) // p possibly already lost
  353. </pre>
  354. <div id="footer">
  355. Build version go1.6.<br>
  356. Except as <a href="https://developers.google.com/site-policies#restrictions">noted</a>,
  357. the content of this page is licensed under the
  358. Creative Commons Attribution 3.0 License,
  359. and code is licensed under a <a href="http://localhost:6060/LICENSE">BSD license</a>.<br>
  360. <a href="http://localhost:6060/doc/tos.html">Terms of Service</a> |
  361. <a href="http://www.google.com/intl/en/policies/privacy/">Privacy Policy</a>
  362. </div>
  363. </div><!-- .container -->
  364. </div><!-- #page -->
  365. <!-- TODO(adonovan): load these from <head> using "defer" attribute? -->
  366. <script type="text/javascript" src="../../lib/godoc/jquery.js"></script>
  367. <script type="text/javascript" src="../../lib/godoc/jquery.treeview.js"></script>
  368. <script type="text/javascript" src="../../lib/godoc/jquery.treeview.edit.js"></script>
  369. <script type="text/javascript" src="../../lib/godoc/godocs.js"></script>
  370. </body>
  371. </html>