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-2023 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/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/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.dclass;
21 import dmd.declaration;
22 import dmd.dscope;
23 import dmd.expression;
24 import dmd.id;
25 import dmd.identifier;
26 import dmd.mtype;
27 import dmd.target;
28 import dmd.tokens;
29 import dmd.func : setUnsafe, setUnsafePreview;
30 
31 /*************************************************************
32  * Check for unsafe access in @safe code:
33  * 1. read overlapped pointers
34  * 2. write misaligned pointers
35  * 3. write overlapped storage classes
36  * Print error if unsafe.
37  * Params:
38  *      sc = scope
39  *      e = expression to check
40  *      readonly = if access is read-only
41  *      printmsg = print error message if true
42  * Returns:
43  *      true if error
44  */
45 
46 bool checkUnsafeAccess(Scope* sc, Expression e, bool readonly, bool printmsg)
47 {
48     //printf("checkUnsafeAccess(e: '%s', readonly: %d, printmsg: %d)\n", e.toChars(), readonly, printmsg);
49     if (e.op != EXP.dotVariable)
50         return false;
51     DotVarExp dve = cast(DotVarExp)e;
52     if (VarDeclaration v = dve.var.isVarDeclaration())
53     {
54         if (sc.intypeof || !sc.func || !sc.func.isSafeBypassingInference())
55             return false;
56         auto ad = v.isMember2();
57         if (!ad)
58             return false;
59 
60         import dmd.globals : global;
61         if (v.isSystem())
62         {
63             if (sc.setUnsafePreview(global.params.systemVariables, !printmsg, e.loc,
64                 "cannot access `@system` field `%s.%s` in `@safe` code", ad, v))
65                 return true;
66         }
67 
68         // needed to set v.overlapped and v.overlapUnsafe
69         if (ad.sizeok != Sizeok.done)
70             ad.determineSize(ad.loc);
71 
72         const hasPointers = v.type.hasPointers();
73         if (hasPointers)
74         {
75             if (v.overlapped)
76             {
77                 if (sc.setUnsafe(!printmsg, e.loc,
78                     "field `%s.%s` cannot access pointers in `@safe` code that overlap other fields", ad, v))
79                     return true;
80             }
81         }
82 
83         if (v.type.hasInvariant())
84         {
85             if (v.overlapped)
86             {
87                 if (sc.setUnsafe(!printmsg, e.loc,
88                     "field `%s.%s` cannot access structs with invariants in `@safe` code that overlap other fields",
89                     ad, v))
90                     return true;
91             }
92         }
93 
94         if (readonly || !e.type.isMutable())
95             return false;
96 
97         if (hasPointers && v.type.toBasetype().ty != Tstruct)
98         {
99             if ((!ad.type.alignment.isDefault() && ad.type.alignment.get() < target.ptrsize ||
100                  (v.offset & (target.ptrsize - 1))))
101             {
102                 if (sc.setUnsafe(!printmsg, e.loc,
103                     "field `%s.%s` cannot modify misaligned pointers in `@safe` code", ad, v))
104                     return true;
105             }
106         }
107 
108         if (v.overlapUnsafe)
109         {
110             if (sc.setUnsafe(!printmsg, e.loc,
111                 "field `%s.%s` cannot modify fields in `@safe` code that overlap fields with other storage classes",
112                 ad, v))
113             {
114                 return true;
115             }
116         }
117     }
118     return false;
119 }
120 
121 
122 /**********************************************
123  * Determine if it is @safe to cast e from tfrom to tto.
124  * Params:
125  *      e = expression to be cast
126  *      tfrom = type of e
127  *      tto = type to cast e to
128  * Returns:
129  *      true if @safe
130  */
131 bool isSafeCast(Expression e, Type tfrom, Type tto)
132 {
133     // Implicit conversions are always safe
134     if (tfrom.implicitConvTo(tto))
135         return true;
136 
137     if (!tto.hasPointers())
138         return true;
139 
140     auto tfromb = tfrom.toBasetype();
141     auto ttob = tto.toBasetype();
142 
143     if (ttob.ty == Tclass && tfromb.ty == Tclass)
144     {
145         ClassDeclaration cdfrom = tfromb.isClassHandle();
146         ClassDeclaration cdto = ttob.isClassHandle();
147 
148         int offset;
149         if (!cdfrom.isBaseOf(cdto, &offset) &&
150             !((cdfrom.isInterfaceDeclaration() || cdto.isInterfaceDeclaration())
151                 && cdfrom.classKind == ClassKind.d && cdto.classKind == ClassKind.d))
152             return false;
153 
154         if (cdfrom.isCPPinterface() || cdto.isCPPinterface())
155             return false;
156 
157         if (!MODimplicitConv(tfromb.mod, ttob.mod))
158             return false;
159         return true;
160     }
161 
162     if (ttob.ty == Tarray && tfromb.ty == Tsarray) // https://issues.dlang.org/show_bug.cgi?id=12502
163         tfromb = tfromb.nextOf().arrayOf();
164 
165     if (ttob.ty == Tarray   && tfromb.ty == Tarray ||
166         ttob.ty == Tpointer && tfromb.ty == Tpointer)
167     {
168         Type ttobn = ttob.nextOf().toBasetype();
169         Type tfromn = tfromb.nextOf().toBasetype();
170 
171         /* From void[] to anything mutable is unsafe because:
172          *  int*[] api;
173          *  void[] av = api;
174          *  int[] ai = cast(int[]) av;
175          *  ai[0] = 7;
176          *  *api[0] crash!
177          */
178         if (tfromn.ty == Tvoid && ttobn.isMutable())
179         {
180             if (ttob.ty == Tarray && e.op == EXP.arrayLiteral)
181                 return true;
182             return false;
183         }
184 
185         // If the struct is opaque we don't know about the struct members then the cast becomes unsafe
186         if (ttobn.ty == Tstruct && !(cast(TypeStruct)ttobn).sym.members ||
187             tfromn.ty == Tstruct && !(cast(TypeStruct)tfromn).sym.members)
188             return false;
189 
190         const frompointers = tfromn.hasPointers();
191         const topointers = ttobn.hasPointers();
192 
193         if (frompointers && !topointers && ttobn.isMutable())
194             return false;
195 
196         if (!frompointers && topointers)
197             return false;
198 
199         if (!topointers &&
200             ttobn.ty != Tfunction && tfromn.ty != Tfunction &&
201             (ttob.ty == Tarray || ttobn.size() <= tfromn.size()) &&
202             MODimplicitConv(tfromn.mod, ttobn.mod))
203         {
204             return true;
205         }
206     }
207     return false;
208 }
209 
210 /*************************************************
211  * Check for unsafe use of `.ptr` or `.funcptr`
212  * Params:
213  *      sc = context
214  *      e = expression for error messages
215  *      id = `ptr` or `funcptr`
216  *      flag = DotExpFlag
217  * Returns:
218  *      true if error
219  */
220 bool checkUnsafeDotExp(Scope* sc, Expression e, Identifier id, int flag)
221 {
222     if (!(flag & DotExpFlag.noDeref)) // this use is attempting a dereference
223     {
224         if (id == Id.ptr)
225             return sc.setUnsafe(false, e.loc, "`%s.ptr` cannot be used in `@safe` code, use `&%s[0]` instead", e, e);
226         else
227             return sc.setUnsafe(false, e.loc, "`%s.%s` cannot be used in `@safe` code", e, id);
228     }
229     return false;
230 }