File: ptr.bs

package info (click to toggle)
storm-lang 0.7.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 51,836 kB
  • sloc: ansic: 261,420; cpp: 138,870; sh: 14,877; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (611 lines) | stat: -rw-r--r-- 16,258 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
use core:lang;
use core:asm;
use lang:asm;
use lang:bs:macro;

// Pointers.
Ptr : generate(params) {
	generatePtr(params, "Ptr", false, false, false);
}

ConstPtr : generate(params) {
	generatePtr(params, "ConstPtr", true, false, false);
}

// References.
Ref : generate(params) {
	generatePtr(params, "Ref", false, true, false);
}

ConstRef : generate(params) {
	generatePtr(params, "ConstRef", true, true, false);
}

// RValue-ref.
RRef : generate(params) {
	generatePtr(params, "RRef", false, true, true);
}

ConstRRef : generate(params) {
	generatePtr(params, "ConstRRef", true, true, true);
}

// Create a type.
private Named? generatePtr(Array<Value> params, Str name, Bool isConst, Bool isRef, Bool rvalRef) {
	// Only one parameter.
	if (params.count != 1)
		return null;

	// It must be a value-type (this includes other Ptr classes).
	var par = params[0];
	if (!par.isValue)
		return null;

	PtrType(par.asRef(false), name, isConst, isRef, rvalRef);
}

/**
 * A pointer- or reference type in the C++ implementation.
 *
 * Represented as a pointer to the start of the object followed by a an integer offset. This lets us
 * check if a pointer dereference would be in range, and makes the GC happy.
 *
 * Can also act as a reference.
 */
class PtrType extends Type {
	init(Value inside, Str name, Bool isConst, Bool isRef, Bool rvalRef) {
		init(name, [inside], TypeFlags:typeValue) { isRef = isRef; rvalRef = rvalRef; isConst = isConst; }
	}

	// Is this a reference?
	Bool isRef;

	// R-value reference?
	Bool rvalRef;

	// Is the thing we're pointing to 'const'?
	Bool isConst;

	// Is this a pointer?
	Bool isPtr() {
		!isRef & !rvalRef;
	}

	// Get the type inside.
	Type? inside() {
		params[0].type;
	}

	// Load members.
	Bool loadAll() : override {
		// Note: We make assumptions regarding the type in generated code. Don't alter the order of
		// these!
		add(MemberVar("base", Value(named{core:unsafe:RawPtr}), this));
		add(MemberVar("offset", Value(named{core:Nat}), this));

		// Default ctors.
		// add(TypeDefaultCtor(this));
		add(TypeCopyCtor(this));
		add(TypeAssign(this));

		Value val(this, false);
		Value ref(this, true);
		Value int(named{Int});

		// Version of the default ctor that writes a zero to our struct, so that we can see the
		// initialization.
		addFn(Value(), "__init", [ref], defCtor());

		// Compare pointers.
		addFn(named{Bool}, "==", [ref, ref], named{helpers:pointerEq<unsafe:RawPtr, unsafe:RawPtr>});
		addFn(named{Bool}, "!=", [ref, ref], named{helpers:pointerNeq<unsafe:RawPtr, unsafe:RawPtr>});
		addFn(named{Bool}, "<", [ref, ref], named{helpers:pointerLt<unsafe:RawPtr, unsafe:RawPtr>});
		addFn(named{Bool}, ">", [ref, ref], named{helpers:pointerGt<unsafe:RawPtr, unsafe:RawPtr>});
		addFn(named{Bool}, "<=", [ref, ref], named{helpers:pointerLte<unsafe:RawPtr, unsafe:RawPtr>});
		addFn(named{Bool}, ">=", [ref, ref], named{helpers:pointerGte<unsafe:RawPtr, unsafe:RawPtr>});

		// Pointer arithmetic.
		if (t = inside) {
			Size sz = t.size.aligned;
			addFn(val, "+", [ref, int], ptrAdd(Offset(sz)));
			addFn(val, "-", [ref, int], ptrAdd(Offset(sz)));
			addFn(ref, "+=", [ref, int], ptrInc(Offset(sz)));
			addFn(ref, "-=", [ref, int], ptrInc(-Offset(sz)));
			addFn(ref, "++*", [ref], ptrPrefixInc(Offset(sz)));
			addFn(val, "*++", [ref], ptrPostfixInc(Offset(sz)));
			addFn(ref, "--*", [ref], ptrPrefixInc(-Offset(sz)));
			addFn(val, "*--", [ref], ptrPostfixInc(-Offset(sz)));
			addFn(int, "-", [ref, ref], ptrDiff(Offset(sz)));
		}

		// Allocate arrays from Storm. Useful when implementing the standard library. These will be marked as heap allocations.
		if (type = inside()) {
			Function f(val, "allocArray", [Value(named{Nat})]);
			f.setCode(DynamicCode(allocArrayFn(type)));
			f.make(FnFlags:static);
			add(f);

			Function d(Value(), "deepCopy", [thisPtr(this), named{CloneEnv}]);
			d.setCode(DynamicCode(deepCopyFn(type)));
			add(d);
		}


		// TODO: Add suitable members!

		super:loadAll();
	}

	// Add a function ptr.
	private void addFn(Value result, Str name, Value[] params, Function fn) {
		Function f(result, name, params);
		f.setCode(DelegatedCode(fn.ref));
		add(f);
	}

	private void addFn(Value result, Str name, Value[] params, Listing l) {
		Function f(result, name, params);
		f.setCode(DynamicCode(l));
		add(f);
	}

	// Generate the default ctor. We want to write to the int so that it registers as an
	// initialization.
	private Listing defCtor() : static {
		Listing l(true, ptrDesc);
		Var me = l.createParam(ptrDesc);
		l << prolog();
		l << fnParam(ptrDesc, me);
		l << fnCall(named{core:unsafe:RawPtr:__init<core:unsafe:RawPtr>}.ref, true);
		l << mov(ptrA, me);
		l << mov(intRel(ptrA, Offset(sPtr)), intConst(0));
		l << fnRet(ptrA);
		l;
	}

	// Generate += / -= operator.
	private Listing ptrInc(Offset offset) : static {
		Listing l(true, ptrDesc);

		Var me = l.createParam(ptrDesc);
		Var delta = l.createParam(intDesc);

		l << prolog();
		l << mov(ptrA, me);
		l << mov(ebx, delta);
		l << mul(ebx, intConst(offset));
		l << add(intRel(ptrA, Offset(sPtr)), ebx);
		l << fnRet(ptrA);

		l;
	}

	// Generate + and - operator. (Note: We don't currently support 3 + <ptr>)
	private Listing ptrAdd(Offset offset) {
		Listing l(true, Value(this).desc);

		Var me = l.createParam(ptrDesc);
		Var delta = l.createParam(intDesc);
		Var res = l.createVar(l.root, size);

		l << prolog();
		l << mov(ptrA, me);
		l << mov(ptrRel(res), ptrRel(ptrA));
		l << mov(intRel(res, Offset(sPtr)), intRel(ptrA, Offset(sPtr)));

		l << mov(ebx, delta);
		l << mul(ebx, intConst(offset));
		l << add(intRel(res, Offset(sPtr)), ebx);
		l << fnRet(res);

		l;
	}

	// Prefix ++ and --.
	private Listing ptrPrefixInc(Offset offset) {
		Listing l(true, ptrDesc);

		Var me = l.createParam(ptrDesc);

		l << prolog();
		l << mov(ptrA, me);
		l << add(intRel(ptrA, Offset(sPtr)), intConst(offset));
		l << fnRet(ptrA);

		l;
	}

	// Postfix ++ and --.
	private Listing ptrPostfixInc(Offset offset) {
		Listing l(true, Value(this).desc);

		Var me = l.createParam(ptrDesc);
		Var res = l.createVar(l.root, size);

		l << prolog();
		l << mov(ptrA, me);

		// Make a copy.
		l << mov(ptrRel(res), ptrRel(ptrA));
		l << mov(intRel(res, Offset(sPtr)), intRel(ptrA, Offset(sPtr)));

		l << add(intRel(ptrA, Offset(sPtr)), intConst(offset));
		l << fnRet(res);

		l;
	}

	// Difference between two pointers.
	private Listing ptrDiff(Offset offset) : static {
		Listing l(true, intDesc);

		Var me = l.createParam(ptrDesc);
		Var o = l.createParam(ptrDesc);

		l << prolog();

		// Check if they are from the same allocation.
		l << fnParam(ptrDesc, me);
		l << fnParam(ptrDesc, o);
		l << fnCall(named{assumeSameAlloc<unsafe:RawPtr, unsafe:RawPtr>}.ref, false);

		l << mov(ptrA, me);
		l << mov(ptrB, o);
		l << mov(eax, intRel(ptrA, Offset(sPtr)));
		l << mov(ebx, intRel(ptrB, Offset(sPtr)));
		l << sub(eax, ebx);
		l << idiv(eax, intConst(offset));
		l << fnRet(eax);

		l;
	}

	private Listing allocArrayFn(Type inside) {
		Listing l(false, this.typeDesc);

		Var res = l.createVar(l.root, this.size);
		Var param = l.createParam(intDesc);

		l << prolog();

		l << ucast(ptrA, param);
		l << fnParam(ptrDesc, inside.typeRef);
		l << fnParam(ptrDesc, ptrA);
		l << fnCall(ref(BuiltIn:allocArray), false, ptrDesc, ptrA);
		l << mov(ptrRel(res, Offset()), ptrA);
		l << mov(intRel(res, Offset(sPtr)), natConst(sPtr * 2));

		Nat mask = AllocFlags:arrayAlloc.v | AllocFlags:heapAlloc.v;
		l << or(param, natConst(mask));
		l << mov(intRel(ptrA, Offset(sPtr)), param);

		l << fnRet(res);

		l;
	}

	private Listing deepCopyFn(Type inside) {
		Listing l(true, voidDesc);

		var pDesc = ptrDesc;

		Var thisParam = l.createParam(pDesc);
		Var envParam = l.createParam(pDesc);

		l << prolog();

		// Get the allocation and see if it has
		Var alloc = l.createVar(l.root, sPtr);
		l << mov(ptrA, thisParam);
		l << mov(alloc, ptrRel(ptrA));

		Label done = l.label();
		l << cmp(alloc, ptrConst(Offset()));
		l << jmp(done, CondFlag:ifEqual);

		Var copy = l.createVar(l.root, sPtr);
		l << fnParam(pDesc, envParam);
		l << fnParam(pDesc, alloc);
		l << fnCall(ref(BuiltIn:cloneEnvGet), false, pDesc, copy);

		// Did we get something?
		l << cmp(copy, ptrConst(Offset()));
		l << jmp(done, CondFlag:ifNotEqual);

		// No, we need to clone things ourselves.

		// Read the size of the allocation and allocate a copy!
		l << mov(ptrA, alloc);
		l << mov(ptrA, ptrRel(ptrA));
		l << fnParam(ptrDesc, inside.typeRef);
		l << fnParam(ptrDesc, ptrA);
		l << fnCall(ref(BuiltIn:allocArray), false, pDesc, copy);

		// Copy mask/filled.
		l << mov(ptrA, alloc);
		l << mov(ptrC, copy);
		l << mov(ptrRel(ptrC, Offset(sPtr)), ptrRel(ptrA, Offset(sPtr)));

		// Copy all elements.
		Label loopHead = l.label();
		Label loopTail = l.label();
		Var id = l.createVar(l.root, sPtr); // initialized to zero
		Var allocPos = l.createVar(l.root, sPtr);
		Var copyPos = l.createVar(l.root, sPtr);

		l << mov(ptrA, alloc);
		l << lea(allocPos, ptrRel(ptrA, Offset(sPtr * 2)));
		l << mov(ptrA, copy);
		l << lea(copyPos, ptrRel(ptrA, Offset(sPtr * 2)));

		l << loopHead;
		l << mov(ptrA, alloc);
		l << cmp(id, ptrRel(ptrA));
		l << jmp(loopTail, CondFlag:ifAboveEqual);

		if (Value(inside).isAsmType()) {
			l << mov(ptrA, allocPos);
			l << mov(ptrC, copyPos);
			var size = Value(inside).size;
			l << mov(xRel(size, ptrC), xRel(size, ptrA));
		} else if (copyCtor = inside.copyCtor) {
			l << fnParam(pDesc, copyPos);
			l << fnParam(pDesc, allocPos);
			l << fnCall(copyCtor.ref, false);
		} else {
			// Note: this is not entirely platform independent:
			Offset offset;
			Nat ptrSize = sPtr.current;
			Nat totalSize = inside.size.current;
			l << mov(ptrA, allocPos);
			l << mov(ptrC, copyPos);
			while (offset.current.nat + ptrSize <= totalSize) {
				l << mov(ptrRel(ptrC, offset), ptrRel(ptrA, offset));
				offset += sPtr;
			}
			while (offset.current.nat + 1 <= totalSize) {
				l << mov(byteRel(ptrC, offset), byteRel(ptrA, offset));
				offset += sByte;
			}
		}

		if (deepCopy = inside.deepCopyFn) {
			l << fnParam(pDesc, copyPos);
			l << fnParam(pDesc, envParam);
			l << fnCall(deepCopy.ref, true);
		}

		Size alignedSize = inside.size.aligned;
		l << add(allocPos, ptrConst(alignedSize));
		l << add(copyPos, ptrConst(alignedSize));
		l << add(id, ptrConst(1));
		l << jmp(loopHead);

		l << loopTail;
		// Save it to the CloneEnv.
		l << fnParam(pDesc, envParam);
		l << fnParam(pDesc, alloc);
		l << fnParam(pDesc, copy);
		l << fnCall(ref(BuiltIn:cloneEnvPut), false);

		// Store the updated allocation and we're done.
		l << done;
		l << mov(ptrC, thisParam);
		l << mov(ptrRel(ptrC), copy);

		l << fnRet();
		l;
	}

	// Nicer to string in error messages etc.
	void toS(StrBuf to) : override {
		if (isConst)
			to << "const ";
		to << params[0];
		if (isRef)
			to << "&";
		else if (rvalRef)
			to << "&&";
		else
			to << "*";
	}

	// Also for the identifier.
	Str identifier() : override {
		toS();
	}
}

class PtrError extends progvis:TypedError {
	init(Str type, Str msg) {
		init(type) { msg = msg; }
		saveTrace();

		// Disable tracing for this thread so that we don't trace any destructor calls.
		progvis:program:onFatalException();
	}

	Str msg;

	void message(StrBuf to) {
		to << msg;
	}
}


void assumeSameAlloc(unsafe:RawPtr a, unsafe:RawPtr b) {
	Bool same;
	asm {
		mov ptrA, a;
		mov ptrB, b;
		cmp p[ptrA], p[ptrB];
		setCond same, ifEqual;
	}

	if (!same)
		throw PtrError("undefined behavior", "Trying to compare pointers from different allocations with <, >, <=, =>, or -");
}

// Check so that a pointer is not deallocated.
void checkPtr(unsafe:RawPtr base) {
	if ((base.readFilled() & AllocFlags:sizeMask.v) == 0)
		throw PtrError("use after free", "Trying to read from memory that was freed.");
}

// Check the validity of a pointer. Assumes we want to read a maximum of 'size' bytes at wherever
// 'ptr' and 'offset' refers to.
void checkPtr(unsafe:RawPtr base, Nat offset, Nat size) {
	Nat total = base.readSize() * (base.readFilled() & AllocFlags:sizeMask.v);
	// Array header.
	if (base.isValue)
		offset -= sPtr.current * 2;
	if (offset + size > total) {
		if (total == 0)
			throw PtrError("use after free", "Trying to read from memory that was freed.");
		else
			throw PtrError("buffer overflow", "Trying to read at offset ${offset} in an allocation of size ${total}.");
	}
}

// Check that the pointer provided as 'base' and 'offset' refers to the start of an allocation, and
// that it was actually allocated on the heap.
// Returns 'false' if the pointer was a null pointer.
Bool checkDelete(unsafe:RawPtr base, Nat offset) {
	if (base.empty() & offset == 0)
		return false;

	if (offset != sPtr.current * 2)
		throw PtrError("memory", "Trying to delete memory not allocated by 'new'!");

	Nat filled = base.readFilled;

	// Malloc'd memory is marked with the MSB set.
	if ((filled & AllocFlags:heapAlloc.v) == 0)
		throw PtrError("memory", "Trying to delete memory allocated on the stack!");

	if ((filled & AllocFlags:arrayAlloc.v) != 0)
		throw PtrError("memory", "This allocation was allocated using new[], and should be freed using delete[].");

	if ((filled & AllocFlags:sizeMask.v) == 0)
		throw PtrError("use after free", "Trying to free memory that was already freed.");

	true;
}

// Check that this pointer was allocated using 'new[]' for arrays. Returns the number of elements.
Bool checkDeleteArray(unsafe:RawPtr base, Nat offset) {
	if (base.empty() & offset == 0)
		return false;

	if (offset != sPtr.current * 2)
		throw PtrError("memory", "Trying to delete memory not allocated by 'new[]'!");

	Nat filled = base.readFilled;

	// Malloc'd memory is marked with the MSB set.
	if ((filled & AllocFlags:heapAlloc.v) == 0)
		throw PtrError("memory", "Trying to delete memory allocated on the stack!");

	if ((filled & AllocFlags:sizeMask.v) == 0)
		throw PtrError("use after free", "Trying to free memory that was already freed.");

	// To make 'free' feasible, we don't complain that you need to use the plain delete if the plain new was used.
	return true;
}

// Wrap things inside a pointer or a reference.
Value wrapPtr(Value val) {
	unless (t = (named{}).find(SimplePart("Ptr", [val.asRef(false)]), Scope()) as Type)
		throw InternalError("Could not find the pointer type for ${val}");
	Value(t);
}

Value wrapConstPtr(Value val) {
	unless (t = (named{}).find(SimplePart("ConstPtr", [val.asRef(false)]), Scope()) as Type)
		throw InternalError("Could not find the pointer type for ${val}");
	Value(t);
}

Value wrapRef(Value val) {
	unless (t = (named{}).find(SimplePart("Ref", [val.asRef(false)]), Scope()) as Type)
		throw InternalError("Could not find the pointer type for ${val}");
	Value(t);
}

Value wrapConstRef(Value val) {
	unless (t = (named{}).find(SimplePart("ConstRef", [val.asRef(false)]), Scope()) as Type)
		throw InternalError("Could not find the pointer type for ${val}");
	Value(t);
}

Value wrapRRef(Value val) {
	unless (t = (named{}).find(SimplePart("RRef", [val.asRef(false)]), Scope()) as Type)
		throw InternalError("Could not find the pointer type for ${val}");
	Value(t);
}

Value wrapConstRRef(Value val) {
	unless (t = (named{}).find(SimplePart("ConstRRef", [val.asRef(false)]), Scope()) as Type)
		throw InternalError("Could not find the pointer type for ${val}");
	Value(t);
}

// Unwrap pointers and references.
Value unwrapPtr(Value val) {
	if (t = val.type as PtrType) {
		if (!t.isRef)
			return t.params[0];
	}
	val;
}

Value unwrapRef(Value val) {
	if (t = val.type as PtrType) {
		if (t.isRef)
			return t.params[0];
	}
	val;
}

Value unwrapPtrOrRef(Value val) {
	if (t = val.type as PtrType) {
		return t.params[0];
	}
	val;
}

// Is it a ptr or ref?
Bool isCppPtr(Value val) {
	if (t = val.type as PtrType) {
		return t.isPtr;
	}
	false;
}

Bool isCppRef(Value val) {
	if (t = val.type as PtrType) {
		return t.isRef;
	}
	false;
}

// Unwrap a reference. Returns 'null' if not a reference.
Type? isCppRef(Type t) {
	if (t as PtrType)
		if (t.isRef)
			return t.inside();
	null;
}

Type? isCppRRef(Type t) {
	if (t as PtrType)
		if (t.isRef & t.rvalRef)
			return t.inside();
	null;
}

Bool isCppConst(Type t) {
	if (t as PtrType)
		return t.isConst;
	false;
}