none
P/Invoke AdjustTokenPrivileges() RRS feed

  • Question

  • I'm trying to get "SeDebugPrivilege" for my app but I keep getting this "PInvokeStackImbalance" MDA on the bold code line...

    [DllImport("advapi32.dll", SetLastError = true)]
                [return: MarshalAs(UnmanagedType.Bool)]
                private static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges, TOKEN_PRIVILEGES NewState, int BufferLength, out TOKEN_PRIVILEGES OldState, out int ReturnLength);
    
                public static bool ChangePrivilege(IntPtr token, string privilegeName, bool enablePrivilege)
                {
                    TOKEN_PRIVILEGES tp;
                    LUID luid;
                    TOKEN_PRIVILEGES tpPrevious;
                    TOKEN_PRIVILEGES tpNull;
                    int buffer = Marshal.SizeOf(typeof(TOKEN_PRIVILEGES));
                    int bufferNull;
    
                    if (!LookupPrivilegeValue(null, privilegeName, out luid))
                    {
                        return false;
                    }
    
                    tp.PrivilegeCount = 1;
                    tp.Luid = luid;
                    tp.Attributes = 0;
    
                    if (!AdjustTokenPrivileges(token, false, tp, Marshal.SizeOf(typeof(TOKEN_PRIVILEGES)), out tpPrevious, out buffer))
                    {
                        return false;
                    }
    
                    tpPrevious.PrivilegeCount = 1;
                    tpPrevious.Luid = luid;
    
                    if (enablePrivilege)
                    {
                        tpPrevious.Attributes |= SE_PRIVILEGE_ENABLED;
                    }
    
                    else
                    {
                        tpPrevious.Attributes ^= (SE_PRIVILEGE_ENABLED & tpPrevious.Attributes);
                    }
    
                    if (!AdjustTokenPrivileges(token, false, tpPrevious, Marshal.SizeOf(typeof(TOKEN_PRIVILEGES)), out tpNull, out bufferNull))
                    {
                        return false;
                    }
                    return true;
                }

    "A call to PInvoke function 'DebugPrivileges!DebugPrivileges.NativeFunctions+Privileges::AdjustTokenPrivileges' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature."

    Aaron Chapman

    • Moved by Leo Liu - MSFT Friday, March 30, 2012 9:14 AM Moved for better support. (From:Visual C# General)
    Friday, March 30, 2012 1:22 AM

Answers

All replies