Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Proposal: Safe pointers #1043

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Feb 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/runtime/BorrowedReference.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace Python.Runtime
{
using System;
/// <summary>
/// Represents a reference to a Python object, that is being lent, and
/// can only be safely used until execution returns to the caller.
/// </summary>
readonly ref struct BorrowedReference
{
readonly IntPtr pointer;
public bool IsNull => this.pointer == IntPtr.Zero;

/// <summary>Gets a raw pointer to the Python object</summary>
public IntPtr DangerousGetAddress()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use a property named Address can be more fit?
Why I have to be warned if I trying use the raw pointer, seems it doesn't make any sense. Or just don't expose the interface and use explicit operator IntPtr instead.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is modeled after SafeHandle class and its DangerousGetHandle method.
The whole point of introducing these references is to get rid of IntPtrs entirely. It should warn you against converting into IntPtr. Maybe Obsolete part is unnecessary as Dangerous sounds like a warning enough. I will remove Obsolete.

=> this.IsNull ? throw new NullReferenceException() : this.pointer;

BorrowedReference(IntPtr pointer)
{
this.pointer = pointer;
}
}
}
39 changes: 39 additions & 0 deletions src/runtime/NewReference.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
namespace Python.Runtime
{
using System;
/// <summary>
/// Represents a reference to a Python object, that is tracked by Python's reference counting.
/// </summary>
[NonCopyable]
ref struct NewReference
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it necessary to limit it as a stack-allocated value? If make it to a normal struct and rename it to PyReference, it can be assigned to a collection and implement the IDisposable for using () usage.
For better usage, a BorrowedReference may be able to promote to a PyReference for using the implict operate overloading.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With [NoCopyable] you won't be able to put it into a collection anyway. And without [NoCopyable] it does not provide any safety guarantees.

Having it as ref struct saves you from adding ref everywhere you take it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But....sometimes I just want to put them into collections...😂

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then you can still do DangerousGetHandle or create a PyObject from them.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But this type also has a purpose for reminding others that it's a reference don't forget to decref it, isn't it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because it must be clear from code, that care is necessary around this scenario.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, as mentioned above, [NoCopyable] would already prevent you from putting an instance into a collection, even if ref were removed. And [NoCopyable] is basically the sole purpose of this change, as if you do

NewReference refA = GetNewReferenceSomehow();
NewReference refB = refA;

Then you already miappropriated refcounts.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe more introduce a type named PyHandle for that?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

emmm, but that make BorrowedReference embarrassed.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@amos402 The idea with PyHandle can be reviewed separately. This PR is only for tracking new vs borrowed references as used in Python documentation for C API.

{
IntPtr pointer;
public bool IsNull => this.pointer == IntPtr.Zero;

/// <summary>Gets a raw pointer to the Python object</summary>
public IntPtr DangerousGetAddress()
=> this.IsNull ? throw new NullReferenceException() : this.pointer;

/// <summary>
/// Returns <see cref="PyObject"/> wrapper around this reference, which now owns
/// the pointer. Sets the original reference to <c>null</c>, as it no longer owns it.
/// </summary>
public PyObject MoveToPyObject()
{
if (this.IsNull) throw new NullReferenceException();

var result = new PyObject(this.pointer);
this.pointer = IntPtr.Zero;
return result;
}
/// <summary>
/// Removes this reference to a Python object, and sets it to <c>null</c>.
/// </summary>
public void Dispose()
{
if (!this.IsNull)
Runtime.XDecref(this.pointer);
this.pointer = IntPtr.Zero;
}
}
}
6 changes: 6 additions & 0 deletions src/runtime/NonCopyableAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Python.Runtime
{
using System;
[AttributeUsage(AttributeTargets.Struct)]
class NonCopyableAttribute : Attribute { }
}
7 changes: 7 additions & 0 deletions src/runtime/Python.Runtime.15.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,13 @@
<PackageReference Include="Microsoft.TargetingPack.NETFramework.v4.5" Version="1.0.1" ExcludeAssets="All" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="NonCopyableAnalyzer" Version="0.5.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />

<PropertyGroup>
Expand Down
3 changes: 3 additions & 0 deletions src/runtime/Python.Runtime.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
</Compile>
<Compile Include="arrayobject.cs" />
<Compile Include="assemblymanager.cs" />
<Compile Include="BorrowedReference.cs" />
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it good for separate these three items to different files? They're small, related, and it make the project files be scattered.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The might get more code later on. Generally, I prefer a type per file approach for anything except delegate types.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or create a folder for them? Just just too far if they sorted by name I thought🤣

<Compile Include="classderived.cs" />
<Compile Include="classbase.cs" />
<Compile Include="classmanager.cs" />
Expand Down Expand Up @@ -119,6 +120,8 @@
<Compile Include="moduleobject.cs" />
<Compile Include="modulepropertyobject.cs" />
<Compile Include="nativecall.cs" />
<Compile Include="NewReference.cs" />
<Compile Include="NonCopyableAttribute.cs" />
<Compile Include="overload.cs" />
<Compile Include="propertyobject.cs" />
<Compile Include="pyansistring.cs" />
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/assemblymanager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ internal static void UpdatePath()
probed.Clear();
for (var i = 0; i < count; i++)
{
IntPtr item = Runtime.PyList_GetItem(list, i);
BorrowedReference item = Runtime.PyList_GetItem(list, i);
string path = Runtime.GetManagedString(item);
if (path != null)
{
Expand Down Expand Up @@ -492,4 +492,4 @@ internal static Type[] GetTypes(Assembly a)
}
}
}
}
}
2 changes: 1 addition & 1 deletion src/runtime/methodbinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth
for (int i = 0; i < pynkwargs; ++i)
{
var keyStr = Runtime.GetManagedString(Runtime.PyList_GetItem(keylist, i));
kwargDict[keyStr] = Runtime.PyList_GetItem(valueList, i);
kwargDict[keyStr] = Runtime.PyList_GetItem(valueList, i).DangerousGetAddress();
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This generates a compiler warning, that uncovers a potentially dangerous pattern, where kwargsDict may contain borrowed references.

}
Runtime.XDecref(keylist);
Runtime.XDecref(valueList);
Expand Down
16 changes: 12 additions & 4 deletions src/runtime/pydict.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,12 +139,20 @@ public PyObject Values()
/// </remarks>
public PyObject Items()
{
IntPtr items = Runtime.PyDict_Items(obj);
if (items == IntPtr.Zero)
var items = Runtime.PyDict_Items(this.obj);
try
{
throw new PythonException();
if (items.IsNull)
{
throw new PythonException();
}

return items.MoveToPyObject();
}
finally
{
items.Dispose();
}
return new PyObject(items);
}


Expand Down
8 changes: 5 additions & 3 deletions src/runtime/runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1509,6 +1509,8 @@ internal static IntPtr PyUnicode_FromString(string s)
return PyUnicode_FromUnicode(s, s.Length);
}

internal static string GetManagedString(in BorrowedReference borrowedReference)
=> GetManagedString(borrowedReference.DangerousGetAddress());
/// <summary>
/// Function to access the internal PyUnicode/PyString object and
/// convert it to a managed string with the correct encoding.
Expand Down Expand Up @@ -1591,7 +1593,7 @@ internal static bool PyDict_Check(IntPtr ob)
internal static extern IntPtr PyDict_Values(IntPtr pointer);

[DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr PyDict_Items(IntPtr pointer);
internal static extern NewReference PyDict_Items(IntPtr pointer);

[DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr PyDict_Copy(IntPtr pointer);
Expand Down Expand Up @@ -1631,13 +1633,13 @@ internal static IntPtr PyList_New(long size)
[DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr PyList_AsTuple(IntPtr pointer);

internal static IntPtr PyList_GetItem(IntPtr pointer, long index)
internal static BorrowedReference PyList_GetItem(IntPtr pointer, long index)
{
return PyList_GetItem(pointer, new IntPtr(index));
}

[DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr PyList_GetItem(IntPtr pointer, IntPtr index);
private static extern BorrowedReference PyList_GetItem(IntPtr pointer, IntPtr index);

internal static int PyList_SetItem(IntPtr pointer, long index, IntPtr value)
{
Expand Down