Fix Sysctl() in buffer size autodetection mode (#52824)
authorVadim Zhukov <persgray@gmail.com>
Thu, 10 Jun 2021 19:45:37 +0000 (22:45 +0300)
committerGitHub <noreply@github.com>
Thu, 10 Jun 2021 19:45:37 +0000 (21:45 +0200)
commitb52d276e3c18687a120747e2edfd3ae50679683f
tree6621210a553e1e5ae1b4df34aec5e4a3d04ba0e2
parent2e2d1fb06693b1c44e1fb0ea48ad980cc1cc4500
Fix Sysctl() in buffer size autodetection mode (#52824)

* Fix Sysctl() in buffer size autodetection mode

The code private static unsafe void Sysct() in the
Interop/BSD/System.Native/Interop.Sysctl.cs has two flaws in the case
value == null && len == 0.

First, in case of failure, this code doesn't call FreeHGlobal() on the memory it
allocated right before. I.e., we have pure memory leak.

Second, the "I don't know how much memory is needed, please allocated it by
yourself" idea standing behind value == null && len == 0 assumes the Sysctl()
itself being responsible to avoid ENOMEM condition. It could happen when, for
example, we ask to list all processes in the system: this list could be expanded
between first and second actual sysctl() calls, making the second call fail. So
instead of a single try, we should try to allocate a bit more memory and try
again; not force all our callers to do this themselves, by catching
InvalidOperationException and analyzing it.

Fixes #52823

* add missing IntPtr <-> int casts
src/libraries/Common/src/Interop/BSD/System.Native/Interop.Sysctl.cs