Search code examples
c#.netazureazure-web-app-servicegdi

Making gdi32.dll function calls in Azure Web App - supported?


Trying to make some basic calls to gdi32.dll functions from C# after publishing a Azure Web App and I'm having lots of problems. Is it fully supported or is there a workaround / config change I can make?

The pointers below all return non-zero values when run in Visual Studio on a standard setup, but they return 0 when running in Azure.

Created a basic ASP.NET Web Forms project and added the blow to the codebehind of Default.aspx to test:

[DllImport("gdi32.dll")]
private static extern IntPtr CreatePen(int enPenStyle, int nWidth, uint crColor);

[DllImport("gdi32.dll")]
private static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);

[DllImport("gdi32.dll")]
private static extern bool MoveToEx(IntPtr hdc, int X, int Y, IntPtr lpPoint);

[DllImport("gdi32.dll")]
private static extern bool LineTo(IntPtr hdc, int nXEnd, int nYEnd);

[DllImport("gdi32.dll")]
private static extern bool DeleteObject([In] IntPtr hObject);


protected void Page_Load(object sender, EventArgs e)
{
    using (Bitmap bitmap = new Bitmap(100, 100))
    {
        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            IntPtr hdc = graphics.GetHdc();
            IntPtr pen = CreatePen(0, (int)2, (uint)0);
            IntPtr hObject = SelectObject(hdc, pen);

            DeleteObject(hObject);
            DeleteObject(pen);
            graphics.ReleaseHdc();

            Response.Write(string.Format("HDC handle: {0}", hdc));
            Response.Write("<br/>");
            Response.Write(string.Format("CreatePen pen: {0}", hObject));
            Response.Write("<br/>");
            Response.Write(string.Format("SelectObject returned: {0}", hObject));
        }
    }
}      

Solution

  • Most GDI calls are explicitly blocked by the Azure App Service sandbox, so the erroneous behavior you're seeing is expected. There are no workarounds, unfortunately.

    You can find more information about the sandbox and the reasoning behind this limitation here: https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox

    For the sake of radical attack surface area reduction, the sandbox prevents almost all of the Win32k.sys APIs from being called, which practically means that most of User32/GDI32 system calls are blocked. For most applications this is not an issue since most Azure Web Apps do not require access to Windows UI functionality (they are web applications after all).

    Some exceptions are made to enable popular PDF generation libraries to work. See the link above for more details.