Skip to content

Commit efabeba

Browse files
committed
Add a safeguard during serialization
1 parent 3998941 commit efabeba

File tree

1 file changed

+31
-16
lines changed

1 file changed

+31
-16
lines changed

src/runtime/runtime_data.cs

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -89,22 +89,37 @@ internal static void Stash()
8989

9090
IFormatter formatter = CreateFormatter();
9191
var ms = new MemoryStream();
92-
trace("serialization start");
93-
formatter.Serialize(ms, runtimeStorage);
94-
trace("serialization done");
95-
96-
Debug.Assert(ms.Length <= int.MaxValue);
97-
byte[] data = ms.GetBuffer();
98-
// TODO: use buffer api instead
99-
IntPtr mem = PyMem_Malloc(ms.Length + IntPtr.Size);
100-
Marshal.WriteIntPtr(mem, (IntPtr)ms.Length);
101-
Marshal.Copy(data, 0, mem + IntPtr.Size, (int)ms.Length);
102-
103-
ClearCLRData();
104-
IntPtr capsule = PyCapsule_New(mem, null, IntPtr.Zero);
105-
PySys_SetObject("clr_data", capsule);
106-
// Let the dictionary own the reference
107-
XDecref(capsule);
92+
IntPtr capsule = IntPtr.Zero;
93+
try
94+
{
95+
trace("serialization start");
96+
formatter.Serialize(ms, runtimeStorage);
97+
trace("serialization done");
98+
99+
Debug.Assert(ms.Length <= int.MaxValue);
100+
byte[] data = ms.GetBuffer();
101+
// TODO: use buffer api instead
102+
IntPtr mem = PyMem_Malloc(ms.Length + IntPtr.Size);
103+
Marshal.WriteIntPtr(mem, (IntPtr)ms.Length);
104+
Marshal.Copy(data, 0, mem + IntPtr.Size, (int)ms.Length);
105+
106+
ClearCLRData();
107+
capsule = PyCapsule_New(mem, null, IntPtr.Zero);
108+
PySys_SetObject("clr_data", capsule);
109+
110+
}
111+
catch(Exception e)
112+
{
113+
trace($"Serialization failed! No runtime data will be saved. \n {e.Message} :: {e.StackTrace}");
114+
}
115+
finally
116+
{
117+
if (capsule != IntPtr.Zero)
118+
{
119+
// Let the dictionary own the reference
120+
XDecref(capsule);
121+
}
122+
}
108123
}
109124

110125
internal static void RestoreRuntimeData()

0 commit comments

Comments
 (0)