]> git.lizzy.rs Git - rust.git/blob - src/libstd/rt/borrowck.rs
Add ToCStr method .with_c_str()
[rust.git] / src / libstd / rt / borrowck.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use c_str::ToCStr;
12 use cast::transmute;
13 use libc::{c_char, size_t, STDERR_FILENO};
14 use io;
15 use io::{Writer, WriterUtil};
16 use option::{Option, None, Some};
17 use uint;
18 use str;
19 use str::{OwnedStr, StrSlice};
20 use sys;
21 use unstable::raw;
22 use vec::ImmutableVector;
23
24 pub static FROZEN_BIT: uint = 1 << (uint::bits - 1);
25 pub static MUT_BIT: uint = 1 << (uint::bits - 2);
26 static ALL_BITS: uint = FROZEN_BIT | MUT_BIT;
27
28 #[deriving(Eq)]
29 struct BorrowRecord {
30     box: *mut raw::Box<()>,
31     file: *c_char,
32     line: size_t
33 }
34
35 fn try_take_task_borrow_list() -> Option<~[BorrowRecord]> {
36     // XXX
37     None
38 }
39
40 fn swap_task_borrow_list(_f: &fn(~[BorrowRecord]) -> ~[BorrowRecord]) {
41     // XXX
42 }
43
44 pub unsafe fn clear_task_borrow_list() {
45     // pub because it is used by the box annihilator.
46     let _ = try_take_task_borrow_list();
47 }
48
49 unsafe fn fail_borrowed(box: *mut raw::Box<()>, file: *c_char, line: size_t) {
50     debug_borrow("fail_borrowed: ", box, 0, 0, file, line);
51
52     match try_take_task_borrow_list() {
53         None => { // not recording borrows
54             let msg = "borrowed";
55             do msg.with_c_str |msg_p| {
56                 sys::begin_unwind_(msg_p, file, line);
57             }
58         }
59         Some(borrow_list) => { // recording borrows
60             let mut msg = ~"borrowed";
61             let mut sep = " at ";
62             for entry in borrow_list.rev_iter() {
63                 if entry.box == box {
64                     msg.push_str(sep);
65                     let filename = str::raw::from_c_str(entry.file);
66                     msg.push_str(filename);
67                     msg.push_str(fmt!(":%u", entry.line as uint));
68                     sep = " and at ";
69                 }
70             }
71             do msg.with_c_str |msg_p| {
72                 sys::begin_unwind_(msg_p, file, line)
73             }
74         }
75     }
76 }
77
78 /// Because this code is so perf. sensitive, use a static constant so that
79 /// debug printouts are compiled out most of the time.
80 static ENABLE_DEBUG: bool = false;
81
82 #[inline]
83 unsafe fn debug_borrow<T>(tag: &'static str,
84                           p: *const T,
85                           old_bits: uint,
86                           new_bits: uint,
87                           filename: *c_char,
88                           line: size_t) {
89     //! A useful debugging function that prints a pointer + tag + newline
90     //! without allocating memory.
91
92     // XXX
93     if false {
94         debug_borrow_slow(tag, p, old_bits, new_bits, filename, line);
95     }
96
97     unsafe fn debug_borrow_slow<T>(tag: &'static str,
98                                    p: *const T,
99                                    old_bits: uint,
100                                    new_bits: uint,
101                                    filename: *c_char,
102                                    line: size_t) {
103         let dbg = STDERR_FILENO as io::fd_t;
104         dbg.write_str(tag);
105         dbg.write_hex(p as uint);
106         dbg.write_str(" ");
107         dbg.write_hex(old_bits);
108         dbg.write_str(" ");
109         dbg.write_hex(new_bits);
110         dbg.write_str(" ");
111         dbg.write_cstr(filename);
112         dbg.write_str(":");
113         dbg.write_hex(line as uint);
114         dbg.write_str("\n");
115     }
116 }
117
118 trait DebugPrints {
119     fn write_hex(&self, val: uint);
120     unsafe fn write_cstr(&self, str: *c_char);
121 }
122
123 impl DebugPrints for io::fd_t {
124     fn write_hex(&self, mut i: uint) {
125         let letters = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
126                        '9', 'a', 'b', 'c', 'd', 'e', 'f'];
127         static UINT_NIBBLES: uint = ::uint::bytes << 1;
128         let mut buffer = [0_u8, ..UINT_NIBBLES+1];
129         let mut c = UINT_NIBBLES;
130         while c > 0 {
131             c -= 1;
132             buffer[c] = letters[i & 0xF] as u8;
133             i >>= 4;
134         }
135         self.write(buffer.slice(0, UINT_NIBBLES));
136     }
137
138     unsafe fn write_cstr(&self, p: *c_char) {
139         use libc::strlen;
140         use vec;
141
142         let len = strlen(p);
143         let p: *u8 = transmute(p);
144         do vec::raw::buf_as_slice(p, len as uint) |s| {
145             self.write(s);
146         }
147     }
148 }
149
150 #[inline]
151 pub unsafe fn borrow_as_imm(a: *u8, file: *c_char, line: size_t) -> uint {
152     let a = a as *mut raw::Box<()>;
153     let old_ref_count = (*a).ref_count;
154     let new_ref_count = old_ref_count | FROZEN_BIT;
155
156     debug_borrow("borrow_as_imm:", a, old_ref_count, new_ref_count, file, line);
157
158     if (old_ref_count & MUT_BIT) != 0 {
159         fail_borrowed(a, file, line);
160     }
161
162     (*a).ref_count = new_ref_count;
163
164     old_ref_count
165 }
166
167 #[inline]
168 pub unsafe fn borrow_as_mut(a: *u8, file: *c_char, line: size_t) -> uint {
169     let a = a as *mut raw::Box<()>;
170     let old_ref_count = (*a).ref_count;
171     let new_ref_count = old_ref_count | MUT_BIT | FROZEN_BIT;
172
173     debug_borrow("borrow_as_mut:", a, old_ref_count, new_ref_count, file, line);
174
175     if (old_ref_count & (MUT_BIT|FROZEN_BIT)) != 0 {
176         fail_borrowed(a, file, line);
177     }
178
179     (*a).ref_count = new_ref_count;
180
181     old_ref_count
182 }
183
184 pub unsafe fn record_borrow(a: *u8, old_ref_count: uint,
185                             file: *c_char, line: size_t) {
186     if (old_ref_count & ALL_BITS) == 0 {
187         // was not borrowed before
188         let a = a as *mut raw::Box<()>;
189         debug_borrow("record_borrow:", a, old_ref_count, 0, file, line);
190         do swap_task_borrow_list |borrow_list| {
191             let mut borrow_list = borrow_list;
192             borrow_list.push(BorrowRecord {box: a, file: file, line: line});
193             borrow_list
194         }
195     }
196 }
197
198 pub unsafe fn unrecord_borrow(a: *u8, old_ref_count: uint,
199                               file: *c_char, line: size_t) {
200     if (old_ref_count & ALL_BITS) == 0 {
201         // was not borrowed before, so we should find the record at
202         // the end of the list
203         let a = a as *mut raw::Box<()>;
204         debug_borrow("unrecord_borrow:", a, old_ref_count, 0, file, line);
205         do swap_task_borrow_list |borrow_list| {
206             let mut borrow_list = borrow_list;
207             assert!(!borrow_list.is_empty());
208             let br = borrow_list.pop();
209             if br.box != a || br.file != file || br.line != line {
210                 let err = fmt!("wrong borrow found, br=%?", br);
211                 do err.with_c_str |msg_p| {
212                     sys::begin_unwind_(msg_p, file, line)
213                 }
214             }
215             borrow_list
216         }
217     }
218 }
219
220 #[inline]
221 pub unsafe fn return_to_mut(a: *u8, orig_ref_count: uint,
222                             file: *c_char, line: size_t) {
223     // Sometimes the box is null, if it is conditionally frozen.
224     // See e.g. #4904.
225     if !a.is_null() {
226         let a = a as *mut raw::Box<()>;
227         let old_ref_count = (*a).ref_count;
228         let new_ref_count =
229             (old_ref_count & !ALL_BITS) | (orig_ref_count & ALL_BITS);
230
231         debug_borrow("return_to_mut:",
232                      a, old_ref_count, new_ref_count, file, line);
233
234         (*a).ref_count = new_ref_count;
235     }
236 }
237
238 #[inline]
239 pub unsafe fn check_not_borrowed(a: *u8,
240                                  file: *c_char,
241                                  line: size_t) {
242     let a = a as *mut raw::Box<()>;
243     let ref_count = (*a).ref_count;
244     debug_borrow("check_not_borrowed:", a, ref_count, 0, file, line);
245     if (ref_count & FROZEN_BIT) != 0 {
246         fail_borrowed(a, file, line);
247     }
248 }