Debian Codegraph @

gcc/d/dmd/safe.d

raw
1 /**
2 * Checks whether member access or array casting is allowed in `@safe` code.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/function.html#function-safety, Function Safety)
5 *
6 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
7 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
8 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
9 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/safe.d, _safe.d)
10 * Documentation: https://dlang.org/phobos/dmd_safe.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/safe.d
12 */
13
14 module dmd.safe;
15
16 import core.stdc.stdio;
17
18 import dmd.aggregate;
19 import dmd.astenums;
20 import dmd.common.outbuffer;
21 import dmd.dcast : implicitConvTo;
22 import dmd.dclass;
23 import dmd.declaration;
24 import dmd.dscope;
25 import dmd.dsymbol;
26 import dmd.dsymbolsem : determineSize;
27 import dmd.errors;
28 import dmd.expression;
29 import dmd.func;
30 import dmd.funcsem : isRootTraitsCompilesScope;
31 import dmd.globals : FeatureState, global;
32 import dmd.id;
33 import dmd.identifier;
34 import dmd.location;
35 import dmd.mtype;
36 import dmd.rootobject;
37 import dmd.root.string : fTuple;
38 import dmd.target;
39 import dmd.tokens;
40 import dmd.typesem : hasPointers, arrayOf, size;
41
42 /*************************************************************
43 * Check for unsafe access in @safe code:
44 * 1. read overlapped pointers
45 * 2. write misaligned pointers
46 * 3. write overlapped storage classes
47 * Print error if unsafe.
48 * Params:
49 * sc = scope
50 * e = expression to check
51 * readonly = if access is read-only
52 * printmsg = print error message if true
53 * Returns:
54 * true if error
55 */
56
57 bool checkUnsafeAccess(Scope* sc, Expression e, bool readonly, bool printmsg)
58 {
59 //printf("checkUnsafeAccess(e: '%s', readonly: %d, printmsg: %d)\n", e.toChars(), readonly, printmsg);
60 if (e.op != EXP.dotVariable)
61 return false;
62 auto dve = cast(DotVarExp)e;
63 VarDeclaration v = dve.var.isVarDeclaration();
64 if (!v)
65 return false;
66 if (!sc.func)
67 return false;
68 auto ad = v.isMember2();
69 if (!ad)
70 return false;
71
72 if (v.isSystem())
73 {
74 if (sc.setUnsafePreview(sc.previews.systemVariables, !printmsg, e.loc,
75 "accessing `@system` field `%s.%s`", ad, v))
76 return true;
77 }
78
79 // This branch shouldn't be here, but unfortunately calling `ad.determineSize`
80 // breaks code with circular reference errors. Specifically, test23589.d fails
81 if (ad.sizeok != Sizeok.done && !sc.func.isSafeBypassingInference())
82 return false;
83
84 // needed to set v.overlapped and v.overlapUnsafe
85 if (ad.sizeok != Sizeok.done)
86 ad.determineSize(ad.loc);
87
88 import dmd.globals : FeatureState;
89 const hasPointers = v.type.hasPointers();
90 if (hasPointers)
91 {
92 if (v.overlapped)
93 {
94 if (sc.func.isSafeBypassingInference() && sc.setUnsafe(!printmsg, e.loc,
95 "accessing overlapped field `%s.%s` with pointers", ad, v))
96 {
97 return true;
98 }
99 else
100 {
101 // @@@DEPRECATED_2.116@@@
102 // https://issues.dlang.org/show_bug.cgi?id=20655
103 // Inferring `@system` because of union access breaks code,
104 // so make it a deprecation safety violation as of 2.106
105 // To turn into an error, remove `isSafeBypassingInference` check in the
106 // above if statement and remove the else branch
107 sc.setUnsafePreview(FeatureState.default_, !printmsg, e.loc,
108 "accessing overlapped field `%s.%s` with pointers", ad, v);
109 }
110 }
111 }
112
113 if (v.type.hasInvariant())
114 {
115 if (v.overlapped)
116 {
117 if (sc.setUnsafe(!printmsg, e.loc,
118 "accessing overlapped field `%s.%s` with a structs invariant",
119 ad, v))
120 return true;
121 }
122 }
123
124 // @@@DEPRECATED_2.119@@@
125 // https://issues.dlang.org/show_bug.cgi?id=24477
126 // Should probably be turned into an error in a new edition
127 if (v.type.hasUnsafeBitpatterns() && v.overlapped && sc.setUnsafePreview(
128 FeatureState.default_, !printmsg, e.loc,
129 "accessing overlapped field `%s.%s` with unsafe bit patterns", ad, v)
130 )
131 {
132 return true;
133 }
134
135 if (readonly || !e.type.isMutable())
136 return false;
137
138 if (hasPointers && v.type.toBasetype().ty != Tstruct)
139 {
140 if ((!ad.type.alignment.isDefault() && ad.type.alignment.get() < target.ptrsize) ||
141 (v.offset & (target.ptrsize - 1)))
142 {
143 if (sc.setUnsafe(!printmsg, e.loc,
144 "modifying misaligned pointers through field `%s.%s`", ad, v))
145 return true;
146 }
147 }
148
149 if (v.overlapUnsafe)
150 {
151 if (sc.setUnsafe(!printmsg, e.loc,
152 "modifying field `%s.%s` which overlaps with fields with other storage classes",
153 ad, v))
154 {
155 return true;
156 }
157 }
158
159 return false;
160 }
161
162
163 /**********************************************
164 * Determine if it is @safe to cast e from tfrom to tto.
165 * Params:
166 * e = expression to be cast
167 * tfrom = type of e
168 * tto = type to cast e to
169 * msg = reason why cast is unsafe or deprecated
170 * Returns:
171 * true if @safe or deprecated
172 */
173 bool isSafeCast(Expression e, Type tfrom, Type tto, ref string msg)
174 {
175 // Implicit conversions are always safe
176 if (tfrom.implicitConvTo(tto))
177 return true;
178
179 if (!tto.hasPointers())
180 return true;
181
182 auto tfromb = tfrom.toBasetype();
183 auto ttob = tto.toBasetype();
184
185 // Casting to void* is always safe, https://github.com/dlang/dmd/issues/20514
186 if (ttob.isTypePointer() && ttob.nextOf().toBasetype().ty == Tvoid)
187 return true;
188
189 if (ttob.ty == Tclass && tfromb.ty == Tclass)
190 {
191 ClassDeclaration cdfrom = tfromb.isClassHandle();
192 ClassDeclaration cdto = ttob.isClassHandle();
193 int offset;
194
195 if (cdfrom == cdto)
196 goto Lsame;
197
198 if (!cdfrom.isBaseOf(cdto, &offset) &&
199 !((cdfrom.isInterfaceDeclaration() || cdto.isInterfaceDeclaration())
200 && cdfrom.classKind == ClassKind.d && cdto.classKind == ClassKind.d))
201 {
202 msg = "Source object type is incompatible with target type";
203 return false;
204 }
205
206 // no RTTI
207 if (cdfrom.isCPPinterface() || cdto.isCPPinterface())
208 {
209 msg = "No dynamic type information for extern(C++) classes";
210 return false;
211 }
212 if (cdfrom.classKind == ClassKind.cpp || cdto.classKind == ClassKind.cpp)
213 msg = "No dynamic type information for extern(C++) classes";
214
215 Lsame:
216 if (!MODimplicitConv(tfromb.mod, ttob.mod))
217 {
218 msg = "Incompatible type qualifier";
219 return false;
220 }
221 return true;
222 }
223
224 if (ttob.ty == Tarray && tfromb.ty == Tsarray) // https://issues.dlang.org/show_bug.cgi?id=12502
225 tfromb = tfromb.nextOf().arrayOf();
226
227 if (ttob.ty == Tarray && tfromb.ty == Tarray ||
228 ttob.ty == Tpointer && tfromb.ty == Tpointer)
229 {
230 Type ttobn = ttob.nextOf().toBasetype();
231 Type tfromn = tfromb.nextOf().toBasetype();
232
233 /* From void[] to anything mutable is unsafe because:
234 * int*[] api;
235 * void[] av = api;
236 * int[] ai = cast(int[]) av;
237 * ai[0] = 7;
238 * *api[0] crash!
239 */
240 if (tfromn.ty == Tvoid && ttobn.isMutable())
241 {
242 if (ttob.ty == Tarray && e.op == EXP.arrayLiteral)
243 return true;
244 msg = "`void` data may contain pointers and target element type is mutable";
245 return false;
246 }
247
248 // If the struct is opaque we don't know about the struct members then the cast becomes unsafe
249 if (ttobn.ty == Tstruct && !(cast(TypeStruct)ttobn).sym.members)
250 {
251 msg = "Target element type is opaque";
252 return false;
253 }
254 if (tfromn.ty == Tstruct && !(cast(TypeStruct)tfromn).sym.members)
255 {
256 msg = "Source element type is opaque";
257 return false;
258 }
259
260 if (e.op != EXP.arrayLiteral)
261 {
262 // For bool, only 0 and 1 are safe values
263 // Runtime array cast reinterprets data
264 if (ttobn.ty == Tbool && tfromn.ty != Tbool)
265 msg = "Source element may have bytes which are not 0 or 1";
266 else if (ttobn.hasUnsafeBitpatterns())
267 msg = "Target element type has unsafe bit patterns";
268
269 // Can't alias a bool pointer with a non-bool pointer
270 if (ttobn.ty != Tbool && tfromn.ty == Tbool && ttobn.isMutable())
271 msg = "Target element could be assigned a byte which is not 0 or 1";
272 else if (tfromn.hasUnsafeBitpatterns() && ttobn.isMutable())
273 msg = "Source element type has unsafe bit patterns and target element type is mutable";
274 }
275
276 const frompointers = tfromn.hasPointers();
277 const topointers = ttobn.hasPointers();
278
279 if (frompointers && !topointers && ttobn.isMutable())
280 {
281 msg = "Target element type is mutable and source element type contains a pointer";
282 return false;
283 }
284
285 if (!frompointers && topointers)
286 {
287 msg = "Target element type contains a pointer";
288 return false;
289 }
290
291 if (!topointers &&
292 ttobn.ty != Tfunction && tfromn.ty != Tfunction &&
293 (ttob.ty == Tarray || ttobn.size() <= tfromn.size()) &&
294 MODimplicitConv(tfromn.mod, ttobn.mod))
295 {
296 return true;
297 }
298 }
299 msg = "Source type is incompatible with target type containing a pointer";
300 return false;
301 }
302
303 /*************************************************
304 * Check for unsafe use of `.ptr` or `.funcptr`
305 * Params:
306 * sc = context
307 * e = expression for error messages
308 * id = `ptr` or `funcptr`
309 * flag = DotExpFlag
310 * Returns:
311 * true if error
312 */
313 bool checkUnsafeDotExp(Scope* sc, Expression e, Identifier id, int flag)
314 {
315 if (!(flag & DotExpFlag.noDeref)) // this use is attempting a dereference
316 {
317 if (id == Id.ptr)
318 return sc.setUnsafe(false, e.loc, "using `%s.ptr` (instead of `&%s[0])`", e, e);
319 return sc.setUnsafe(false, e.loc, "using `%s.%s`", e, id);
320 }
321 return false;
322 }
323
324 /**************************************
325 * Safer D adds safety checks to functions with the default
326 * trust setting.
327 */
328 bool isSaferD(FuncDeclaration fd)
329 {
330 return fd.type.toTypeFunction().trust == TRUST.default_ && fd.saferD;
331 }
332
333 bool isSafe(FuncDeclaration fd)
334 {
335 if (fd.safetyInprocess)
336 setFunctionToUnsafe(fd);
337 return fd.type.toTypeFunction().trust == TRUST.safe;
338 }
339
340 extern (D) bool isSafeBypassingInference(FuncDeclaration fd)
341 {
342 return !(fd.safetyInprocess) && fd.isSafe();
343 }
344
345 bool isTrusted(FuncDeclaration fd)
346 {
347 if (fd.safetyInprocess)
348 setFunctionToUnsafe(fd);
349 return fd.type.toTypeFunction().trust == TRUST.trusted;
350 }
351
352 /*****************************************************
353 * Report safety violation for function `fd`, or squirrel away
354 * error message in fd.safetyViolation if needed later.
355 * Call when `fd` was just inferred to be @system OR
356 * `fd` was @safe and an tried something unsafe.
357 * Params:
358 * fd = function we're gonna rat on
359 * gag = suppress error message (used in escape.d)
360 * loc = location of error
361 * format = printf-style format string
362 * args = arguments for %s format specifier
363 */
364 extern (D) void reportSafeError(FuncDeclaration fd, bool gag, Loc loc,
365 const(char)* format, RootObject[] args...)
366 {
367 if (fd.type.toTypeFunction().trust == TRUST.system) // function was just inferred to be @system
368 {
369 if (format)
370 {
371 fd.safetyViolation = new AttributeViolation(loc, format, args);
372 }
373 else if (args.length > 0)
374 {
375 if (FuncDeclaration fd2 = (cast(Dsymbol) args[0]).isFuncDeclaration())
376 {
377 fd.safetyViolation = new AttributeViolation(loc, fd2); // call to non-@nogc function
378 }
379 }
380 }
381 else if (fd.isSafe() || fd.isSaferD())
382 {
383 if (!gag && format)
384 {
385 OutBuffer buf;
386 buf.writestring(AttributeViolation(loc, format, args).action);
387 if (fd.isSafe())
388 buf.writestring(" is not allowed in a `@safe` function");
389 else
390 {
391 version (IN_GCC)
392 buf.writestring(" is not allowed in a function with default safety with `-fpreview=safer`");
393 else
394 buf.writestring(" is not allowed in a function with default safety with `-preview=safer`");
395 }
396 .error(loc, "%s", buf.extractChars());
397 }
398 }
399 }
400
401
402 /**********************************************
403 * Function is doing something unsafe. If inference
404 * is in process, commit the function to be @system.
405 * Params:
406 * fd = the naughty function
407 * Returns:
408 * true if this is a safe function and so an error OR is inferred to be @system,
409 * false otherwise.
410 */
411 extern (D) bool setFunctionToUnsafe(FuncDeclaration fd)
412 {
413 if (fd.safetyInprocess)
414 {
415 fd.safetyInprocess = false;
416 fd.type.toTypeFunction().trust = TRUST.system;
417
418 if (fd.fes)
419 setFunctionToUnsafe(fd.fes.func);
420 return true;
421 }
422 else if (fd.isSafe() || fd.isSaferD())
423 return true;
424 return false;
425 }
426
427
428 /**************************************
429 * The function is calling `@system` function `f`, so mark it as unsafe.
430 *
431 * Params:
432 * fd = caller
433 * f = function being called (needed for diagnostic of inferred functions)
434 * Returns: whether there's a safe error
435 */
436 extern (D) bool setUnsafeCall(FuncDeclaration fd, FuncDeclaration f)
437 {
438 if (setFunctionToUnsafe(fd))
439 {
440 reportSafeError(fd, false, f.loc, null, f, null);
441 return fd.isSafe();
442 }
443 return false;
444 }
445
446 /**************************************
447 * A statement / expression in this scope is not `@safe`,
448 * so mark the enclosing function as `@system`
449 *
450 * Params:
451 * sc = scope that the unsafe statement / expression is in
452 * gag = surpress error message (used in escape.d)
453 * loc = location of error
454 * format = printf-style format string
455 * args = arguments for format string
456 * Returns: whether there is a safe error
457 */
458 bool setUnsafe(Scope* sc, bool gag, Loc loc, const(char)* format, RootObject[] args...)
459 {
460 if (sc.intypeof)
461 return false; // typeof(cast(int*)0) is safe
462
463 if (sc.debug_) // debug {} scopes are permissive
464 return false;
465
466 if (!sc.func)
467 {
468 if (sc.varDecl)
469 {
470 if (sc.varDecl.storage_class & STC.safe)
471 {
472 string action = AttributeViolation(loc, format, args).action;
473 .error(loc, "%.*s can't initialize `@safe` variable `%s`", action.fTuple.expand, sc.varDecl.toChars());
474 return true;
475 }
476 else if (!(sc.varDecl.storage_class & STC.trusted))
477 {
478 sc.varDecl.storage_class |= STC.system;
479 sc.varDecl.systemInferred = true;
480 }
481 }
482 return false;
483 }
484
485
486 if (isRootTraitsCompilesScope(sc)) // __traits(compiles, x)
487 {
488 if (sc.func.isSafeBypassingInference())
489 {
490 // Message wil be gagged, but still call error() to update global.errors and for
491 // -verrors=spec
492 string action = AttributeViolation(loc, format, args).action;
493 .error(loc, "%.*s is not allowed in a `@safe` function", action.fTuple.expand);
494 return true;
495 }
496 return false;
497 }
498
499 if (setFunctionToUnsafe(sc.func))
500 {
501 if (format || args.length > 0)
502 {
503 reportSafeError(sc.func, gag, loc, format, args);
504 }
505 return sc.func.isSafe(); // it is only an error if in an @safe function
506 }
507 return false;
508 }
509
510 /***************************************
511 * Like `setUnsafe`, but for safety errors still behind preview switches
512 *
513 * Given a `FeatureState fs`, for example dip1000 / dip25 / systemVariables,
514 * the behavior changes based on the setting:
515 *
516 * - In case of `-revert=fs`, it does nothing.
517 * - In case of `-preview=fs`, it's the same as `setUnsafe`
518 * - By default, print a deprecation in `@safe` functions, or store an attribute violation in inferred functions.
519 *
520 * Params:
521 * sc = used to find affected function/variable, and for checking whether we are in a deprecated / speculative scope
522 * fs = feature state from the preview flag
523 * gag = surpress error message
524 * loc = location of error
525 * format = printf-style format string
526 * args = arguments for format string
527 * Returns: whether an actual safe error (not deprecation) occured
528 */
529 bool setUnsafePreview(Scope* sc, FeatureState fs, bool gag, Loc loc, const(char)* format, RootObject[] args...)
530 {
531 //printf("setUnsafePreview() fs:%d %s\n", fs, fmt);
532 assert(format);
533 with (FeatureState) final switch (fs)
534 {
535 case disabled:
536 return false;
537
538 case enabled:
539 return sc.setUnsafe(gag, loc, format, args);
540
541 case default_:
542 if (!sc.func)
543 return false;
544 if (sc.func.isSafeBypassingInference())
545 {
546 if (!gag && !sc.isDeprecated())
547 {
548 string action = AttributeViolation(loc, format, args).action;
549 deprecation(loc, "%.*s will become `@system` in a future release", action.fTuple.expand);
550 }
551 }
552 else if (!sc.func.safetyViolation)
553 {
554 import dmd.func : AttributeViolation;
555 sc.func.safetyViolation = new AttributeViolation(loc, format, args);
556 }
557 return false;
558 }
559 }