michl2007
michl2007

Reputation: 15

Access Denied when initialize Disk

I have following code:

if (APartitionStyle = 0) then //mbr
  begin
    hDevice := CreateFile(
                            PChar(ADisk),
                            GENERIC_WRITE and GENERIC_READ,
                            FILE_SHARE_WRITE and FILE_SHARE_READ,
                            nil,
                            OPEN_EXISTING,
                            0,
                            0);

    error := SysErrorMessage(GetLastError);

    if (hDevice = INVALID_HANDLE_VALUE) then
    begin
      error := SysErrorMessage(GetLastError);
      result := error;
    end;

    dwIoControlCode := IOCTL_DISK_CREATE_DISK;

    dsk.PartitionStyle := PARTITION_STYLE_MBR;
    dsk.mbr.Signature := Random(9999);

    lpInBuffer := @dsk;
    nInBufferSize := sizeof(CREATE_DISK);
    lpOutBuffer := nil;
    nOutBufferSize := 0;
    lpOverlapped := nil;

    bresult := DeviceIOControl(
                                hDevice,
                                dwIoControlCode,
                                lpInBuffer,
                                nInBufferSize,
                                lpOutBuffer,
                                nOutBufferSize,
                                lpBytesReturned,
                                lpOverlapped);

    if not bresult then
    begin
      error := SysErrorMessage(GetLastError);
      result := error;
    end;

I have executed the code as administrator or system and as user (with admin privilegs).

I have read something like: Driver is locked. Is there something missing in the code?

The handle is successfully created. On DeviceIOControl I get an error "Access Denied".

Upvotes: 1

Views: 192

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598029

You are passing incorrect values to CreateFile(). You are using the and operator to combine bit flags:

hDevice := CreateFile(
                        PChar(ADisk),
                        GENERIC_WRITE and GENERIC_READ, { = 0 ! }
                        FILE_SHARE_WRITE and FILE_SHARE_READ, { = 0 ! }
                        nil,
                        OPEN_EXISTING,
                        0,
                        0);

You need to use the or operator instead:

hDevice := CreateFile(
                        PChar(ADisk),
                        GENERIC_WRITE or GENERIC_READ, { = $C0000000 ! }
                        FILE_SHARE_WRITE or FILE_SHARE_READ, { = $00000003 ! }
                        nil,
                        OPEN_EXISTING,
                        0,
                        0);

Upvotes: 3

Related Questions