Skip to content

Commit c5cbb03

Browse files
committed
Fix NRE in namespace function & removing initializer data field when not all references are removed
1 parent 1770f1f commit c5cbb03

2 files changed

Lines changed: 23 additions & 3 deletions

File tree

Confuser.Core/Project/Patterns/NamespaceFunction.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,13 @@ public override object Evaluate(IDnlibDef definition) {
2929
if (type == null)
3030
type = ((IMemberDef)definition).DeclaringType;
3131

32+
if (type == null)
33+
return false;
34+
3235
while (type.IsNested)
3336
type = type.DeclaringType;
3437

35-
return type != null && Regex.IsMatch(type.Namespace, ns);
38+
return type != null && Regex.IsMatch(type.Namespace ?? "", ns);
3639
}
3740
}
3841
}

Confuser.Protections/Constants/EncodePhase.cs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,10 +215,25 @@ void UpdateReference(CEContext moduleCtx, TypeSig valueType, List<Tuple<MethodDe
215215
}
216216
}
217217

218+
void RemoveDataFieldRefs(ConfuserContext context, HashSet<FieldDef> dataFields, HashSet<Instruction> fieldRefs) {
219+
foreach (var type in context.CurrentModule.GetTypes())
220+
foreach (var method in type.Methods.Where(m => m.HasBody)) {
221+
foreach (var instr in method.Body.Instructions)
222+
if (instr.Operand is FieldDef && !fieldRefs.Contains(instr))
223+
dataFields.Remove((FieldDef)instr.Operand);
224+
}
225+
226+
foreach (var fieldToRemove in dataFields) {
227+
fieldToRemove.DeclaringType.Fields.Remove(fieldToRemove);
228+
}
229+
}
230+
218231
void ExtractConstants(
219232
ConfuserContext context, ProtectionParameters parameters, CEContext moduleCtx,
220233
Dictionary<object, List<Tuple<MethodDef, Instruction>>> ldc,
221234
Dictionary<byte[], List<Tuple<MethodDef, Instruction>>> ldInit) {
235+
var dataFields = new HashSet<FieldDef>();
236+
var fieldRefs = new HashSet<Instruction>();
222237
foreach (MethodDef method in parameters.Targets.OfType<MethodDef>().WithProgress(context.Logger)) {
223238
if (!method.HasBody)
224239
continue;
@@ -284,8 +299,9 @@ void ExtractConstants(
284299
ldc.Remove(arrLen);
285300
}
286301

287-
if(dataField.DeclaringType!=null)
288-
dataField.DeclaringType.Fields.Remove(dataField);
302+
dataFields.Add(dataField);
303+
fieldRefs.Add(instrs[i - 1]);
304+
289305
var value = new byte[dataField.InitialValue.Length + 4];
290306
value[0] = (byte)(arrLen >> 0);
291307
value[1] = (byte)(arrLen >> 8);
@@ -328,6 +344,7 @@ void ExtractConstants(
328344

329345
context.CheckCancellation();
330346
}
347+
RemoveDataFieldRefs(context, dataFields, fieldRefs);
331348
}
332349

333350
class ByteArrayComparer : IEqualityComparer<byte[]> {

0 commit comments

Comments
 (0)